def halo_gas(halo):
    """
    Generate an image (returns a pixel grid) for the gas in the halo
    specified.
    """

    baryonic_ids_in_halo_at_z0 = np.unique(
        np.concatenate([
            baryons_end.gas_ids[baryons_end.gas_halos == halo],
            baryons_end.star_ids[baryons_end.star_halos == halo],
        ]))

    _, mask, _ = np.intersect1d(
        baryons_ini.gas_ids,
        baryonic_ids_in_halo_at_z0,
        assume_unique=True,
        return_indices=True,
    )

    c = np.concatenate([
        baryons_ini.gas_coordinates[mask],
        np.array([[0.0, 0.0, 0.0], [50000.0, 50000.0, 50000.0]]),
    ])
    hsml = np.concatenate([hsml_ini_gas[mask], [0.0, 0.0]])

    qv = QuickView(c, hsml=hsml, **kwargs).get_image()

    return qv
def lagrangian_region(lr):
    """
    Generate an image (returns a pixel grid) for the gas in the lagrangian region
    specified.
    """

    mask = data.lagrangian_regions == lr

    c = np.concatenate([
        baryons_ini.gas_coordinates[mask],
        np.array([[0.0, 0.0, 0.0], [50000.0, 50000.0, 50000.0]]),
    ])
    hsml = np.concatenate([hsml_ini_gas[mask], [0.0, 0.0]])

    qv = QuickView(c, hsml=hsml, **kwargs).get_image()

    return qv
Esempio n. 3
0
def generate_views(data: SimulationData, res=2048) -> Tuple[np.ndarray]:
    """
    Generates the views on the data from py-sphviewer.

    Returns the overall image for the whole box and then a zoomed region.
    """

    qv_all = QuickView(
        data.coordinates,
        data.masses,
        r="infinity",
        plot=False,
        xsize=res,
        ysize=res,
        logscale=False,
        p=0,
        np=48,
    )
    zoomed_res = (res * 6) // 10
    mask = np.logical_and(
        np.logical_and(
            data.coordinates[0] > (data.boxsize / 2 - 4 - 20),
            data.coordinates[0] < (data.boxsize / 2 + 6 - 20),
        ),
        np.logical_and(
            data.coordinates[1] > (data.boxsize / 2 - 3.5 - 20),
            data.coordinates[1] < (data.boxsize / 2 + 6.5 - 20),
        ),
    )
    qv_zoomed = QuickView(
        data.coordinates.T[mask].T,
        data.masses[mask],
        r="infinity",
        plot=False,
        xsize=zoomed_res,
        ysize=zoomed_res,
        logscale=False,
        np=48,
    )

    return qv_all.get_image(), qv_zoomed.get_image()
Esempio n. 4
0
    gas_coordinates[:, 0] < largest_center[0] + distance_to_plot,
    gas_coordinates[:, 1] > largest_center[1] - distance_to_plot,
    gas_coordinates[:, 1] < largest_center[1] + distance_to_plot,
    gas_coordinates[:, 2] > largest_center[2] - distance_to_plot,
    gas_coordinates[:, 2] < largest_center[2] + distance_to_plot,
])

#%%
gas_coordinates_around_center = gas_coordinates[mask]

#%%
# First we'll set up some plotting commands
kwargs = dict(xsize=2048, ysize=2048, r="infinity", logscale=False, plot=False)

#%%
qv_nomass = QuickView(gas_coordinates_around_center, **kwargs)

#%%
fig, ax = plt.subplots()
ax.axis("off")
ax.imshow(
    qv_nomass.get_image(),
    norm=LogNorm(),
    extent=[
        -distance_to_plot, distance_to_plot, -distance_to_plot,
        distance_to_plot
    ],
)

# Plot the virial radius of the cluster on top as a check
circle = plt.Circle((0, 0),
Esempio n. 5
0
    def get_normalized_image(image):
        image = (image-np.min(image))/(np.max(image)-np.min(image))
        return image

    pos1 = np.zeros([5000, 3])
    pos2 = np.zeros([10000, 3])

    pos1[:, 0:2] = -1+2*np.random.rand(5000, 2)
    pos2[:, 0:2] = -1+2*np.random.rand(10000, 2)

    r2 = np.sqrt(pos2[:, 0]**2+pos2[:, 1]**2)
    k2, = np.where(r2 < 0.5)
    pos2 = pos2[k2, :]

    qv1 = QuickView(pos1.T, np.ones(len(pos1)),
                    r='infinity', logscale=False, plot=False,
                    extent=[-1, 1, -1, 1], x=0, y=0, z=0)
    qv2 = QuickView(pos2.T, np.ones(len(pos2)),
                    r='infinity', logscale=False, plot=False,
                    extent=[-1, 1, -1, 1], x=0, y=0, z=0)

    image1 = cm.gist_heat(get_normalized_image(qv1.get_image()))
    image2 = cm.gist_stern(get_normalized_image(qv2.get_image()))

    fig = plt.figure(1, figsize=(10, 5))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)

    blend = Blend(image1, 1.0*image2)
    screen = blend.Screen()
    overlay = blend.Overlay()
Esempio n. 6
0
    def read_galaxy(self, itype, gn, sgn, centre, load_region_length):

        p, t = defineprojection(projection[indices[n]])
        data = {}

        eagle_data = EagleSnapshot(
            '/disks/eagle/L0100N1504/REFERENCE/data/snapshot_027_z000p101/snap_027_z000p101.0.hdf5'
        )

        centre *= self.h

        region = np.array([(centre[0] - 0.5 * load_region_length),
                           (centre[0] + 0.5 * load_region_length),
                           (centre[1] - 0.5 * load_region_length),
                           (centre[1] + 0.5 * load_region_length),
                           (centre[2] - 0.5 * load_region_length),
                           (centre[2] + 0.5 * load_region_length)])

        eagle_data.select_region(*region)
        f = h5py.File(
            '/disks/eagle/L0100N1504/REFERENCE/data/snapshot_027_z000p101/snap_027_z000p101.0.hdf5',
            'r')

        constants = f['Constants']
        Mpc = constants.attrs['CM_PER_MPC']
        SMass = constants.attrs["SOLAR_MASS"]
        for att in ['GroupNumber', 'Coordinates', 'Mass']:
            if parttype == 1 and att == 'Mass':
                data[att] = np.ones(len(data['GroupNumber'])) * SMass * 9.7e6
                continue
            tmp = eagle_data.read_dataset(itype, att)
            cgs = f['PartType%i/%s' %
                    (itype, att)].attrs.get('CGSConversionFactor')
            aexp = f['PartType%i/%s' %
                     (itype, att)].attrs.get('aexp-scale-exponent')
            hexp = f['PartType%i/%s' %
                     (itype, att)].attrs.get('h-scale-exponent')
            data[att] = np.multiply(tmp,
                                    cgs * self.a**aexp * self.h**hexp,
                                    dtype='f8')

            if att == 'Coordinates':
                centre2 = np.multiply(centre,
                                      cgs / Mpc * self.a**aexp * self.h**hexp)
                galx = np.zeros(len(myData))
                galy = np.zeros(len(myData))
                galz = np.zeros(len(myData))
                j = 1
                print myData[1][2], cgs, Mpc, self.a, aexp, self.h, hexp
                print np.multiply(myData[1][2],
                                  cgs / Mpc * self.a**aexp * self.h**hexp)
                for i in range(
                        1,
                        len(myData)):  #Only if first galaxy in list is centre
                    galx[j] = np.multiply(
                        myData[i][2], cgs / Mpc * self.a**aexp * self.h**hexp *
                        self.h) - centre2[0]
                    galy[j] = np.multiply(
                        myData[i][3], cgs / Mpc * self.a**aexp * self.h**hexp *
                        self.h) - centre2[1]
                    galz[j] = np.multiply(
                        myData[i][4], cgs / Mpc * self.a**aexp * self.h**hexp *
                        self.h) - centre2[2]
                    j += 1
                print galx, galy, galz
                x1, y1, x2, y2, x3, y3, l1, l2, l3, l4, l5, l6 = find_galaxy(
                    projection[indices[n]], galx, galy, galz)

        f.close()

        mask = (data['GroupNumber'] == gn)
        for att in data.keys():
            data[att] = data[att][mask]
        for i in range(3):
            if i == 0:
                stringtitle = parttype_string + " for p=0 and t=0" + " at snapshot 27 with redshift z = 0.1"
                x = x1
                y = y1
                xlabel = l1
                ylabel = l2
            if i == 1:
                p = p + 90
                stringtitle = parttype_string + " for p=90 and t=0" + " at snapshot 27 with redshift z = 0.1"
                x = x2
                y = y2
                xlabel = l3
                ylabel = l4
            if i == 2:
                stringtitle = parttype_string + " for p=0 and t=90" + " at snapshot 27 with redshift z = 0.1"
                t = t + 90
                p = p - 90
                x = x3
                y = y3
                xlabel = l5
                ylabel = l6
            qv_parallel = QuickView(data['Coordinates'] / Mpc,
                                    data['Mass'] / SMass,
                                    r='infinity',
                                    plot=False,
                                    p=p,
                                    t=t,
                                    x=centre2[0],
                                    y=centre2[1],
                                    z=centre2[2],
                                    max_hsml=max_hsml,
                                    extent=[-0.5, 0.5, -0.5, 0.5])

            plt.imshow(qv_parallel.get_image(),
                       extent=qv_parallel.get_extent(),
                       cmap='viridis',
                       origin='lower')
            plt.colorbar()
            color = ['r', 'k', 'm', 'w']
            plt.title(stringtitle)
            plt.xlabel(xlabel)
            print p, t, x, y
            plt.ylabel(ylabel)
            plt.xlim(-0.21, 0.21)
            plt.ylim(-0.21, 0.21)
            #plt.clim(5,)
            #plt.scatter(x, y, facecolors = 'none', color = 'r')
            marker = ['o', 's', '^', 'D']
            for j in range(len(x)):
                plt.scatter(x[j],
                            y[j],
                            marker=marker[j],
                            facecolors='none',
                            color='r',
                            label=myData[j][5])
            plt.legend(bbox_to_anchor=(-0.3, -0.15), loc=3, prop={'size': 8})

            plt.show()
#%%
one_image = reduce(darker_colour, images)

#%%
fig, ax = plt.subplots(figsize=(8, 8))
ax.axis("off")
fig.subplots_adjust(0, 0, 1, 1)

ax.imshow(one_image, origin="lower")
fig.savefig("lagrangian_regions_combined_secondset.png", dpi=300)

#%% [markdown]
# We need to make the dark matter for the background!

#%%
qv = QuickView(data.snapshot_end.dark_matter.coordinates, **kwargs)

#%%
plt.imshow(qv.get_image, cmap="bone", norm=LogNorm())
plt.gca().axis("off")

#%% [markdown]
# On top of everyone's favourite dark matter image, we also want to show the
# halo virial radii.

#%%
with open(f"{directory}/lt/halo_catalogue.pickle", "rb") as handle:
    halo_catalogue = load(handle)

#%%
halo_masses = (sum([
Esempio n. 8
0
        #     y = t['Y'][gas][xmask][ymask]
        #
        #     return x, y
        #
        # x, y = pos(box[l])
        # axs[l, k].scatter(x, y, c='grey', s=0.05, marker='.')

        x = np.array(t['X'][gas])
        y = np.array(t['Y'][gas])
        z = np.array(t['Z'][gas])
        pos = np.column_stack((x, y, z))

        qv = QuickView(pos,
                       r='infinity',
                       plot=False,
                       x=0,
                       y=0,
                       z=0,
                       extent=[-110, 110, -110, 110])
        img = qv.get_image()
        extent = qv.get_extent()

        im = axs[l, k].imshow(img, extent=extent, cmap='twilight')
        #if (k == 2): fig.colorbar(im, ax=axs[l, k], pad=0.1)

        axs[l, k].tick_params(left=False,
                              right=False,
                              top=False,
                              bottom=False,
                              length=2,
                              tickdir='in',
Esempio n. 9
0
def render_luminosity_map(
    parts_data,
    luminosity,
    filtname,
    ang_momentum,
    halo_data,
    index,
    output_path,
    simulation_name,
):
    pos_parts = parts_data[:, 0:3].copy()

    face_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum)
    edge_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum,
                                                          axis="y")

    pos_face_on = np.matmul(face_on_rotation_matrix, pos_parts.T)
    pos_face_on = pos_face_on.T
    pos_edge_on = np.matmul(edge_on_rotation_matrix, pos_parts.T)
    pos_edge_on = pos_edge_on.T

    hsml_parts = parts_data[:, 7]

    r_limit = 5 * halo_data.half_mass_radius_star[index]
    r_img = 30.0
    if r_limit < r_img:
        r_img = r_limit
    xmin = -r_img
    ymin = -r_img
    xmax = r_img
    ymax = r_img

    rcParams.update(params)
    fig = plt.figure()
    ax = plt.subplot(1, 2, 1)

    ###### plot one side ########################
    qv = QuickView(
        pos_face_on,
        mass=luminosity,
        hsml=hsml_parts,
        logscale=True,
        plot=False,
        r="infinity",
        p=0,
        t=0,
        extent=[xmin, xmax, ymin, ymax],
        x=0,
        y=0,
        z=0,
    )
    img = qv.get_image()
    ext = qv.get_extent()
    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("y [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    img = get_normalized_image(img, vmin=img.max() - 2.3)
    ax.imshow(img, cmap="magma", extent=ext, vmin=img.max() - 2.3)
    ax.autoscale(False)

    ###### plot another side ########################
    ax = plt.subplot(1, 2, 2)
    qv = QuickView(
        pos_edge_on,
        mass=luminosity,
        hsml=hsml_parts,
        logscale=True,
        plot=False,
        r="infinity",
        p=90,
        t=0,
        extent=[xmin, xmax, ymin, ymax],
        x=0,
        y=0,
        z=0,
    )
    img = qv.get_image()
    ext = qv.get_extent()
    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("z [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    img = get_normalized_image(img, vmin=img.max() - 2.3)
    ims = ax.imshow(img, cmap="magma", vmin=img.max() - 2.3, extent=ext)
    ax.autoscale(False)

    cbar_ax = fig.add_axes([0.86, 0.22, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ims, ticks=[4, 6, 8, 10, 12], cax=cbar_ax)
    cb.set_label(label=r"$\log_{10}$ $\Sigma$ [Jy/kpc$^{2}$]", labelpad=0.5)

    outfile = (f"{output_path}/galaxy_%s_map_%i_" % (filtname, index) +
               simulation_name + ".png")
    fig.savefig(outfile, dpi=150)
    plt.close("all")

    return
Esempio n. 10
0
def plot_galaxy(parts_data, parttype, ang_momentum, halo_data, index,
                output_path, simulation_name):
    # partsDATA contains particles data and is structured as follow
    # [ (:3)Position[Mpc]: (0)X | (1)Y | (2)Z ]
    if parttype == 4:
        cmap = plt.cm.magma
    if parttype == 0:
        cmap = plt.cm.viridis

    pos_parts = parts_data[:, 0:3].copy()
    face_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum,
                                                          axis="z")
    edge_on_rotation_matrix = rotation_matrix_from_vector(ang_momentum,
                                                          axis="y")

    pos_face_on = np.matmul(face_on_rotation_matrix, pos_parts.T)
    pos_face_on = pos_face_on.T
    pos_edge_on = np.matmul(edge_on_rotation_matrix, pos_parts.T)
    pos_edge_on = pos_edge_on.T

    hsml_parts = parts_data[:, 7]
    mass = parts_data[:, 3]

    r_limit = 5 * halo_data.half_mass_radius_star[index]
    r_img = 30.0
    if r_limit < r_img:
        r_img = r_limit
    xmin = -r_img
    ymin = -r_img
    xmax = r_img
    ymax = r_img

    rcParams.update(params)
    fig = plt.figure()
    ax = plt.subplot(1, 2, 1)

    if parttype == 4:
        title = "Stellar component"
    if parttype == 0:
        title = "HI+H2 gas"
    ax.set_title(title)

    ###### plot one side ########################
    qv = QuickView(
        pos_face_on,
        mass=mass,
        hsml=hsml_parts,
        logscale=True,
        plot=False,
        r="infinity",
        p=0,
        t=0,
        extent=[xmin, xmax, ymin, ymax],
        x=0,
        y=0,
        z=0,
    )
    img = qv.get_image()
    ext = qv.get_extent()
    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("y [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    img = get_normalized_image(img)
    ax.imshow(img, cmap=cmap, extent=ext)
    ax.autoscale(False)

    ###### plot another side ########################
    ax = plt.subplot(1, 2, 2)
    if parttype == 4:
        kappa = halo_data.kappa_co[index]
        mass_galaxy = halo_data.log10_stellar_mass[index]
        ac = halo_data.axis_ca[index]
        cb = halo_data.axis_cb[index]
        ba = halo_data.axis_ba[index]
        title = r" $\kappa_{\mathrm{co}} = $%0.2f" % (kappa)
        title += " - $\log_{10}$ $M_{*}/M_{\odot} = $%0.2f" % (mass_galaxy)
        title += " \n c/a = %0.2f," % (ac)
        title += " c/b = %0.2f," % (cb)
        title += " b/a = %0.2f" % (ba)
    if parttype == 0:
        kappa = halo_data.gas_kappa_co[index]
        mass_galaxy = halo_data.log10_gas_mass[index]
        ac = halo_data.gas_axis_ca[index]
        cb = halo_data.gas_axis_cb[index]
        ba = halo_data.gas_axis_ba[index]
        title = r" $\kappa_{\mathrm{co}} = $%0.2f" % (kappa)
        title += " - $\log_{10}$ $M_{gas}/M_{\odot} = $%0.2f" % (mass_galaxy)
        title += " \n c/a = %0.2f," % (ac)
        title += " c/b = %0.2f," % (cb)
        title += " b/a = %0.2f" % (ba)
    ax.set_title(title)

    qv = QuickView(
        pos_edge_on,
        mass=mass,
        hsml=hsml_parts,
        logscale=True,
        plot=False,
        r="infinity",
        p=0,
        t=0,
        extent=[xmin, xmax, ymin, ymax],
        x=0,
        y=0,
        z=0,
    )
    img = qv.get_image()
    ext = qv.get_extent()
    ax.tick_params(labelleft=True, labelbottom=True, length=0)
    plt.xlabel("x [kpc]")
    plt.ylabel("z [kpc]")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    img = get_normalized_image(img)
    ims = ax.imshow(img, cmap=cmap, extent=ext)
    ax.autoscale(False)

    cbar_ax = fig.add_axes([0.86, 0.22, 0.018, 0.5])
    cbar_ax.tick_params(labelsize=15)
    cb = plt.colorbar(ims, ticks=[4, 6, 8, 10, 12], cax=cbar_ax)
    cb.set_label(label=r"$\log_{10}$ $\Sigma$ [M$_{\odot}$/kpc$^{2}$]",
                 labelpad=0.5)

    if parttype == 0:
        outfile = f"{output_path}/galaxy_gas_%i_" % (
            index) + simulation_name + ".png"
    if parttype == 4:
        outfile = f"{output_path}/galaxy_stars_%i_" % (
            index) + simulation_name + ".png"
    fig.savefig(outfile, dpi=150)
    plt.close("all")

    return
Esempio n. 11
0
    os.environ["MKL_NUM_THREADS"] = "1"
    os.environ["NUMEXPR_NUM_THREADS"] = "1"
    os.environ["OMP_NUM_THREADS"] = "1"

    print("Comparing with pySPHViewer")
    coordinates = zeros((number_of_particles, 3))
    coordinates[:, 0] = x
    coordinates[:, 1] = y
    h = 1.778_002 * h  # The kernel_gamma we use.

    t = time()
    qv = QuickView(
        coordinates,
        hsml=h,
        mass=m,
        xsize=res,
        ysize=res,
        r="infinity",
        plot=False,
        logscale=False,
    ).get_image()
    dt_pysphviewer = time() - t
    print(f"pySPHViewer took {dt_pysphviewer} on the same problem.")
    print(f"Note that pySPHViewer is running in single-threaded mode.")

    ratio = dt_us / dt_pysphviewer

    if ratio < 1.0:
        print(f"That makes us {1 / ratio} x faster 😀 ")
    else:
        print(f"That makes pySphviewer {ratio} x faster 😔")
Esempio n. 12
0
#This file contains a few lines as example of
#the use of py-sphviewer.

import h5py
from sphviewer.tools import QuickView

halo = h5py.File('dm_halo.h5py', 'r')
pos = halo['Coordinates'].value

qv = QuickView(pos.T, r='infinity', nb=8)
Esempio n. 13
0
        image = (image-np.min(image))/(np.max(image)-np.min(image))
        return image

    pos1 = np.zeros([5000,3])
    pos2 = np.zeros([10000,3])

    pos1[:,0:2] = -1+2*np.random.rand(5000,2)
    pos2[:,0:2] = -1+2*np.random.rand(10000,2)


    r2 = np.sqrt(pos2[:,0]**2+pos2[:,1]**2)
    k2, = np.where(r2 < 0.5)
    pos2 = pos2[k2,:]

    qv1 = QuickView(pos1.T, np.ones(len(pos1)),
                    r='infinity', logscale=False, plot=False,
                    extent=[-1,1,-1,1], x=0, y=0, z=0)
    qv2 = QuickView(pos2.T, np.ones(len(pos2)),
                    r='infinity', logscale=False, plot=False,
                    extent=[-1,1,-1,1], x=0, y=0, z=0)


    image1 = cm.gist_heat(get_normalized_image(qv1.get_image()))
    image2 = cm.gist_stern(get_normalized_image(qv2.get_image()))


    fig = plt.figure(1, figsize=(10,5))
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)

    blend = Blend(image1, 1.0*image2)