def make_temperature_plots(s, output, cr):
    pynbody.analysis.angmom.faceon(s.g)
    sph.image(s.g,
              qty="temp",
              units="K",
              width=100,
              cmap="afmhot",
              vmin=1e4,
              vmax=1e6)
    if cr:
        plt.savefig('pioneer.%06d_temperature_faceon.png' % (output))
    else:
        plt.savefig('pioneer.%06d_temperature_faceon_nocr.png' % (output))
    plt.clf()

    pynbody.analysis.angmom.sideon(s.s)
    sph.image(s.g,
              qty="temp",
              units="K",
              width=100,
              cmap="afmhot",
              vmin=1e4,
              vmax=1e6)
    if cr:
        plt.savefig('pioneer.%06d_temperature_sideon.png' % (output))
    else:
        plt.savefig('pioneer.%06d_temperature_sideon_nocr.png' % (output))
    plt.clf()
Example #2
0
def plots(property='rho', firsthalo=0, nhalos=1):
    for halonum in xrange(firsthalo, nhalos):
        halo = h.load_copy(halonum)
        print "Halo %i loaded" % halonum
        halo.physical_units()
        halomass = sum(halo['mass'])
        halo.g['rhosq'] = halo.g['rho'] * halo.g['rho']
        print "Density squared computed"
        #plot density profiles
        #bin by position
        pb.analysis.angmom.faceon(halo)  #orient faceon wrt angular momentum
        print "Orientation complete"
        #skipping centering leads to IndexError in next steps
        volproj = sph.image(halo.g,
                            qty=property,
                            units='g cm^-3',
                            av_z=True,
                            width=100,
                            cmap='RdYlBu',
                            title=r"%e $M_\odot$" % halomass,
                            filename='%i_volproj.png' % halonum)  #slice
        print "Volume weighted projection complete"
        rhoproj = sph.image(halo.g,
                            qty=property,
                            units='g cm^-3',
                            av_z='rhosq',
                            width=100,
                            cmap='RdYlBu',
                            title=r"%e $M_\odot$" % halomass,
                            filename='%i_emsnproj.png' %
                            halonum)  #integrated along z by default
        print "Emission weighted projection complete"
def make_density_plots(s, output, cr):
    pynbody.analysis.angmom.faceon(s.g)
    sph.image(s.g,
              qty="rho",
              units="g cm^-3",
              width=60,
              cmap="magma",
              vmin=5e-27,
              vmax=1e-23)
    if cr:
        plt.savefig('pioneer.%06d_density_faceon.png' % (output))
    else:
        plt.savefig('pioneer.%06d_density_faceon_nocr.png' % (output))
    plt.clf()

    pynbody.analysis.angmom.sideon(s.s)
    sph.image(s.g,
              qty="rho",
              units="g cm^-3",
              width=60,
              cmap="magma",
              vmin=5e-27,
              vmax=1e-23)
    if cr:
        plt.savefig('pioneer.%06d_density_sideon.png' % (output))
    else:
        plt.savefig('pioneer.%06d_density_sideon_nocr.png' % (output))
    plt.clf()
Example #4
0
def rho_proj(sim,
             resolution=1000,
             cmap="inferno",
             units="Msol kpc^-2",
             show_cbar=False,
             **kwargs):

    redshift = sim.properties['Redshift']
    boxsize = sim.properties["boxsize"]

    im = sph.image(sim.g,
                   width=boxsize,
                   resolution=resolution,
                   cmap=cmap,
                   units=units,
                   show_cbar=show_cbar,
                   **kwargs)

    if not show_cbar:
        cbar = plt.colorbar()
        cbar.set_label(label=r"$\rho\ (\mathrm{M_\odot\ kpc^{-2}})$",
                       fontsize=20)

    plt.ylabel(r"$y\ (\mathrm{cMpc})$", fontsize=20)
    plt.xlabel(r"$x\ (\mathrm{cMpc})$", fontsize=20)
    plt.title(r"$z = {0: .3f}$".format(redshift), fontsize=20)

    return (im)
Example #5
0
def metal_map(sim, metal, **kwargs):
    redshift = sim.properties["Redshift"]
    metal_arr = sim.g[metal]
    metal_tot = np.sum(metal_arr)

    metallicity = "{0}XH".format(metal)
    if metal_tot != 0:
        im = sph.image(sim.g,
                       qty=metallicity,
                       width=sim.properties["boxsize"],
                       cmap="RdPu",
                       show_cbar=False,
                       approximate_fast=False,
                       **kwargs)
        cbar = plt.colorbar()
        cbar.set_label(label="[{0}/{1}]".format(metal, "H"), fontsize=16)
        plt.title("z = {1: .3f}".format(metal, redshift), fontsize=18)
        plt.ylabel(r"$y\ (\mathrm{cMpc})$", fontsize=16)
        plt.xlabel(r"$x\ (\mathrm{cMpc})$", fontsize=16)
        return (im)
    else:
        print("Zero metals found! Can not make metallicity \
              plot for: {0}".format(sim))
    
    impData = s[pynbody.filt.Cuboid(str((rx-sbox/2.0)) + " kpc", str((ry-sbox/2.0)) + " kpc",str((rz-sbox/4.0)) + " kpc",
                    str((rx+sbox/2.0)) + " kpc", str((ry+sbox/2.0)) + " kpc",str((rz+sbox/4.0)) + " kpc")]
    
    rect = [0.15,0.15,0.85,0.9]
    coords= [-rx,-ry,-rz] # Translation requires negative of the coord
    with pynbody.transformation.translate(impData,coords):
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.yaxis.set_visible(False)
        #ax.set_xlabel(fontsize=40)
        fileOut="img_log_ax_Z-z=%.1lf-%i.pdf"% (z,i)
        titleStr = "$Z_{\odot}$ - z = %.1lf" % z# + "\n[%.2lf %.2lf %.2lf]"%(rx,ry,rz)
        print (titleStr)
        sph.image(impData.g,qty="zsolar",width=smallbox,cmap="nipy_spectral", denoise=True ,av_z=False, subplot=ax,
            log=True, vmax=1.0, vmin=1e-6, qtytitle=r"${\rm log}\, \langle Z\rangle/Z_{\odot}$", approximate_fast=False
            ); #vmin=0.006, vmax=1.0,
        ax.set_xticks([-tic, 0, tic])
        ## ax.set_xticklabels(['-0.7','0','0.7'])
        plt.savefig(fileOut,dpi=fig.dpi,bbox_inches='tight')
        plt.close(fig)

        fig = plt.figure()
        ax = fig.add_subplot(111)
        #ax.yaxis.set_visible(False)
        #ax.set_xlabel(fontsize=40)
        fileOut="img_log_ax_Z-f_pol-z=%.1lf-%i.pdf"% (z,i)
        titleStr = r"$Z_{\odot}/f_{pol}$ - z = %.1lf" % z# + "\n[%.2lf %.2lf %.2lf]"%(rx,ry,rz)
        print (titleStr)
        sph.image(impData.g,qty="zEnhanced",width=smallbox,cmap="nipy_spectral", denoise=True ,av_z=False, subplot=ax,
            log=True, vmax=1.0, vmin=1e-6, qtytitle=r"${\rm log}\, Z/Z_{\odot}$", approximate_fast=False
Example #7
0
import pynbody
import pynbody.plot.sph as sph
import matplotlib.pylab as plt

# load the snapshot and set to physical units
s = pynbody.load('testdata/g15784.lr.01024.gz')
s.physical_units()

# load the halos
h = s.halos()

# center on the largest halo and align the disk
pynbody.analysis.angmom.faceon(h[1])

#create an image of gas density integrated down the line of site (z axis)
sph.image(h[1].g, qty="rho", units="g cm^-2", width=100, cmap="Greys")
Example #8
0
        default="pynmovie.mp4",
    )
    parser.add_option("-e", action="store", dest="script", help="preprocessing script to run on each simulation.")
    parser.add_option(
        "-n", action="store_false", dest="video", help="Don't actually produce a video, just make pngs.", default=True
    )
    (opts, args) = parser.parse_args()
    imgcount = 0
    try:
        (vmin, vmax) = [float(i) for i in opts.valrange.split()]
    except AttributeError:
        (vmin, vmax) = (None, None)
    if opts.script != None:
        sys.path.append(".")
        scriptfile = __import__(opts.script.split(".")[0])
    for i in args:
        if opts.script != None:
            scriptfile.process(i)
        else:
            sim = pyn.load(i)
            ptypes = {"gas": sim.gas, "dm": sim.dm, "stars": sim.stars}
            p_sph.image(ptypes[opts.ptype], units="m_p cm**-3", cmap="jet", vmin=vmin, vmax=vmax)
        plt.savefig("%09d.png" % (imgcount), dpi=150)
        imgcount += 1
    if opts.video:
        import envoy

        vid = envoy.run("ffmpeg  -qscale 1 -r %d -i %%09d.png %s" % (int(opts.fps), opts.outname))
        for i in range(imgcount):
            envoy.run("rm %09d.png" % (i))
Example #9
0
import pynbody
import pynbody.plot.sph as sph
import matplotlib.pylab as plt

# load the snapshot and set to physical units
s = pynbody.load('testdata/g15784.lr.01024.gz')
s.physical_units()

# load the halos
h = s.halos()

# center on the largest halo and align the disk
pynbody.analysis.angmom.sideon(h[1])

#create a simple slice showing the gas temperature
sph.image(h[1].g,qty="temp",width=50,cmap="YlOrRd", denoise=True,approximate_fast=False)

Example #10
0
import pynbody
import pynbody.plot.sph as sph
import matplotlib.pylab as plt

# load the snapshot and set to physical units
s = pynbody.load('testdata/g15784.lr.01024.gz')
s.physical_units()

# load the halos
h = s.halos()

# center on the largest halo and align the disk
pynbody.analysis.angmom.faceon(h[1])

#create a simple slice of gas density
sph.image(h[1].g,qty="rho",units="g cm^-3",width=100,cmap="Greys")

Example #11
0
def render(sim,
           filename=None,
           r_band='i',
           g_band='v',
           b_band='u',
           r_scale=0.5,
           g_scale=1.0,
           b_scale=1.0,
           dynamic_range=2.0,
           mag_range=None,
           width=50,
           starsize=None,
           plot=True,
           axes=None,
           ret_im=False,
           clear=True,
           ret_range=False):
    '''
    Make a 3-color image of stars.

    The colors are based on magnitudes found using stellar Marigo
    stellar population code.  However there is no radiative transfer
    to account for dust.

    Returns: If ret_im=True, an NxNx3 array representing an RGB image

    **Optional keyword arguments:**

       *filename*: string (default: None)
         Filename to be written to (if a filename is specified)

       *r_band*: string (default: 'i')
         Determines which Johnston filter will go into the image red channel

       *g_band*: string (default: 'v')
         Determines which Johnston filter will go into the image green channel

       *b_band*: string (default: 'b')
         Determines which Johnston filter will go into the image blue channel

       *r_scale*: float (default: 0.5)
         The scaling of the red channel before channels are combined

       *g_scale*: float (default: 1.0)
         The scaling of the green channel before channels are combined

       *b_scale*: float (default: 1.0)
         The scaling of the blue channel before channels are combined

       *width*: float in kpc (default:50)
         Sets the size of the image field in kpc

       *starsize*: float in kpc (default: None)
         If not None, sets the maximum size of stars in the image

       *ret_im*: bool (default: False)
         if True, the NxNx3 image array is returned

       *ret_range*: bool (default: False)
         if True, the range of the image in mag arcsec^-2 is returned.

       *plot*: bool (default: True)
         if True, the image is plotted

       *axes*: matplotlib axes object (deault: None)
         if not None, the axes object to plot to

       *dynamic_range*: float (default: 2.0)
         The number of dex in luminosity over which the image brightness ranges

       *mag_range*: float, float (default: None)
         If provided, the brightest and faintest surface brightnesses in the range,
         in mag arcsec^-2. Takes precedence over dynamic_range.
    '''

    if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase):
        if isinstance(width, str):
            width = _units.Unit(width)
        width = width.in_units(sim['pos'].units, **sim.conversion_context())

    if starsize is not None:
        smf = filt.HighPass('smooth', str(starsize) + ' kpc')
        sim.s[smf]['smooth'] = array.SimArray(starsize, 'kpc', sim=sim)

    r = image(sim.s,
              qty=r_band + '_lum_den',
              width=width,
              log=False,
              units="pc^-2",
              clear=False,
              noplot=True) * r_scale
    g = image(sim.s,
              qty=g_band + '_lum_den',
              width=width,
              log=False,
              units="pc^-2",
              clear=False,
              noplot=True) * g_scale
    b = image(sim.s,
              qty=b_band + '_lum_den',
              width=width,
              log=False,
              units="pc^-2",
              clear=False,
              noplot=True) * b_scale

    # convert all channels to mag arcsec^-2

    r = pynbody.plot.stars.convert_to_mag_arcsec2(r)
    g = pynbody.plot.stars.convert_to_mag_arcsec2(g)
    b = pynbody.plot.stars.convert_to_mag_arcsec2(b)

    #r,g,b = nw_scale_rgb(r,g,b)
    #r,g,b = nw_arcsinh_fit(r,g,b)

    if mag_range is None:
        rgbim, mag_max = pynbody.plot.stars.combine(r, g, b,
                                                    dynamic_range * 2.5)
        mag_min = mag_max + 2.5 * dynamic_range
    else:
        mag_max, mag_min = mag_range
        rgbim, mag_max = pynbody.plot.stars.combine(r, g, b, mag_min - mag_max,
                                                    mag_max)

    if plot:
        if clear:
            plt.clf()
        if axes is None:
            axes = plt.gca()

        if axes:
            axes.imshow(rgbim[::-1, :],
                        extent=(-width / 2, width / 2, -width / 2, width / 2))
            axes.set_xlabel('x [' + str(sim.s['x'].units) + ']')
            axes.set_ylabel('y [' + str(sim.s['y'].units) + ']')
            plt.draw()

    if filename:
        plt.axis('off')
        plt.savefig(filename, dpi=1600, figsize=(25, 25), bbox_inches='tight')

    if ret_im:
        return rgbim

    if ret_range:
        return mag_max, mag_min
Example #12
0
import matplotlib
matplotlib.use('Agg')
import pynbody
import pynbody.plot.sph as sph
import matplotlib.pyplot as plt
import numpy as np

pynbody.config['number_of_threads'] = 1
s = pynbody.load('/oasis/scratch/comet/mjt29/temp_project/Romulus25/cosmo25p.768sg1bwK1BHe75.008192')
halos = s.halos(dosort=True)
#numbers = [18, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 151, 152, 153, 154, 155, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 186, 187, 188, 189, 190, 191, 192, 193, 194, 196, 197, 198, 199, 200, 201, 202, 204, 206, 207, 208, 209, 210, 213, 214, 215, 216, 218, 219, 222, 223, 224, 225, 226, 229, 230, 232, 233, 234, 235, 236, 237, 239, 242, 244, 245, 247, 249, 252, 253, 254, 258, 260, 264, 265, 266, 273, 276, 283, 304, 310, 335]
numbers = [38]

for i in range(len(numbers)):
    h = halos.load_copy(i)
    h.physical_units()
    
    pynbody.analysis.halo.center(h, mode='hyb')
    pynbody.plot.stars.render(h, width='40 kpc')
    plt.savefig('stars_' + str(i) + '.png')
    plt.close()

    sph.image(h.g, qty="rho", units="g cm^-3", cmap="Greys")
    plt.savefig('gas_density_' + str(i) + '.png')
    plt.close()


rx,ry,rz = -121.77, -104.01, -203.10
tic = 0.8
i=0  # 00121, 0

print(rx,ry,rz)

impData = s[pynbody.filt.Cuboid(str((rx-sbox/2.0)) + " kpc", str((ry-sbox/2.0)) + " kpc",str((rz-sbox/4.0)) + " kpc",
                                str((rx+sbox/2.0)) + " kpc", str((ry+sbox/2.0)) + " kpc",str((rz+sbox/4.0)) + " kpc")]

rect = [0.15,0.15,0.85,0.9]
coords= [-rx,-ry,-rz] # Translation requires negative of the coord
with pynbody.transformation.translate(impData,coords):
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.xaxis.set_visible(True)
    ax.yaxis.set_visible(True)
    fileOut="img_log_ax_vel-z=%.1lf-%i.pdf"% (z,i)
    titleStr = "v - z = %.1lf" % z
    print (titleStr)
    sph.image(impData.g,qty="vel",width=smallbox,cmap="RdYlBu_r", denoise=True ,av_z=False, # units="km s^-1",
                      log=True, approximate_fast=False, subplot=ax, qtytitle=r"${\rm log}\, v\, {\rm km/s}$"
                      ); #vmin=0.006, vmax=1.0,
    plt.savefig(fileOut,dpi=fig.dpi,bbox_inches='tight') 
    plt.close(fig)
    

print("Fraction of PM ",
      np.sum(impData.g['rho'] * impData.g['x']**3 * impData.g['pzsolar']/impData.g['zsolar'])/np.sum(impData.g['rho'] * impData.g['x']**3))
Example #14
0
              run_realnames) in zip(isnap_images, runs):
 gizmoDir = gizmo_tools.getGizmoDir(run_dir)
 with tempfile.NamedTemporaryFile() as tf:
     for run_name, snap_list in zip(run_names, isnap_runs):
         fullDir = os.path.join(gizmoDir, run_dir, run_name)
         for ii, isnap in enumerate(snap_list):
             infile = f"{fullDir}/snapshot_{isnap:03d}.hdf5"
             header, snap = gizmo_tools.load_gizmo_nbody(
                 run_dir, run_name, f"{isnap:03d}")
             tt = header["time"] / t_orbit
             print(f"Rendering {run_name} {isnap} {tt}")
             for iwidth, width in enumerate(widths):
                 m = sph.image(snap.gas,
                               qty="rho",
                               units="g cm^-3",
                               width=f"{width} pc",
                               resolution=res,
                               noplot=True,
                               approximate_fast=True)
                 key = f"{run_dir}_{run_name}_{ii}_{iwidth}_face"
                 f_out[key] = m  # g/cm^2
                 # centre = snap[filt.disc(f"{width*2} pc",f"{width*2} pc")]
                 snap.rotate_x(90)
                 m = sph.image(snap.gas,
                               qty="rho",
                               units="g cm^-3",
                               width=f"{width} pc",
                               resolution=res,
                               noplot=True,
                               approximate_fast=True)
                 # m = generic.hist2d(centre["rxy"],centre["z"],gridsize=(res,res),weights=centre["mass"],make_plot=False)
Example #15
0
import pynbody
import pynbody.plot.sph as sph
import matplotlib.pylab as plt

# load the snapshot and set to physical units
s = pynbody.load('testdata/g15784.lr.01024.gz')
s.physical_units()

# load the halos
h = s.halos()

# center on the largest halo and align the disk
pynbody.analysis.angmom.faceon(h[1])

#create a simple slice of gas density
sph.image(h[1].g,qty="rho",units="g cm^-3",width=100,cmap="spectral")

Example #16
0
def colorCodedImage(sim, qtys, width = 60, resolution = 500, z_camera = None,
                    av_zs = (False, False), cmap = 'Reds', vmins = (None, None), 
                    vmaxs = (None, None), logs = (True, True)):
    """
    Generates an image as with pynbody.plot.sph.image with brightness set by
    one quantity and color set by a second quantity.
    
    Parameters
    ----------
    sim : SimSnap
        Snapshot or sub-snap to render
    qtys : list or tuple
        A tuple/list of 2 quantities (strings) to render.  The quantity are
        SimSnap keys, e.g. 'rho', 'temp', 'mass', etc.  The first quantity
        sets the brightness of the image, the second sets the color
    width : number
        Width of the plot to render
    resolution : int
        Number of pixels to render along each axis
    z_camera : number
        z-camera location (see pynbody.plot.sph.image)
    av_zs : tuple
        Average along line-of-sight (see pynbody.plot.sph.image).  If True,
        volume averating is used.  If a string averaging is over that qty.
        E.g., mass averaging can be acheived by using av_zs = ('rho', 'rho')
    cmap : str or cmap
        colormap to use for color-coding
    vmins, vmaxs : list/tuples
        vmin, vmax for the quantities (one for each quantity)
    logs : list/tuple
        List or tuple of booleans.  Defines whether color should use a log
        scale.
    
    Returns
    -------
    im : array
        The rendered RGB image used
    """
    cmaps = ('gray', cmap)
    ims = []
    # Generate the images
    for i in range(2):
        im = image(sim, qtys[i], width, resolution, av_z=av_zs[i], 
                           z_camera=z_camera, log=logs[i], vmin=vmins[i],
                           vmax=vmaxs[i], cmap=cmaps[i], ret_im=True)
        cb = plt.gcf().axes[-1]
        ims.append(im)
    
    # Grayscale image arrays
    grayims = [im.get_array() for im in ims]
    for i in range(2):
        grayims[i] = normalizeArray(grayims[i], logs[i], vmins[i], vmaxs[i])
    # Convert to rgb
    rgb = colorCodeArray(grayims[0], grayims[1], cmap=cmap)
    # Plot
    #rgb = mpl.colors.hsv_to_rgb(hsv)
    top = 0.5 * width
    plt.gca().imshow(rgb, extent = (-top, top, -top, top))
    # Add colorbar
    #ax = im.get_axes()
    cb = plt.colorbar(ims[1], orientation='vertical', label=qtys[1])
    cb = plt.colorbar(ims[0], orientation='horizontal', label=qtys[0])
    plt.ylabel('y ($' + sim['y'].units.latex() + '$)')
    plt.tight_layout()
    return rgb
Example #17
0
import matplotlib
matplotlib.use('Agg')
import pynbody
import pynbody.plot.sph as sph
import matplotlib.pyplot as plt
import numpy as np

pynbody.config['number_of_threads'] = 1
s = pynbody.load(
    '/oasis/scratch/comet/mjt29/temp_project/Romulus25/cosmo25p.768sg1bwK1BHe75.008192'
)
halos = s.halos(dosort=True)
#numbers = [18, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 102, 103, 104, 105, 106, 107, 108, 109, 110, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 151, 152, 153, 154, 155, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 186, 187, 188, 189, 190, 191, 192, 193, 194, 196, 197, 198, 199, 200, 201, 202, 204, 206, 207, 208, 209, 210, 213, 214, 215, 216, 218, 219, 222, 223, 224, 225, 226, 229, 230, 232, 233, 234, 235, 236, 237, 239, 242, 244, 245, 247, 249, 252, 253, 254, 258, 260, 264, 265, 266, 273, 276, 283, 304, 310, 335]
numbers = [38]

for i in range(len(numbers)):
    h = halos.load_copy(i)
    h.physical_units()

    pynbody.analysis.halo.center(h, mode='hyb')
    pynbody.plot.stars.render(h, width='40 kpc')
    plt.savefig('stars_' + str(i) + '.png')
    plt.close()

    sph.image(h.g, qty="rho", units="g cm^-3", cmap="Greys")
    plt.savefig('gas_density_' + str(i) + '.png')
    plt.close()
import pynbody
import pynbody.plot.sph as sph
import matplotlib.pylab as plt

# load the snapshot and set to physical units
s = pynbody.load('testdata/g15784.lr.01024.gz')
s.physical_units()

# load the halos
h = s.halos()

# center on the largest halo and align the disk
pynbody.analysis.angmom.faceon(h[1])

#create a simple slice of gas density
sph.image(h[1].g,qty="temp",width=50,cmap="spectral")

    z_crit = 2.0e-7
    # Fix birth times
    print s.derivable_keys()[1:5]
    pynbody.analysis.ramses_util.get_tform(s,"/home1/02744/earnric/bin/part2birth");

    if (len(s.s) > 0) :
        x,y,zz =  s.s['pos'][1] # Get the coords of the first SP
        print "Star Particle 1 coords: ", x,y,zz
        
        coords= [0, 0, -zz]
        with pynbody.transformation.translate(s,coords):
            try:
                titleStr = "Z - z = %.1lf" % z + "\ncoords %s"%str(coords)
                sph.image(s.g,qty="metal",width=boxsizestring,cmap="nipy_spectral", denoise=True ,av_z=False,
                          log=True, vmax=1.0, vmin=1e-7, approximate_fast=False,title=titleStr,
                          filename=fileOut); #vmin=0.006, vmax=1.0,
            except:
                print "EXCEPTION while plotting Z file: %s"%file
                pass
            try:
                fileOut="PGF-z=%.1lf%s.png"% (z,str(coords))
                titleStr = "PGF - z = %.1lf" % z + "\ncoords %s"%str(coords)
                sph.image(s.g,qty="pgf",width=boxsizestring,cmap="nipy_spectral", denoise=True ,av_z=False,
                          log=True, vmin=1e-7, approximate_fast=False,title=titleStr,
                          filename=fileOut); #vmin=0.006, vmax=1.0,
            except:
                print "EXCEPTION while plotting PFG file: %s"%file
                pass
            try:
                fileOut="Density-z=%.1lf%s.png"% (z,str(coords))
Example #20
0
def view(sim,
         k,
         components=['d'],
         angles=['faceon'],
         styles=['cmap'],
         figsize=(12, 6),
         clim=[],
         xcircle=0.1):
    s1 = load_s(sim, snapshots[k], 's')
    s2 = load_s(sim, snapshots[k + 1], 's')
    h1 = s1.halos()[1]
    h2 = s2.halos()[1]
    t1 = pynbody.array.SimArray(float(s1.properties['time'].in_units('Gyr')))
    t2 = pynbody.array.SimArray(float(s2.properties['time'].in_units('Gyr')))
    Rvir1 = rvir_fangzhou[k]
    Rvir2 = rvir_fangzhou[k + 1]

    for angle in angles:
        if angle == 'faceon':
            pynbody.analysis.angmom.faceon(h1)
            pynbody.analysis.angmom.faceon(h2)
        elif angle == 'sideon':
            pynbody.analysis.angmom.sideon(h1)
            pynbody.analysis.angmom.sideon(h2)
        else:
            print 'The angle is not right'

        for style in styles:
            if style == 'cmap':
                for component in components:
                    figure(figsize=figsize)

                    subplot(121)
                    ax1 = gca()
                    txt = ax1.text(0.03,
                                   0.8,
                                   r'$k = %i$' % (k),
                                   transform=ax1.transAxes,
                                   color='k',
                                   fontsize=14)
                    txt.set_path_effects(
                        [PathEffects.withStroke(linewidth=5, foreground='w')])
                    if component == 'd':
                        if size(clim) == 0:
                            im = sph.image(h1.d,
                                           qty="rho",
                                           units="g cm^-3",
                                           width=80,
                                           subplot=ax1,
                                           show_cbar=False,
                                           ret_im=True)
                            [vmin, vmax] = im.get_clim()
                        else:
                            sph.image(h1.d,
                                      qty="rho",
                                      units="g cm^-3",
                                      width=80,
                                      subplot=ax1,
                                      show_cbar=False,
                                      vmin=clim[0],
                                      vmax=clim[1])
                        txt = ax1.text(0.03,
                                       0.9,
                                       r'Dark matter',
                                       transform=ax1.transAxes,
                                       color='k',
                                       fontsize=14)
                    elif component == 's':
                        if size(clim) == 0:
                            im = sph.image(h1.s,
                                           qty="rho",
                                           units="g cm^-3",
                                           width=80,
                                           subplot=ax1,
                                           show_cbar=False,
                                           ret_im=True)
                            [vmin, vmax] = im.get_clim()
                        else:
                            sph.image(h1.s,
                                      qty="rho",
                                      units="g cm^-3",
                                      width=80,
                                      subplot=ax1,
                                      show_cbar=False,
                                      vmin=clim[0],
                                      vmax=clim[1])
                        txt = ax1.text(0.03,
                                       0.9,
                                       r'Stars',
                                       transform=ax1.transAxes,
                                       color='k',
                                       fontsize=14)
                    elif component == 'g':
                        if size(clim) == 0:
                            im = sph.image(h1.g,
                                           qty="rho",
                                           units="g cm^-3",
                                           width=80,
                                           subplot=ax1,
                                           show_cbar=False,
                                           ret_im=True)
                            [vmin, vmax] = im.get_clim()
                        else:
                            im = sph.image(h1.g,
                                           qty="rho",
                                           units="g cm^-3",
                                           width=80,
                                           subplot=ax1,
                                           show_cbar=False,
                                           vmin=clim[0],
                                           vmax=clim[1])
                        txt = ax1.text(0.03,
                                       0.9,
                                       r'Gas',
                                       transform=ax1.transAxes,
                                       color='k',
                                       fontsize=14)
                    else:
                        print 'Components not valid'
                    txt.set_path_effects(
                        [PathEffects.withStroke(linewidth=5, foreground='w')])

                    u_st = h1['pos'].units.latex()
                    xlabel("$x/%s$" % u_st)
                    ylabel("$y/%s$" % u_st)

                    ax = gca()
                    circle = Circle((0, 0),
                                    xcircle * Rvir1,
                                    color='k',
                                    fill=False)
                    ax.add_artist(circle)

                    if angle == 'faceon':
                        txt = ax1.text(0.75,
                                       0.9,
                                       r'Face on',
                                       transform=ax1.transAxes,
                                       color='k',
                                       fontsize=14)
                    elif angle == 'sideon':
                        txt = ax1.text(0.75,
                                       0.9,
                                       r'Side on',
                                       transform=ax1.transAxes,
                                       color='k',
                                       fontsize=14)
                    txt.set_path_effects(
                        [PathEffects.withStroke(linewidth=5, foreground='w')])

                    subplot(122)
                    ax2 = gca()
                    txt = ax2.text(0.03,
                                   0.8,
                                   r'$k +1 = %i$' % (k + 1),
                                   transform=ax2.transAxes,
                                   color='k',
                                   fontsize=14)
                    txt.set_path_effects(
                        [PathEffects.withStroke(linewidth=5, foreground='w')])
                    if component == 'd':
                        sph.image(h2.d,
                                  qty="rho",
                                  units="g cm^-3",
                                  width=80,
                                  subplot=ax2,
                                  show_cbar=False,
                                  vmin=vmin,
                                  vmax=vmax)  #,cmap="Greys")
                        txt = ax2.text(0.03,
                                       0.9,
                                       r'Dark matter',
                                       transform=ax2.transAxes,
                                       color='k',
                                       fontsize=14)
                    elif component == 's':
                        sph.image(h2.s,
                                  qty="rho",
                                  units="g cm^-3",
                                  width=80,
                                  subplot=ax2,
                                  show_cbar=False,
                                  vmin=vmin,
                                  vmax=vmax)  #,cmap="Greys")
                        txt = ax2.text(0.03,
                                       0.9,
                                       r'Stars',
                                       transform=ax2.transAxes,
                                       color='k',
                                       fontsize=14)
                    elif component == 'g':
                        sph.image(h2.g,
                                  qty="rho",
                                  units="g cm^-3",
                                  width=80,
                                  subplot=ax2,
                                  show_cbar=False,
                                  vmin=vmin,
                                  vmax=vmax)  #,cmap="Greys")
                        txt = ax2.text(0.03,
                                       0.9,
                                       r'Gas',
                                       transform=ax2.transAxes,
                                       color='k',
                                       fontsize=14)
                    else:
                        print 'Components not valid'
                    txt.set_path_effects(
                        [PathEffects.withStroke(linewidth=5, foreground='w')])

                    if angle == 'faceon':
                        txt = ax2.text(0.75,
                                       0.9,
                                       r'Face on',
                                       transform=ax2.transAxes,
                                       color='k',
                                       fontsize=14)
                    elif angle == 'sideon':
                        txt = ax2.text(0.75,
                                       0.9,
                                       r'Side on',
                                       transform=ax2.transAxes,
                                       color='k',
                                       fontsize=14)
                    txt.set_path_effects(
                        [PathEffects.withStroke(linewidth=5, foreground='w')])

                    ax = gca()
                    circle = Circle((0, 0),
                                    xcircle * Rvir1,
                                    color='k',
                                    fill=False)
                    ax.add_artist(circle)

                    show()

            elif style == 'HST':
                figure(figsize=figsize)

                subplot(121)
                ax1 = gca()
                ax1.text(0.03,
                         0.9,
                         r'HST image',
                         transform=ax1.transAxes,
                         color='w',
                         fontsize=14)
                ax1.text(0.03,
                         0.8,
                         r'$k = %i$' % (k),
                         transform=ax1.transAxes,
                         color='w',
                         fontsize=14)
                pynbody.plot.stars.render(s1,
                                          width='20 kpc',
                                          axes=ax1,
                                          plot=True,
                                          clear=False)

                u_st = s1['pos'].units.latex()
                xlabel("$x/%s$" % u_st)
                ylabel("$y/%s$" % u_st)

                ax = gca()
                circle = Circle((0, 0), xcircle * Rvir1, color='w', fill=False)
                ax.add_artist(circle)

                if angle == 'faceon':
                    ax1.text(0.75,
                             0.9,
                             r'Face on',
                             transform=ax1.transAxes,
                             color='w',
                             fontsize=14)
                elif angle == 'sideon':
                    ax1.text(0.75,
                             0.9,
                             r'Side on',
                             transform=ax1.transAxes,
                             color='w',
                             fontsize=14)

                subplot(122)
                ax2 = gca()
                ax2.text(0.03,
                         0.9,
                         r'HST image',
                         transform=ax2.transAxes,
                         color='w',
                         fontsize=14)
                ax2.text(0.03,
                         0.8,
                         r'$k +1 = %i$' % (k + 1),
                         transform=ax2.transAxes,
                         color='w',
                         fontsize=14)
                pynbody.plot.stars.render(s2,
                                          width='20 kpc',
                                          axes=ax2,
                                          plot=True,
                                          clear=False)
                u_st = s1['pos'].units.latex()
                xlabel("$x/%s$" % u_st)
                ylabel("$y/%s$" % u_st)

                ax = gca()
                circle = Circle((0, 0), xcircle * Rvir1, color='w', fill=False)
                ax.add_artist(circle)

                if angle == 'faceon':
                    ax2.text(0.75,
                             0.9,
                             r'Face on',
                             transform=ax2.transAxes,
                             color='w',
                             fontsize=14)
                elif angle == 'sideon':
                    ax2.text(0.75,
                             0.9,
                             r'Side on',
                             transform=ax2.transAxes,
                             color='w',
                             fontsize=14)

                show()

            else:
                print 'Style not compatible'
Example #21
0
import pynbody
import pynbody.plot.sph as sph
import matplotlib.pylab as plt

# load the snapshot and set to physical units
s = pynbody.load('testdata/g15784.lr.01024.gz')
s.physical_units()

# load the halos
h = s.halos()

# center on the largest halo and align the disk
pynbody.analysis.angmom.sideon(h[1])

#create a simple slice showing the gas temperature
sph.image(h[1].g,
          qty="temp",
          width=50,
          cmap="YlOrRd",
          denoise=True,
          approximate_fast=False)
indicies = np.in1d(s['iord'],outflow3)
outflow3_part = s[np.nonzero(indicies)]

#sph.image(outflow1_part.gas,units='m_p cm^-2', width=5*xymax)

#------------------------------------------------------
width = 3*xymax

fig = plt.figure(figsize=(7.,2.5))
fig.subplots_adjust(left=0.08, bottom=0.05, right=0.9, top=0.97, wspace=0.12, 
                    hspace=0.13)
gs = matplotlib.gridspec.GridSpec(1, 4, width_ratios=[4,4,4,1.4]) 
sps = [fig.add_subplot(gs[0]), fig.add_subplot(gs[1]), fig.add_subplot(gs[2]), fig.add_subplot(gs[3])] 
ax1 = (sps[0])
sim = sph.image(outflow1_part.gas,
                   units='m_p cm^-2', width=width,  clear=False,
                            title='0.1 Gyr ago',show_cbar=True,vmin=1e16,vmax=1e22,
                   subplot=sps[0],cmap='ocean_r');
for label in ax1.yaxis.get_ticklabels():
    label.set_fontsize(8)

for label in ax1.xaxis.get_ticklabels():
    label.set_fontsize(8)

ax1.set_title(ax1.get_title(),fontsize = 12)
circle1=plt.Circle((0,0),xymax,ec='black',fc='none')
ax1.add_artist(circle1)

#Ejected 1 Myr ago
ax2 = subplot(sps[1],sharey = ax1)
#ax2.set_fontsize(12)
sim = sph.image(outflow2_part.gas,