def getimage(data, poss, temp, mass, hsml, num, norm, cmap):

    print('There are', poss.shape[0], 'gas particles in the region')

    # Set up particle objects
    P1 = sph.Particles(poss, mass=temp * mass, hsml=hsml)
    P2 = sph.Particles(poss, mass=mass, hsml=hsml)

    # Initialise the scene
    S1 = sph.Scene(P1)
    S2 = sph.Scene(P2)

    i = data[num]
    i['xsize'] = 3840
    i['ysize'] = 2160
    i['roll'] = 0
    S1.update_camera(**i)
    S2.update_camera(**i)
    R1 = sph.Render(S1)
    R2 = sph.Render(S2)
    R1.set_logscale()
    R2.set_logscale()
    img1 = R1.get_image()
    img2 = R2.get_image()
    img = img1 - img2

    vmax = 7.5
    vmin = 3.5
    print("gas temperature", np.min(img), np.max(img))

    # Convert images to rgb arrays
    rgb = cmap(norm(img))

    return rgb, R1.get_extent()
示例#2
0
def getimage(data, poss, mass, hsml, num, max_pixel, cmap, Type="gas"):

    print('There are', poss.shape[0], 'gas particles in the region')
    
    # Set up particle objects
    P = sph.Particles(poss, mass=mass, hsml=hsml)

    print(np.min(mass))

    # Initialise the scene
    S = sph.Scene(P)

    i = data[num]
    i['xsize'] = 5000
    i['ysize'] = 5000
    i['roll'] = 0
    S.update_camera(**i)
    R = sph.Render(S)
    R.set_logscale()
    img = R.get_image()

    if Type == "gas":
        vmax =11
        vmin = 6
        print("gas", np.max(img))
        # Convert images to rgb arrays
        rgb = cmap(get_normalised_image(img, vmin=vmin, vmax=vmax))
    else:
        vmax = 21.6
        vmin = 15.0
        print("star", np.min(img[img != 0]), np.max(img))
        rgb = img

    return rgb, R.get_extent()
def getimage_stars(data, poss, mass, hsml, num, max_pixel, cmap, Type="gas"):
    print('There are', poss.shape[0], 'gas particles in the region')

    # Set up particle objects
    P = sph.Particles(poss, mass=mass, hsml=hsml)

    print(np.min(mass))

    # Initialise the scene
    S = sph.Scene(P)

    i = data[num]
    i['xsize'] = 3840
    i['ysize'] = 2160
    i['roll'] = 0
    S.update_camera(**i)
    R = sph.Render(S)
    R.set_logscale()
    img = R.get_image()

    img = ndimage.gaussian_filter(img, sigma=(3, 3), order=0)

    if Type == "gas":
        vmax = 11
        vmin = 6
        print("gas", np.max(img))
    else:
        vmax = 13
        vmin = 7.5
        print("star", np.max(img))

    # Convert images to rgb arrays
    rgb = cmap(get_normalised_image(img, vmin=vmin, vmax=vmax))

    return rgb, R.get_extent()
示例#4
0
def getimage(data, poss, hsml, num, boxsize):

    print('There are', poss.shape[0], 'dark matter particles in the region')

    # Set up particle objects
    P = sph.Particles(poss, mass=np.ones(poss.shape[0]), hsml=hsml)

    # Initialise the scene
    S = sph.Scene(P)

    i = data[num]
    i['xsize'] = int(boxsize / hsml.max())
    i['ysize'] = int(boxsize / hsml.max())
    i['roll'] = 0
    S.update_camera(**i)
    R = sph.Render(S)
    R.set_logscale()
    img = R.get_image()

    vmax = 7
    vmin = 1

    # Get colormaps
    cmap = cmaps.twilight()

    print(img.max())

    # Convert images to rgb arrays
    rgb = cmap(get_normalised_image(img, vmin=vmin, vmax=vmax))

    return rgb, R.get_extent()
示例#5
0
def myplot(x, y, nb=32, xsize=500, ysize=500):
	xmin = np.min(x)
	xmax = np.max(x)
	ymin = np.min(y)
	ymax = np.max(y)

	print xmin, xmax, ymin, ymax

	x0 = (xmin+xmax)/2.
	y0 = (ymin+ymax)/2.

	pos = np.zeros([3, len(x)])
	pos[0,:] = x
	pos[1,:] = y
	w = np.ones(len(x))

	P = sph.Particles(pos, w, nb=nb)
	S = sph.Scene(P)
	S.update_camera(r='infinity', x=x0, y=y0, z=0, xsize=xsize, ysize=ysize)
	R = sph.Render(S)
	R.set_logscale()
	img = R.get_image()
	extent = R.get_extent()
	for i, j in zip(xrange(4), [x0,x0,y0,y0]):
		extent[i] += j
	#print extent
	return img, extent
示例#6
0
def myplot(x, y, nb=32, xsize=500, ysize=500):
    """This function reads in a set of data and smooths it using
       nearest neighbors summing. It then outputs the smoothed data
       with a measure of its extent. This output is then inputed to
       Axes.imshow.
       
       :param: x,y   two columns of data such as particle positions
       :param: nb    smoothing size.
    """
    xmin = np.min(x)
    xmax = np.max(x)
    ymin = np.min(y)
    ymax = np.max(y)

    x0 = (xmin + xmax) / 2.
    y0 = (ymin + ymax) / 2.

    pos = np.zeros([3, len(x)])
    pos[0, :] = x
    pos[1, :] = y
    w = np.ones(len(x))

    P = sph.Particles(pos, w, nb=nb)
    S = sph.Scene(P)
    S.update_camera(r='infinity', x=x0, y=y0, z=0, xsize=xsize, ysize=ysize)
    R = sph.Render(S)
    R.set_logscale()
    img = R.get_image()
    extent = R.get_extent()
    for i, j in zip(xrange(4), [x0, x0, y0, y0]):
        extent[i] += j
    print extent, x0, y0
    return img, extent
def plot_dist(fig, ax,P,coods,cmap,
              vmin=1e-4,vmax=None,extent=300,
              p=0,t=0,roll=0):
 
    C = sph.Camera(x=coods[0], y=coods[1], z=coods[2], 
                   r='infinity', zoom=1,
                   t=t, p=p, roll=roll,
                   extent=[-extent,extent,-extent,extent],
                   xsize=512, ysize=512)
 
    S = sph.Scene(P, Camera=C)
    R = sph.Render(S)
    #R.set_logscale()
    img = R.get_image()
    # img = img / img.mean()

    if vmax is None:    
        vmax = img.max()

    if vmin > vmax:
        print("vmin larger than vmax! Setting lower")
        vmin = img.max() / 10
    print("vmin,vmax:",vmin,vmax)
    
    cNorm  = colors.LogNorm(vmin=vmin,vmax=vmax)
    sm = cm.ScalarMappable(norm=cNorm, cmap=cmap)

    ax.imshow(img, extent=[-extent,extent,-extent,extent],
              cmap=cmap, norm=cNorm)

    return sm,img
def plot_sph(x: pd.Series,
             y: pd.Series,
             w: pd.Series,
             nb=32,
             xsize=1000,
             ysize=1000):
    x_min = np.min(x)
    x_max = np.max(x)
    y_min = np.min(y)
    y_max = np.max(y)
    x0 = np.average((x_min, x_max))
    y0 = np.average((y_min, y_max))

    pos = np.zeros([len(df), 3])
    pos[:, 0] = x
    pos[:, 1] = y
    w = w.to_numpy() * 100

    particles = sph.Particles(pos, mass=w, nb=nb)
    scene = sph.Scene(particles)
    scene.update_camera(r="infinity",
                        x=x0,
                        y=y0,
                        z=0,
                        xsize=xsize,
                        ysize=ysize)
    render = sph.Render(scene)
    render.set_logscale()
    img = render.get_image()
    extent = render.get_extent()
    for i, j in zip(range(4), [x0, x0, y0, y0]):
        extent[i] += j

    return img, extent
示例#9
0
def plot_ledlow_contours(t, world2pixel, ngb=12, xsize=500, ysize=500):
    """ Smooth galaxy positions of Ledlow+ (2005) to get contour lines
        @param t           : astropy.table.Table holding Ledlow data
        @param world2pixel : aplpy.FITSFigure world2pixel function to map
                             RA,dec coordinates to Chandra mosaic pixels
        @param ngb         : number of neighbours to smooth over
        @param xsize, ysize: size of the image (resolution?)
        @return            : img, extent """
    ra = 15 * astropy.coordinates.Angle(t['RAJ2000'].filled(numpy.nan),
                                        unit=u.degree)
    dec = astropy.coordinates.Angle(t['DEJ2000'].filled(numpy.nan),
                                    unit=u.degree)
    ra, dec = world2pixel(ra,
                          dec)  # convert ra, dec to xray mosaic pixel values

    # Perform kernel density estimate
    # https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.stats.gaussian_kde.html
    # X, Y = numpy.mgrid[xmax:xmin:300j, ymin:ymax:3000j]
    # positions = numpy.vstack([X.ravel(), Y.ravel()])
    # values = numpy.vstack([ra, dec])
    # kernel = kde.gaussian_kde(values)
    # Z = numpy.reshape(kernel(positions).T, X.shape)
    # Z /= ((41.1-40.6)*60*(20.025-19.50)*60)

    # pyplot.imshow(numpy.rot90(Z), cmap=pyplot.cm.gist_earth_r,
    #               extent=[xmax, xmin, ymin, ymax])
    # cset = pyplot.contour(X, Y, Z, colors="w",
    #         levels=numpy.array([1,2,3,5,8,10])*Z.max()/10)
    # pyplot.clabel(cset, inline=1, fontsize=10)

    # https://stackoverflow.com/questions/2369492
    xmin, xmax = ra.min(), ra.max()
    ymin, ymax = dec.min(), dec.max()

    x0 = (xmin + xmax) / 2.
    y0 = (ymin + ymax) / 2.

    pos = numpy.zeros([3, len(ra)])
    pos[0, :] = ra
    pos[1, :] = dec
    w = numpy.ones(len(ra))

    P = sphviewer.Particles(pos, w, nb=ngb)
    S = sphviewer.Scene(P)
    S.update_camera(r="infinity", x=x0, y=y0, z=0, xsize=xsize, ysize=ysize)

    R = sphviewer.Render(S)
    img = R.get_image()
    extent = R.get_extent()
    for i, j in zip(xrange(4), [x0, x0, y0, y0]):
        extent[i] += j

    img = 10 * img / numpy.max(img)

    return img, extent
def getimage(data, poss, hsml, num, z, cmap):

    print('There are', poss.shape[0], 'dark matter particles in the region')
    
    # Set up particle objects
    P = sph.Particles(poss, mass=np.ones(poss.shape[0]), hsml=hsml)

    # Initialise the scene
    S = sph.Scene(P)

    i = data[num]
    i['xsize'] = 3840
    i['ysize'] = 2160
    i['roll'] = 0
    S.update_camera(**i)
    print("Scene")
    R = sph.Render(S)
    print("Render")
    R.set_logscale()
    print("Logscale")
    img = R.get_image()
    print("Image")

    print(img.max(),
          np.percentile(img, 99.99),
          np.percentile(img, 95),
          np.percentile(img, 90),
          np.percentile(img, 67.5),
          np.percentile(img, 50))

    vmax = 6.9
    vmin = 0.1

    # # Get colormaps
    # cmap2 = cmr.torch_r(np.linspace(0, 1, 128))
    # cmap3 = cmr.swamp(np.linspace(0, 1, 128))
    #
    # # combine them and build a new colormap
    # colors = np.vstack((cmap2, cmap3))
    # cmap = mcolors.LinearSegmentedColormap.from_list('colormap', colors)

    hex_list = ["#000000", "#590925", "#6c1c55", "#7e2e84", "#ba4051",
                "#f6511d", "#ffb400", "#f7ec59", "#fbf6ac", "#ffffff"]

    #cmap = get_continuous_cmap(hex_list, float_list=None)

    img = ndimage.gaussian_filter(img, sigma=(3, 3), order=0)

    # Convert images to rgb arrays
    rgb = cmap(get_normalised_image(img, vmin=vmin, vmax=vmax))

    return rgb, R.get_extent()
示例#11
0
    def __init__(self,
                 pos,
                 mass=None,
                 hsml=None,
                 nb=None,
                 logscale=True,
                 plot=True,
                 min_hsml=None,
                 max_hsml=None,
                 **kwargs):

        if (mass is None):
            mass = np.ones(len(pos[0, :]))

        if (nb == None):
            self._P = sph.Particles(pos, mass, hsml)
        else:
            self._P = sph.Particles(pos, mass, hsml, nb)

        if ((min_hsml is not None) or (max_hsml is not None)):
            hsml = self.get_hsml()
            if (min_hsml is not None):
                min_hsml = min_hsml
            else:
                min_hsml = np.min(hsml)
            if (max_hsml is not None):
                max_hsml = max_hsml
            else:
                max_hsml = np.max(hsml)

            hsml = np.clip(hsml, min_hsml, max_hsml)
            print 'Limiting smoothing lenght to the range [%.3f,%.3f]' % (
                min_hsml, max_hsml)
            self._P.set_hsml(hsml)

        self._S = sph.Scene(self._P)
        self._S.update_camera(**kwargs)

        self._R = sph.Render(self._S)
        if (logscale):
            self._R.set_logscale()

        self._img = self._R.get_image()
        self._extent = self._R.get_extent()

        if (plot):
            self.imshow(aspect='auto')
            return
        else:
            return
def single_sphere(reg, snap, soft, num, part_type, cmap, vlims, runall=True):

    if runall:
        # Define path
        path = '/cosma/home/dp004/dc-rope1/FLARES/FLARES-1/G-EAGLE_' + reg + '/data'
    
        poss, masses, smls = get_particle_data(path, snap, part_type=part_type, soft=soft)

        # Get the spheres centre
        centre, radius, mindist = spherical_region(path, snap)

        # Cutout particles
        poss, masses, smls = cutout_particles(poss, masses, smls, centre, radius)
    
        print('There are %i particles (type %s) in the region'%(len(masses),part_type))
        
        # Set up particle objects
        P = sph.Particles(poss, mass=masses, hsml=smls)

        # Initialise the scene
        S = sph.Scene(P)


    targets = [[0,0,0]]#,0,0,0,0,0,0]
    
    # Define the box size
    lbox = (15 / 0.677) * 2

    # Define anchors dict for camera parameters
    anchors = {}
    anchors['sim_times'] = [0.0, 'same', 'same', 'same', 'same', 'same', 'same', 'same', 'same']
    anchors['id_frames'] = [0, 90, 180, 270, 360, 450, 540, 630, 720]
    anchors['id_targets'] = [0, 'same', 'same', 'same', 'same', 'same', 'same', 'same', 'same']
    anchors['r'] = [lbox * 3 / 4, 'same', 'same', 'same', 'same', 'same', 'same', 'same', 'same']
    anchors['t'] = [0, 'same', 'same', 'same', 'same', 'same', 'same', 'same', 'same']
    anchors['p'] = [0, 'pass', 'pass', 'pass', 'pass', 'pass', 'pass', 'pass', 360]
    anchors['zoom'] = [1., 'same', 'same', 'same', 'same', 'same', 'same', 'same', 'same']
    anchors['extent'] = [10, 'same', 'same', 'same', 'same', 'same', 'same', 'same', 'same']
    
    # Define the camera trajectory
    data = camera_tools.get_camera_trajectory(targets, anchors)

    for N in np.arange(num*N_block,(num*N_block)+N_block):
        print("N:",N,'| p:',data[N]['p'])

        # Get images
        if runall:
            img, extent = getimage(snap, N, data, part_type=part_type, overwrite=True, P=P, S=S)
        else:
            img, extent = getimage(snap, N, data, part_type=part_type, overwrite=False)


        rgb = apply_cmap(img,cmap,vlims)

        fig = plt.figure(figsize=(16,9), frameon=False)

        ax = fig.add_subplot(111)
    
        # set extent to 16:9 ratio
        ax.set_xlim(extent[0] * 16/9, extent[1] * 16/9)
        
        ax.imshow(rgb, origin='lower', aspect='equal', extent=extent)
        ax.tick_params(axis='both', left=False, top=False, right=False, 
                       bottom=False, labelleft=False, labeltop=False, 
                       labelright=False, labelbottom=False)

        ax.set_facecolor(cmap(0.0)) # (0.95588623, 0.91961077, 0.95812116))
        fname = 'plots/spheres/All/all_parts_animation_reg%s_snap%s_ptype%s_angle%05d.png'%(reg,snap,part_type,N)
        print("Saving:",fname)
        fig.savefig(fname, dpi=300, bbox_inches='tight')
        plt.close(fig)
示例#13
0
def plot_parent(i, P, n, res, centre, z_centre):
    print("i:", i)
    sys.stdout.flush()
    cmap = cmaps.twilight()

    f = modified_sigmoid(i / n, 3)
    L, l = 3300 / 2, 50
    dl = L * (1 - f) + l * f
    R = 16. / 9
    offset = 100
    dx = dl * R
    dy = dl

    ext_x = 3200 / 2
    ext_y = 3200 / 2
    if ext_x > dx: ext_x = dx
    if ext_y > dy: ext_y = dy

    C = sph.Camera(r='infinity',
                   t=0,
                   p=0,
                   roll=0,
                   xsize=res,
                   ysize=res,
                   x=centre,
                   y=centre,
                   z=z_centre,
                   extent=[-ext_x, ext_x, -ext_y, ext_y])

    S = sph.Scene(P, C)
    R = sph.Render(S)
    extent = R.get_extent()
    img = np.log10(R.get_image())
    print(img.max(), img.min())

    fig = plt.figure(figsize=(16, 9))
    ax = fig.add_axes([0, 0, 1, 1])

    # ax.imshow(img, cmap=cmap, vmin=-0.05, vmax=1.2, extent=extent,aspect='equal')
    ax.imshow(img,
              cmap=cmap,
              vmin=--1,
              vmax=2.4,
              extent=extent,
              aspect='equal')

    del (img)
    del (C)

    ax.set_facecolor(cmap(0.0))
    ax.set_xlim(-dx, dx)
    ax.set_ylim(-dy, dy)

    ax.hlines(0.9, 0.092, 0.192, transform=ax.transAxes, color='red', lw=2)
    ax.text(0.1,
            0.94,
            '$%i \; \mathrm{cMpc}$' % (dx * 0.2),
            transform=ax.transAxes,
            size=12,
            color='black')

    rect = patches.Rectangle((0.09, 0.92),
                             0.105,
                             0.065,
                             linewidth=1,
                             edgecolor='none',
                             facecolor='white',
                             alpha=0.5,
                             transform=ax.transAxes)

    ax.add_patch(rect)

    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)

    # plt.show()
    fname = 'plots/parent_zoom/parent_zoom_%03d.png' % i
    # plt.gca().set_axis_off()
    # plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
    #                     hspace = 0, wspace = 0)
    # plt.margins(0,0)
    print(fname)
    fig.savefig(fname, dpi=150)  #, bbox_inches='tight', pad_inches = 0)
    plt.close(fig)
示例#14
0
        cmap = 'gnuplot'
        axlab = r'$\log\Sigma_{X,\mathrm{0.5-2keV}}$ [$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{pc}^{-2}]$'
    elif prop == 'stars':
        cmap = 'bone'
        axlab = r'$\log\Sigma_*$ [$M_{\odot}$ $\mathrm{pc}^{-2}]$'
    elif prop == 'temperature':
        cmap = 'seismic'
        axlab = r'$\langle\log(T)\rangle$ $[\mathrm{K}]$'
    else:
        raise IOError(
            'Plot options are "gasmass", "stars", "temperature" or "xrays"')

    if not mean_mass_weighted:

        Particles = sphviewer.Particles(pos, quantity, hsml=smoothing_length)
        Scene = sphviewer.Scene(Particles)

        phi_list = np.arange(0., 359., 1)
        for p, phi in tqdm(enumerate(phi_list)):
            Scene.update_camera(x=0.,
                                y=0.,
                                z=0.,
                                r='infinity',
                                t=45.,
                                p=phi,
                                extent=[-ext, ext, -ext, ext],
                                xsize=res,
                                ysize=res)
            Render = sphviewer.Render(Scene)
            Render.set_logscale()
        for ax, t, p, c1, c2 in zip([ax1, ax2, ax3], [0, 0, 90], [0, 90, 90],
                                    [0, 2, 2], [1, 1, 0]):

            C = sph.Camera(r='infinity',
                           t=t,
                           p=p,
                           roll=0,
                           xsize=ext,
                           ysize=ext,
                           x=c[0],
                           y=c[1],
                           z=c[2],
                           extent=[-dl, dl, -dl, dl])

            S = sph.Scene(P, C)
            R = sph.Render(S)
            img = np.log10(R.get_image())
            extent = R.get_extent()
            ax.imshow(img, cmap=cmaps.twilight())


        ax1.text(0.1,0.9,'$\mathrm{log_{10}}(M_{\star} \,/\, \mathrm{M_{\odot}}) = %.2f$'%\
                 np.log10(mstar["%02d"%region][tag][_idx] * 1e10),
                 transform=ax1.transAxes)

        for ax in [ax1, ax2, ax3]:
            ax.xaxis.set_major_formatter(
                FuncFormatter(lambda x, pos: (x / convers) * 1e3))
            ax.yaxis.set_major_formatter(
                FuncFormatter(lambda x, pos: (x / convers) * 1e3))
    def __init__(self, gn, prop,
                 sim='L0100N1504',
                 run='REFERENCE',
                 snapnum=28,
                 halotype='all'):

        self.groupnumber = gn
        self.property = prop
        tag = snapdict[str(snapnum)][0]

        try:
            data = h5.File(
                '/data5/arijdav1/saved_regions/' + sim + '_' + run + '/' + tag + '/' + halotype + '/group' + str(
                    gn) + '.hdf5', 'r')
        except IOError:
            print 'Invalid group number for this box.'
            exit()

        if prop == 'stars':
            pos = np.array(data['Stars/Coordinates']).T
            smoothing_length = np.array(data['Stars/SmoothingLength'])
            quantity = np.array(data['Stars/Mass']) * 1e10
        else:
            pos = np.array(data['Gas/Coordinates']).T
            smoothing_length = np.array(data['Gas/SmoothingLength'])
            if prop == 'gas':
                quantity = np.array(data['Gas/Mass']) * 1e10
            elif prop == 'hotgas':
                quantity = np.array(data['Gas/Mass']) * 1e10
                temp = np.array(data['Gas/Temperature'])
                mask = np.where(temp > np.power(10., 5.5))[0]
                column_pos = column_pos[mask]
                smoothing_length = smoothing_length[mask]
                quantity = quantity[mask]
            elif prop == 'xrays':
                quantity = np.array(
                    data['Gas/Xray_luminosity']) / 1e30  # make the numbers smaller so sphviewer can deal with them
            else:
                raise IOError('Plot options are "gas", "hotgas", "stars" or "xrays"')


        N = len(quantity)

        pos *= 1e3  # convert to kpc
        smoothing_length *= 1e3

        if prop == 'gas':
            self.cmap = 'hot'
            self.axlab = r'$\log\Sigma_g$ [$M_{\odot}$ $\mathrm{pc}^{-2}]$'
        elif prop == 'hotgas':
            self.cmap = 'hot'
            self.axlab = r'$\log\Sigma_{\mathrm{g,hot}}$ [$M_{\odot}$ $\mathrm{pc}^{-2}]$'
        elif prop == 'xrays':
            self.cmap = 'gnuplot'
            self.axlab = r'$\log\Sigma_{X,\mathrm{0.5-2keV}}$ [$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{pc}^{-2}]$'
        elif prop == 'stars':
            self.cmap = 'bone'
            self.axlab = r'$\log\Sigma_*$ [$M_{\odot}$ $\mathrm{pc}^{-2}]$'
        else:
            raise IOError('Plot options are "gas", "hotgas", "stars" or "xrays"')

        Particles = sphviewer.Particles(pos, quantity, hsml=smoothing_length)
        self.Scene = sphviewer.Scene(Particles)
    def select(self,centre,region_size): # Region size in Mpc
        
        print 'Loading region...'
        code_centre = centre * self.h/(self.a_0*1e3) # convert to h-less comoving code units
        region_size *= self.h/self.a_0

        # Point read_eagle to the data
        snapfile = self.sim_path + 'snapshot_' + self.tag + '/snap_' + self.tag + '.0.hdf5'

        # Open snapshot
        snap = read.EagleSnapshot(snapfile)
        # Select region of interest
        snap.select_region(code_centre[0]-region_size/2.,
                            code_centre[0]+region_size/2.,
                            code_centre[1]-region_size/2.,
                            code_centre[1]+region_size/2.,
                            code_centre[2]-region_size/2.,
                            code_centre[2]+region_size/2.)

        if self.property == 'stars':
            pos = snap.read_dataset(4,'Coordinates') * self.a_0/self.h
            smoothing_length = snap.read_dataset(4, 'SmoothingLength') * self.a_0 / self.h
            quantity = snap.read_dataset(4, 'Mass') / self.h * 1e10
        else:
            pos = snap.read_dataset(0, 'Coordinates') * self.a_0 / self.h
            smoothing_length = snap.read_dataset(0, 'SmoothingLength') * self.a_0 / self.h

            if self.property == 'gas':
                quantity = snap.read_dataset(0, 'Mass') / self.h / 1e10
            elif self.property == 'xrays':
                pids = snap.read_dataset(0, 'ParticleIDs')
                quantity = self.xrays[np.searchsorted(self.xray_pids,pids)]
            else:
                raise IOError('Plot options are "gas","stars" or "xrays"')

        
        print 'Wrapping box...'
        region_size /= self.h/self.a_0
        centre_mpc = centre /1e3
        pos = ne.evaluate("pos-centre_mpc")
        pos[pos[:,0]<(-1.*self.boxsize/2.),0] += self.boxsize
        pos[pos[:,1]<(-1.*self.boxsize/2.),1] += self.boxsize
        pos[pos[:,2]<(-1.*self.boxsize/2.),2] += self.boxsize
        pos[pos[:,0]>self.boxsize/2.,0] -= self.boxsize
        pos[pos[:,1]>self.boxsize/2.,1] -= self.boxsize
        pos[pos[:,2]>self.boxsize/2.,2] -= self.boxsize
        pos = ne.evaluate("pos+centre_mpc")
        



        pos = pos.T

        N = len(quantity)

        pos *= 1e3  # convert to kpc
        smoothing_length *= 1e3

        print 'Creating scene...'
        Particles = sphviewer.Particles(pos, quantity, hsml=smoothing_length)
        self.Scene = sphviewer.Scene(Particles)
    def __init__(self, prop,
                 sim='L0100N1504',
                 run='REFERENCE',
                 snapnum=28):
        print 'Initialising box for imaging...'

        tag = snapdict[str(snapnum)][0]

        sim_path = '/data5/simulations/EAGLE/' + sim + '/' + run + '/data/'

        # Get volume information
        boxsize = E.readAttribute('SNAP', sim_path, tag, "/Header/BoxSize")
        h = E.readAttribute('SNAP', sim_path, tag, "/Header/HubbleParam")
        a_0 = E.readAttribute('SNAP', sim_path, tag, "/Header/ExpansionFactor")

        # Point read_eagle to the data
        snapfile = sim_path + 'snapshot_' + tag + '/snap_' + tag + '.0.hdf5'
        comm = MPI.COMM_WORLD
        comm_rank = comm.Get_rank()
        comm_size = comm.Get_size()
        # Open snapshot
        snap = read.EagleSnapshot(snapfile)
        # Select region of interest
        snap.select_region(0.,boxsize,0.,boxsize,0.,boxsize)
        # Split selection between processors
        # This assigns an equal number of hash cells to each processor.
        snap.split_selection(comm_rank,comm_size)

        if prop == 'stars':
            #pos = load_array('Coordinates', 4, sim=sim, run=run, tag=tag).T
            #smoothing_length = load_array('SmoothingLength', 4, sim=sim, run=run, tag=tag)
            #quantity = load_array('Mass', 4, sim=sim, run=run, tag=tag) * 1e10

            pos = snap.read_dataset(4,'Coordinates') * a_0/h
            pos = pos.T
            smoothing_length = snap.read_dataset(4, 'SmoothingLength') * a_0 / h
            quantity = snap.read_dataset(4, 'Mass') / h * 1e10
        else:
            #pos = load_array('Coordinates', 0, sim=sim, run=run, tag=tag).T
            #smoothing_length = load_array('SmoothingLength', 0, sim=sim, run=run, tag=tag)

            pos = snap.read_dataset(0, 'Coordinates') * a_0 / h
            print pos
            pos = pos.T
            smoothing_length = snap.read_dataset(0, 'SmoothingLength') * a_0 / h

            if prop == 'gas':
                quantity = snap.read_dataset(0, 'Mass') / h / 1e10
                print quantity
            elif prop == 'xrays':
                pids = snap.read_dataset(0, 'ParticleIDs')
                print 'Matching x-rays to particles'

                xray_data = h5.File('/data6/arijdav1/Lx_matching/'+sim+'_'+run+'/'+tag+'.hdf5','r')
                xrays = np.array(xray_data['Xray_luminosity']) / 1e30
                xray_pids = np.array(xray_data['ParticleIDs'])
                #match_sort = np.argsort(xray_pids)
                #xrays = xrays[match_sort]
                #xray_pids = xray_pids[match_sort]

                quantity = xrays[np.searchsorted(xray_pids,pids)]


            else:
                raise IOError('Plot options are "gas","stars" or "xrays"')

        N = len(quantity)

        pos *= 1e3  # convert to kpc
        smoothing_length *= 1e3

        print N

        Particles = sphviewer.Particles(pos, quantity, hsml=smoothing_length)

        print Particles.get_pos()
        print Particles.get_mass()
        print Particles.get_hsml()

        self.Scene = sphviewer.Scene(Particles)

        self.sim = sim
        self.run = run
        self.tag = tag
        self.property = prop
        self.boxsize = boxsize / h
print("mass weighted temp:",
      np.sum((_temp * _mass)[mask]) / np.sum(_mass[mask]))

extent = 15
img = [None, None]
for i, _weight in enumerate([_temp, _temp * (_mass / 1.99e38)]):
    Pd = sph.Particles(_coods, _weight)  # halog_dust[mask] * 1e10)
    C = sph.Camera(x=0,
                   y=0,
                   z=0,
                   r='infinity',
                   zoom=1,
                   extent=[-extent, extent, -extent, extent],
                   xsize=512,
                   ysize=512)
    S = sph.Scene(Pd, Camera=C)
    R = sph.Render(S)
    # R.set_logscale()
    img[i] = R.get_image()

#if vmax is None:
#    vmax = img.max()
#
#if vmin > vmax:
#    print("vmin larger than vmax! Setting lower")
#    vmin = img.max() / 10
#print("vmin,vmax:",vmin,vmax)

#cNorm  = colors.LogNorm(vmin=vmin,vmax=vmax)
#sm = cm.ScalarMappable(norm=cNorm, cmap=cmap)
    def select(self, centre, region_size):  # Region size in Mpc
        if not self.quiet:
            print 'Loading region...'

        code_centre = centre * self.h / (
            self.a_0 * 1e3)  # convert to h-less comoving code units
        code_region_size = region_size * self.h / self.a_0

        centre_mpc = centre / 1e3

        # Point read_eagle to the data
        snapfile = self.sim_path + 'snapshot_' + self.tag + '/snap_' + self.tag + '.0.hdf5'

        # Open snapshot
        snap = read.EagleSnapshot(snapfile)
        # Select region of interest
        snap.select_region(code_centre[0] - code_region_size / 2.,
                           code_centre[0] + code_region_size / 2.,
                           code_centre[1] - code_region_size / 2.,
                           code_centre[1] + code_region_size / 2.,
                           code_centre[2] - code_region_size / 2.,
                           code_centre[2] + code_region_size / 2.)

        if self.property == 'stars':
            pos = snap.read_dataset(4, 'Coordinates') * self.a_0 / self.h
            smoothing_length = snap.read_dataset(
                4, 'SmoothingLength') * self.a_0 / self.h
            quantity = snap.read_dataset(4, 'Mass') / self.h * 1e10

        else:
            pos = snap.read_dataset(0, 'Coordinates') * self.a_0 / self.h
            smoothing_length = snap.read_dataset(
                0, 'SmoothingLength') * self.a_0 / self.h

            if self.property == 'gas':
                quantity = snap.read_dataset(0, 'Mass') / self.h / 1e10

            elif self.property == 'xrays':
                pids = snap.read_dataset(0, 'ParticleIDs')
                quantity = self.xrays[np.searchsorted(self.xray_pids, pids)]

            elif self.property == 'entropy':
                m_H_cgs = 1.6737e-24
                weight = snap.read_dataset(0, 'Mass') / self.h / 1e10

                temp = snap.read_dataset(0, 'Temperature')

                abunds = np.zeros((len(temp), 11))
                abunds[:, 0] = snap.read_dataset(
                    0, "SmoothedElementAbundance/Hydrogen")
                abunds[:, 1] = snap.read_dataset(
                    0, "SmoothedElementAbundance/Helium")
                abunds[:, 2] = snap.read_dataset(
                    0, "SmoothedElementAbundance/Carbon")
                abunds[:, 3] = snap.read_dataset(
                    0, "SmoothedElementAbundance/Nitrogen")
                abunds[:, 4] = snap.read_dataset(
                    0, "SmoothedElementAbundance/Oxygen")
                abunds[:,
                       5] = snap.read_dataset(0,
                                              "SmoothedElementAbundance/Neon")
                abunds[:, 6] = snap.read_dataset(
                    0, "SmoothedElementAbundance/Magnesium")
                abunds[:, 7] = snap.read_dataset(
                    0, "SmoothedElementAbundance/Silicon")
                abunds[:, 8] = abunds[:, 7] * 0.6054160
                abunds[:, 9] = abunds[:, 7] * 0.0941736
                abunds[:, 10] = snap.read_dataset(
                    0, "SmoothedElementAbundance/Iron")

                atomic_numbers = np.array(
                    [1., 2., 6., 7., 8., 10., 12., 14., 16., 20., 26.])
                Xe = np.ones(len(abunds[:, 0]))
                num_ratios = np.zeros(np.shape(abunds))
                for col in range(len(abunds[0, :])):
                    num_ratios[:, col] = abunds[:, col] / abunds[:, 0]
                for element in range(len(abunds[0, :]) - 1):
                    Xe += num_ratios[:,
                                     element + 1] * atomic_numbers[element + 1]

                density = snap.read_dataset(0, 'Density')
                n_H = density * abunds[:, 0] / m_H_cgs  # convert into nH cm^-3
                n_e = n_H * Xe  # electron density in cm^-3

                quantity = temp / np.power(n_e, 2. / 3.)

            else:
                raise IOError(
                    'Plot options are "gas","ion", stars" or "xrays"')

        if not self.quiet:
            print 'Wrapping box...'
        pos = ne.evaluate("pos-centre_mpc")
        pos[pos[:, 0] < (-1. * self.boxsize / 2.), 0] += self.boxsize
        pos[pos[:, 1] < (-1. * self.boxsize / 2.), 1] += self.boxsize
        pos[pos[:, 2] < (-1. * self.boxsize / 2.), 2] += self.boxsize
        pos[pos[:, 0] > self.boxsize / 2., 0] -= self.boxsize
        pos[pos[:, 1] > self.boxsize / 2., 1] -= self.boxsize
        pos[pos[:, 2] > self.boxsize / 2., 2] -= self.boxsize
        pos = ne.evaluate("pos+centre_mpc")

        # read_eagle loads in more than we actually asked for above. We need to mask to the region size again!
        posmask = np.where(
            (np.absolute(pos[:, 0] - centre_mpc[0]) < region_size / 2.)
            & (np.absolute(pos[:, 1] - centre_mpc[1]) < region_size / 2.)
            & (np.absolute(pos[:, 2] - centre_mpc[2]) < region_size / 2.))[0]

        pos = pos[posmask, :]
        smoothing_length = smoothing_length[posmask]
        quantity = quantity[posmask]

        N = len(quantity)

        pos *= 1e3  # convert to kpc
        smoothing_length *= 1e3
        if not self.quiet:
            print 'Creating scene...'

        if self.property in [
                'entropy',
        ]:
            weight = weight[posmask]
            Particles = sphviewer.Particles(pos, weight, hsml=smoothing_length)
            self.weightScene = sphviewer.Scene(Particles)
            Particles = sphviewer.Particles(pos,
                                            quantity * weight,
                                            hsml=smoothing_length)
            self.propScene = sphviewer.Scene(Particles)

        else:

            if pos.size == 0:
                self.Scene = None

            else:
                Particles = sphviewer.Particles(pos,
                                                quantity,
                                                hsml=smoothing_length)
                self.Scene = sphviewer.Scene(Particles)
示例#21
0
        vmin=3
        vmax=7

        # ----escala de colores que te guste (http://matplotlib.org/examples/color/colormaps_reference.html)---
        cmap='jet'

<<<<<<< HEAD
        nb1 = 10
        #nb1 = 100 
=======
        #nb1 = 5
        nb1 = 100 
>>>>>>> b29321f0c229ffcfec5b2b43354097e24d056487

        particles=sph.Particles(pos[:3,corte],mstr[corte]*1e10,nb=nb1)
        escena=sph.Scene(particles)
        escena.update_camera(r='infinity',x=0,y=0,z=0,extent=[-rl,rl,-rl,rl])
        rend=sph.Render(escena)
        extent=escena.get_extent()
        rend.set_logscale()

        ax[0,0].imshow(rend.get_image(),extent=extent,origin='lower',cmap=cmap, vmin=vmin, vmax= vmax)
        ax[0,0].set_xlim(-5,5)
        ax[0,0].set_ylim(-5,5)
        ax[0,0].set_xticks([])
        ax[0,0].set_yticks([])
        ax[0,0].set_yticklabels([])
        ax[0,0].set_xticklabels([])
#         ax[0,0].set_ylabel('$y\:[kpc]$', fontsize=40)
#         ax[0,0].minorticks_on()
#         ax[0,0].tick_params( labelsize=40)
示例#22
0
    def __init__(self,
                 pos,
                 mass=None,
                 hsml=None,
                 nb=None,
                 logscale=True,
                 plot=True,
                 min_hsml=None,
                 max_hsml=None,
                 **kwargs):
        """
        Quickview is a simple wrapper of the sphviewer API. 
        This utility stores the particles, defines the Scene and the Camera, and produces the rendering of the Scene in one step, thus making the process of producing images of SPH particles easy and quick. 
        The arguments of the functions are:
         - pos = SPH particle positions. Array of shape [N,3], where N in the 
           number of particles and pos[:,0] = x; pos[:,1] = y; pos[:,2] = z.
         - mass (optional): is the mass of the SPH particles. If present, 
           it must be an array of size N. If absent, a constant value, 
           mass = 1, will be assumed for all particles.
         - hsml (optional): this is an array containing the smoothing lenghts 
           of the SPH particles. The absence of the array will trigger the 
           calculation of the smoothing lenghts.
         - nb (optional): number of neighbours to be used for the calculation
           of the SPH smoothing lengths. If absent, the default value nb=32 will
           be used. This arguement is ignored if the array hsml is provided.
         - logscale (optional): If True, the output image becomes 

                out_log = log10(1.0+output)

         - plot (optional): If true, QuickView will plot the resulting image in
           the current active figure.
         - min_hsml / max_hsml: Physical values of the minimum / maximum 
           smoothing lengths. Only used when defined. 
         
         **kwargs 
         These include the parameters of the Camera:

        """

        if (mass is None):
            mass = np.ones(len(pos))

        if (nb == None):
            self._P = sph.Particles(pos, mass, hsml)
        else:
            self._P = sph.Particles(pos, mass, hsml, nb)

        if ((min_hsml is not None) or (max_hsml is not None)):
            hsml = self.get_hsml()
            if (min_hsml is not None):
                min_hsml = min_hsml
            else:
                min_hsml = np.min(hsml)
            if (max_hsml is not None):
                max_hsml = max_hsml
            else:
                max_hsml = np.max(hsml)

            hsml = np.clip(hsml, min_hsml, max_hsml)
            print('Limiting smoothing length to the range '
                  '[%.3f,%.3f]' % (min_hsml, max_hsml))
            self._P.set_hsml(hsml)

        self._S = sph.Scene(self._P)
        self._S.update_camera(**kwargs)

        self._R = sph.Render(self._S)
        if (logscale):
            self._R.set_logscale()

        self._img = self._R.get_image()
        self._extent = self._R.get_extent()

        if (plot):
            self.imshow(aspect='auto')
            return
        else:
            return
示例#23
0
    smoothing_length *= 1e3

    if prop == 'gasmass':
        cmap = 'hot'
        axlab = r'$\log\Sigma_g$ [$M_{\odot}$ $\mathrm{kpc}^{-2}]$'
    elif prop == 'xrays':
        cmap = 'gnuplot'
        axlab = r'$\log\Sigma_{X,\mathrm{0.5-2keV}}$ [$\mathrm{erg}$ $\mathrm{s}^{-1}$ $\mathrm{kpc}^{-2}]$'
    elif prop == 'stars':
        cmap = 'bone'
        axlab = r'$\log\Sigma_*$ [$M_{\odot}$ $\mathrm{kpc}^{-2}]$'
    else:
        raise IOError('Plot options are "gasmass", "stars", "temperature" or "xrays"')

    Particles = sphviewer.Particles(pos,quantity,hsml=smoothing_length)
    Scene = sphviewer.Scene(Particles)
    
    Scene.update_camera(x=0.,y=0.,z=0.,r='infinity',t=90.,extent=[-ext,ext,-ext,ext],xsize=res,ysize=res)
    Render = sphviewer.Render(Scene)
    #Render.set_logscale()

    img = Render.get_image()
    sdensity_img = img/px_size**2

    '''
    # For quickly viewing the individual images
    extent = Render.get_extent()
    plt.figure()
    plt.imshow(sdensity_img,cmap='hot',extent=extent, origin='lower')
    plt.show()
    '''
               extent=[-dx, dx, -dx, dx],
               t=t,
               p=p,
               roll=0,
               xsize=4000,
               ysize=2250)

# Gas density
P = sph.Particles(norm_coods[coods_mask],
                  pmass[coods_mask] / pmass[coods_mask].min())
# hsml = hsml * 10)# * 2)

hsml = P.get_hsml()

## Create scene and render
S = sph.Scene(P, Camera=C)
R = sph.Render(S)

## Get image and plot
# R.set_logscale()
img = R.get_image()
print(img.min(), img.max())

cmap = sph_cmaps.desert()  # plt.get_cmap('twilight')
img = cmap(vis_util.get_normalized_image(img, vmin=0, vmax=7))

fig, ax = vis_util.plot_img(img, R.get_extent())
# plt.show()
fig.savefig('test_out/gas_time_%s.png' % (tag_idx),
            bbox_inches='tight',
            pad_inches=0)
def getimage(path, snap, soft, num, centre, data, part_type):

    # Get plot data
    if part_type == 0:
        poss_gas, masses_gas, smls_gas = get_sphere_data(path,
                                                         snap,
                                                         part_type=0,
                                                         soft=None)
    elif part_type == 1:
        poss_gas, masses_gas, smls_gas = get_sphere_data(path,
                                                         snap,
                                                         part_type=1,
                                                         soft=soft)
    else:
        return -1

    # Centre particles
    poss_gas -= centre

    # Remove boundary particles
    rgas = np.linalg.norm(poss_gas, axis=1)
    okinds_gas = rgas < 14 / 0.677
    poss_gas = poss_gas[okinds_gas, :]
    masses_gas = masses_gas[okinds_gas]
    smls_gas = smls_gas[okinds_gas]

    if part_type == 0:
        print('There are', len(masses_gas), 'gas particles in the region')
    elif part_type == 1:
        print('There are', len(masses_gas),
              'dark matter particles in the region')

    # Set up particle objects
    P_gas = sph.Particles(poss_gas, mass=masses_gas, hsml=smls_gas)

    # Initialise the scene
    S_gas = sph.Scene(P_gas)

    i = data[num]
    i['xsize'] = 5000
    i['ysize'] = 5000
    i['roll'] = 0
    S_gas.update_camera(**i)
    R_gas = sph.Render(S_gas)
    R_gas.set_logscale()
    img_gas = R_gas.get_image()

    if part_type == 0:
        np.save(
            'animationdata/gas_animationdata_reg' + reg + '_snap' + snap +
            '_angle%05d.npy' % num, img_gas)
    if part_type == 1:
        np.save(
            'animationdata/dm_animationdata_reg' + reg + '_snap' + snap +
            '_angle%05d.npy' % num, img_gas)

    # fig = plt.figure()
    # ax = fig.add_subplot(111)
    #
    # ax.hist(get_normalised_image(img_gas).ravel(), bins=256, range=(0.0, 1.0), fc='k', ec='k')
    #
    # if part_type == 0:
    #     fig.savefig('plots/spheres/All/histDM_animation_reg' + reg + '_snap' + snap + '_angle%05d.png'%num,
    #                 bbox_inches='tight')
    # if part_type == 1:
    #     fig.savefig('plots/spheres/All/histgas_animation_reg' + reg + '_snap' + snap + '_angle%05d.png'%num,
    #                 bbox_inches='tight')
    # plt.close(fig)

    vmax_gas = img_gas.max()
    vmin_gas = vmax_gas * 0.5

    # Get colormaps
    if part_type == 0:
        cmap_gas = cmaps.twilight()
    elif part_type == 1:
        cmap_gas = ml.cm.Greys_r

    # Convert images to rgb arrays
    rgb_gas = cmap_gas(get_normalised_image(img_gas, vmin=vmin_gas))

    return rgb_gas, R_gas.get_extent()
示例#26
0
for i in range(0, N_StePS):
    if StePS_coordinates[i, 2] > -alpha and StePS_coordinates[
            i,
            2] < alpha and plot_R_limit > np.sqrt(StePS_coordinates[i, 0]**2 +
                                                  StePS_coordinates[i, 1]**2 +
                                                  StePS_coordinates[i, 2]**2):
        StePS_slice[j, 0] = StePS_coordinates[i, 0]
        StePS_slice[j, 1] = StePS_coordinates[i, 1]
        StePS_slice[j, 2] = StePS_coordinates[i, 2]
        StePS_slice[j, 3] = StePS_coordinates[i, 3]
        j += 1

end = time.time()
print("..done in %fs. \n\n" % (end - start))
cmap = 'inferno'

extent = [-R_plot, R_plot, -R_plot, R_plot]
Particles = sph.Particles(StePS_slice[:, 0:3].T, StePS_slice[:, 3].T)
Scene = sph.Scene(Particles)
Scene.update_camera(r='infinity', extent=extent)
Render = sph.Render(Scene)
Render.set_logscale()
img = Render.get_image()
fig = plt.figure(1, figsize=(6, 6))
ax1 = fig.add_subplot(111)
ax1.imshow(img, extent=extent, origin='lower', cmap=cmap)
ax1.set_xlabel('x[Mpc]', size=10)
ax1.set_ylabel('y[Mpc]', size=10)
plt.title(title)
plt.show()
示例#27
0
    anchors['zoom'] = [1., 'same', 'same', 'same', 'same', 'same', 'same']
    anchors['extent'] = [10, 'pass', 'pass', 'pass', 'pass', 'pass', 30]

    data = get_camera_trajectory(targets, anchors)

    n1 = 10000

    cube1 = np.random.rand(3, n1)
    cube1[1, :] -= 6
    cube2 = np.random.rand(3, n1)
    cube2[1, :] += 1
    cubes = np.concatenate((cube1, cube2), axis=1)
    mass = np.ones(n1+n1)

    P = sph.Particles(cubes, mass)
    S = sph.Scene(P)

    h = 0
    for i in data:
        i['xsize'] = 200
        i['ysize'] = 200
        i['roll'] = 0
        S = sph.Scene(P)
        S.update_camera(**i)
        print(S.Camera.get_params())
        R = sph.Render(S)
        img = R.get_image()
        R.set_logscale()
        plt.imsave('test/image_'+str('%d.png' % h), img,
                   vmin=0, vmax=6, cmap='cubehelix')
        h += 1
示例#28
0
    def select(self, centre, region_size):  # Region size in Mpc
        if not self.quiet:
            print 'Loading region...'

        code_centre = centre * self.h / (
            self.a_0 * 1e3)  # convert to h-less comoving code units
        code_region_size = region_size * self.h / self.a_0

        centre_mpc = centre / 1e3

        # Point read_eagle to the data
        snapfile = self.sim_path + 'snapshot_' + self.tag + '/snap_' + self.tag + '.0.hdf5'

        # Open snapshot
        snap = read.EagleSnapshot(snapfile)
        # Select region of interest
        snap.select_region(code_centre[0] - code_region_size / 2.,
                           code_centre[0] + code_region_size / 2.,
                           code_centre[1] - code_region_size / 2.,
                           code_centre[1] + code_region_size / 2.,
                           code_centre[2] - code_region_size / 2.,
                           code_centre[2] + code_region_size / 2.)

        if self.property == 'stars':
            pos = snap.read_dataset(4, 'Coordinates') * self.a_0 / self.h
            smoothing_length = snap.read_dataset(
                4, 'SmoothingLength') * self.a_0 / self.h
            quantity = snap.read_dataset(4, 'Mass') / self.h * 1e10

        else:
            pos = snap.read_dataset(0, 'Coordinates') * self.a_0 / self.h
            smoothing_length = snap.read_dataset(
                0, 'SmoothingLength') * self.a_0 / self.h

            if self.property == 'gas':
                quantity = snap.read_dataset(0, 'Mass') / self.h / 1e10

            elif self.property == 'ion':  # do this in CGS units

                self.masses_u_dict = {
                    'Hydrogen': 1.00794,
                    'Carbon': 12.0107,
                    'Oxygen': 15.9994
                }

                p_mass = snap.read_dataset(
                    0, 'Mass') / self.h * C.unit_mass_cgs  # in g
                p_density = snap.read_dataset(
                    0, "Density"
                ) * self.h**2 / self.a_0**3 * C.unit_density_cgs  # in g cm^-3
                p_temp = snap.read_dataset(0, "Temperature")
                el_mass_abund = snap.read_dataset(
                    0, 'SmoothedElementAbundance/' + self.element)
                H_abund = snap.read_dataset(
                    0, 'SmoothedElementAbundance/Hydrogen')
                p_nH = p_density * H_abund / C.m_H_cgs

                ion_fraction = ionbal.find_ionbal(self.z, self.ion,
                                                  np.log10(p_nH),
                                                  np.log10(p_temp))

                mass_in_ion = p_mass * el_mass_abund * ion_fraction

                quantity = mass_in_ion / 1e40

            elif self.property == 'xrays':
                pids = snap.read_dataset(0, 'ParticleIDs')
                quantity = self.xrays[np.searchsorted(self.xray_pids, pids)]
            else:
                raise IOError(
                    'Plot options are "gas","ion", stars" or "xrays"')

        # read_eagle loads in more than we actually asked for above. We need to mask to the region size again!
        posmask = np.where(
            (np.absolute(pos[:, 0] - centre_mpc[0]) < region_size / 2.)
            & (np.absolute(pos[:, 1] - centre_mpc[1]) < region_size / 2.)
            & (np.absolute(pos[:, 2] - centre_mpc[2]) < region_size / 2.))[0]

        pos = pos[posmask, :]
        smoothing_length = smoothing_length[posmask]
        quantity = quantity[posmask]

        if self.property == 'ion':
            mass_in_ion = mass_in_ion[posmask]

        if not self.quiet:
            print 'Wrapping box...'
        pos = ne.evaluate("pos-centre_mpc")
        pos[pos[:, 0] < (-1. * self.boxsize / 2.), 0] += self.boxsize
        pos[pos[:, 1] < (-1. * self.boxsize / 2.), 1] += self.boxsize
        pos[pos[:, 2] < (-1. * self.boxsize / 2.), 2] += self.boxsize
        pos[pos[:, 0] > self.boxsize / 2., 0] -= self.boxsize
        pos[pos[:, 1] > self.boxsize / 2., 1] -= self.boxsize
        pos[pos[:, 2] > self.boxsize / 2., 2] -= self.boxsize
        pos = ne.evaluate("pos+centre_mpc")

        N = len(quantity)

        pos *= 1e3  # convert to kpc
        smoothing_length *= 1e3
        if not self.quiet:
            print 'Creating scene...'
        Particles = sphviewer.Particles(pos, quantity, hsml=smoothing_length)
        self.Scene = sphviewer.Scene(Particles)

        if self.property == 'ion':
            self.ion_positions = pos / 1e3
            self.ion_hsml = smoothing_length / 1e3
            self.ion_quantity = mass_in_ion / (
                C.m_sol_cgs * self.masses_u_dict[self.element])
            self.ion_centre = centre / 1e3