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 __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 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
Пример #4
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
Пример #5
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()
Пример #6
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
Пример #7
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()
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()
Пример #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
    rl = 5
    corte, = np.where((xn < rl) & (yn < rl) & (zn < rl) & (xn > -rl)
                      & (yn > -rl) & (zn > -rl))

    #-----rango que tiene la escala  de colores-----
    vmin = 1.8
    vmax = 6
    # ----escala de colores que te guste (http://matplotlib.org/examples/color/colormaps_reference.html)---
    cmap = 'magma'

    nb1 = 100
    #         nb1 = 100
    #         npixel = 1000
    npixel = 1000

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

    ax[0, 0].imshow(rend.get_image(),
                    extent=extent,
                    origin='lower',
Пример #12
0
from pylab import *
import sphviewer

x, y, z, mass, den, fe = loadtxt(sys.argv[1],
                                 unpack=True,
                                 usecols=[1, 2, 3, 7, 9, 36],
                                 skiprows=1,
                                 delimiter=',')

pos = zeros(shape=(3, len(den)))
pos[0][:] = x
pos[1][:] = y
pos[2][:] = z

Particles = sphviewer.Particles(pos, fe)
for ii in range(200):
    print sys.argv[1], ii

    Scene = sphviewer.Scene(Particles)
    camera = Scene.Camera.get_params()
    theta = double(ii) / 200.0 * 360
    radius = 1000 - double(ii)
    Scene.update_camera(r=radius,
                        t=0,
                        p=theta,
                        xsize=1000,
                        ysize=1000,
                        x=0.0,
                        y=0.0,
                        z=0.0)
Пример #13
0
    alpha *= 180. / np.pi
    beta *= 180. / np.pi
    print(alpha, beta)

    for _orientation, _p, _t, _roll in zip([0, 1, 2, 3, 4, 5], beta, alpha,
                                           [270, 180, 270, 0, 270, 90]):

        print("#########\nRendering orientation %s\np=%s, t=%s, roll=%s\n##########"%\
                (_orientation,_p,_t,_roll))

        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(10, 10))

        if _orientation == 0:
            mask = np.random.rand(len(halog_pos)) < 1
            Pg = sph.Particles(halog_pos[mask], halog_mass[mask] * 1e10)
            Pd = sph.Particles(halog_pos[mask], halog_dust[mask] * 1e10)
            Psfr = sph.Particles(halog_pos[mask], halog_sfr[mask])

            mask = np.random.rand(len(halos_pos)) < 1
            Ps = sph.Particles(halos_pos[mask], halos_pmass[mask] * 1e10)

        extent = 30
        sm1, img1 = plot_dist(fig,
                              ax1,
                              Pg,
                              hcood,
                              cmaps.night(),
                              vmin=1e2,
                              extent=extent,
                              p=_p,
Пример #14
0
    rl = 50
    corte, = np.where((xn_drk < rl) & (yn_drk < rl) & (zn_drk < rl)
                      & (xn_drk > -rl) & (yn_drk > -rl) & (zn_drk > -rl))

    #-----rango que tiene la escala  de colores-----
    vmin = 4.5
    vmax = 6.7

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

    #         nb1 = 300
    nb1 = 25
    npixel = 1000

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

    ax[1, 0].imshow(rend.get_image(),
                    extent=extent,
                    origin='lower',
    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)
Пример #16
0
        #-----rango que tiene la escala  de colores-----
        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()
_radius = np.array(ad.to_dataframe('radius')) / _kpc
_x = np.array(ad.to_dataframe('x')) / _kpc
_y = np.array(ad.to_dataframe('y')) / _kpc
_z = np.array(ad.to_dataframe('z')) / _kpc
_coods = np.squeeze(np.array([_x, _z, _y])).T

radius = 15  # kpc
mask = _radius < radius
print("radius:", radius)
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()
    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)
Пример #19
0
    rl = 50
    corte, = np.where((xn < rl) & (yn < rl) & (zn < rl) & (xn > -rl)
                      & (yn > -rl) & (zn > -rl))

    #-----rango que tiene la escala  de colores-----
    vmin = 0.9
    vmax = 6.7

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

    #         nb1 = 300
    nb1 = 25
    npixel = 1000

    particles = sph.Particles(pos[corte, :3], 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],
                         xsize=npixel,
                         ysize=npixel)
    rend = sph.Render(escena)
    extent = escena.get_extent()
    rend.set_logscale()

    ax[1, 0].imshow(rend.get_image(),
                    extent=extent,
                    origin='lower',
Пример #20
0
# read in relevant columns from your file
x, y, z, mass, den = loadtxt(sys.argv[1],
                             unpack=True,
                             usecols=[1, 2, 3, 7, 9],
                             skiprows=1,
                             delimiter=',')

# set up arrays recognized by py-sphviewer
pos = zeros(shape=(3, len(den)))
pos[0][:] = x
pos[1][:] = y
pos[2][:] = z

# initialize sphviewer particles structure
Particles = sphviewer.Particles(pos, mass)

for ii in range(200):
    print sys.argv[1], ii

    # set up a scene
    Scene = sphviewer.Scene(Particles)
    camera = Scene.Camera.get_params()

    # make a full rotation in 200 frames (theta in degrees)
    theta = double(ii) / 200.0 * 360

    # gradually ease in from 1000 to 800

    radius = (1000 - double(ii)) * 6.957e10  # cm/Rsun
        pmask[pmask] = (pgas[pmask, 1] < c[1] + dl)
        pmask[pmask] = (pgas[pmask, 2] > c[2] - dl)
        pmask[pmask] = (pgas[pmask, 2] < c[2] + dl)

        # pmask = ((pgas[:,0] > coods[0]-dl) & (pgas[:,0] < coods[0]+dl) &\
        #          (pgas[:,1] > coods[1]-dl) & (pgas[:,1] < coods[1]+dl) &\
        #          (pgas[:,2] > coods[2]-dl) & (pgas[:,2] < coods[2]+dl))

        print(len(pgas), np.sum(pmask))
        if np.sum(pmask) == 0:
            raise ValueError('No particles to plot')

        ext = 500  # number of pixels in image
        convers = ext / (2 * dl)  # conversion factor

        P = sph.Particles(pgas[pmask], mass=np.ones(np.sum(pmask)))

        fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 7))

        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],
    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)
Пример #23
0
             (norm_coods[:,1] < dx) & (norm_coods[:,1] > -dx) &\
             (norm_coods[:,2] < dx) & (norm_coods[:,2] > -dx)

C = sph.Camera(x=0,
               y=0,
               z=0,
               r='infinity',
               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))
Пример #24
0
pmask[pmask] = (pdark[pmask,2] > c[2]-dl)
pmask[pmask] = (pdark[pmask,2] < c[2]+dl)

# pmask = ((pdark[:,0] > coods[0]-dl) & (pdark[:,0] < coods[0]+dl) &\
#          (pdark[:,1] > coods[1]-dl) & (pdark[:,1] < coods[1]+dl) &\
#          (pdark[:,2] > coods[2]-dl) & (pdark[:,2] < coods[2]+dl))

print(len(pdark),np.sum(pmask))

# qv = QuickView(pdark[pmask],r='infinity',plot=False)
# qv.imshow()

ext=500 # number of pixels in image
convers = ext/(2*dl) # conversion factor

P = sph.Particles(pdark[pmask],mass=np.ones(np.sum(pmask)))

fig,(ax1,ax2,ax3) = plt.subplots(1,3,figsize=(15,7))

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())
Пример #25
0
    pos *= 1e3 # convert to kpc
    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()
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)
    # beta[(z==0) & (x<0)] = -np.pi/2  

    alpha *= 180./np.pi
    beta  *= 180./np.pi
    print(alpha,beta)
    
    for ax,_orientation,_p,_t,_roll in zip(axes[:3,k], [0, 1, 4], 
                                           beta[[0,1,4]], alpha[[0,1,4]], [270,180,270]):

        print("#########\nRendering orientation %s\np=%s, t=%s, roll=%s\n##########"%\
                (_orientation,_p,_t,_roll))
        
        if _orientation == 0:
            mask = np.random.rand(len(halog_pos)) < 1
            #Pg = sph.Particles(halog_pos[mask], halog_mass[mask] * 1e10) 
            Pd = sph.Particles(halog_pos[mask], halog_dust[mask] * 1e10) 
            # Psfr = sph.Particles(halog_pos[mask], halog_sfr[mask]) 


        extent = 24.5
        sm,img = plot_dist(fig, ax, Pd, hcood, cmaps.twilight(), 
                             vmin=1e2, vmax=1e10, extent=extent, p=_p, t=_t, roll=_roll) 
        # sm4,img4 = plot_dist(fig, ax4, Psfr, hcood, cmaps.sunlight(), 
        #                      vmin=0.1, extent=extent, p=_p, t=_t, roll=_roll) 


    ## ---- plot SEDs
    # gidx = galaxies[k].GroupID
    with h5py.File('sed_out_hires_test.h5','r') as f:
        wav = f['%s/Wavelength'%gidx][:]
        spec = f['%s/SED'%gidx][:]
    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
Пример #29
0
    anchors['p'] = [0, 'pass', 'pass', 'pass', 'pass', 'pass', 900]
    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')
Пример #30
0
# sh_hmr = E.readArray("SUBFIND", sim, tag, "/Subhalo/HalfMassRad", numThreads=1)

## set centre of box

idx = np.argsort(sh_mstar)[::-1][0]
a, b, c = sh_cop[idx]  # use most massive (mstar) halo

## Align with spin axis of galaxy

s = spin[idx]
t = np.arctan(s[0] / s[2]) * 180. / np.pi
p = np.arctan(s[1] / s[2]) * 180. / np.pi

## Create particle and camera objects
scaling = 1
P = sph.Particles(np.array(coods - [a, b, c]) * scaling, np.ones(len(coods)))

C = sph.Camera(x=0,
               y=0,
               z=0,
               r=1,
               zoom=1,
               t=t,
               p=p,
               roll=0,
               xsize=4000,
               ysize=2250)  # 16:9

S = sph.Scene(P, Camera=C)

## loop round object