Ejemplo n.º 1
0
def PartProjAni(folder):
    yt.funcs.mylog.setLevel(50)
    ts = yt.load("/u/yali/" + folder + "/test/output/snapshot_*",
                 unit_base=unit_base,
                 bounding_box=bbox)

    #sorted(ds.field_list)
    #print(dir(ds.fields.PartType0))

    #plot = yt.ProjectionPlot(ts[0], 'x', 'density')
    plot = yt.ParticleProjectionPlot(ts[0], 'x', fields="Masses")
    #plot.set_zlim('density', 8e-29, 3e-26)

    fig = plot.plots['Masses'].figure

    def animate(i):
        ds = ts[i]
        plot._switch_ds(ds)
        plot.annotate_timestamp(corner='upper_left',
                                redshift=False,
                                draw_inset_box=True)
        plot.annotate_scale(corner='upper_right')

    plot.set_buff_size((200, 200))
    ani = FuncAnimation(fig, animate, frames=len(ts))
    return ani
Ejemplo n.º 2
0
def calcProjectionExtrema(Param_Dict, ds, field):
    """Creates dummy projection plots to then calculate the extrema in those.
    Returns a ytArray of these extrema"""
    try:
        if Param_Dict["ParticlePlot"]:
            projPlot = yt.ParticleProjectionPlot(ds, Param_Dict["NAxis"],
                                                 field)
        else:
            projPlot = yt.ProjectionPlot(ds, Param_Dict["NAxis"], field)
    except yt.utilities.exceptions.YTFieldNotFound:
        GUILogger.warning(f"Couldn't find {field} in the available fields")
        return
    ZMin = projPlot.frb[field].min()
    ZMax = projPlot.frb[field].max()
    return yt.YTArray([ZMin, ZMax])
Ejemplo n.º 3
0
def sphere_particle_projection(halo, fields, axes="xyz", output_dir=".",
                               sphere=None):
    if sphere is None:
        sphere = getattr(halo, 'data_object')
    if sphere is None:
        raise RuntimeError('No sphere provided.')

    yt.mylog.info(f"Projecting halo {int(halo.quantities['particle_identifier']):d}.")
    for axis in axes:
        plot = yt.ParticleProjectionPlot(halo.halo_catalog.data_ds, axis, fields,
                                         data_source=sphere,
                                         center=sphere.center,
                                         width=(2*sphere.radius))
        plot.set_axes_unit("pc")
        plot.annotate_title(f"M = {halo.quantities['particle_mass'].in_units('Msun')}.")
        plot.save(os.path.join(output_dir, f"halo_{int(halo.quantities['particle_identifier']):06d}"))
Ejemplo n.º 4
0
    def plot_particle_density(self, projection_plane, savename):
        """
        Inputs:
        ------
        projection_plane: int or str
            0,1,2 or 'x', 'y', 'z' to set which cross section of the 3D data is plotts
            
        savename: str
            String to save file name. Leave off the file extension

        Output:
        ------
        A 2D particle plot showing the mass density of the cut box 
        """

        bbox = 1.1 * np.array([[np.min(self.x), np.max(self.x)],
                               [np.min(self.y), np.max(self.y)],
                               [np.min(self.z), np.max(self.z)]])
        ds = yt.load_particles(self.data,
                               length_unit=kpc,
                               mass_unit=1e10,
                               bbox=bbox,
                               n_ref=4)
        center = self.com
        p = yt.ParticleProjectionPlot(
            ds, projection_plane,
            ['particle_mass'
             ])  #, center=center)#, width=self.box_size, depth=self.box_size)
        p.set_colorbar_label('particle_mass', 'Msun')
        #p.zoom(2)
        p.annotate_text((0.7, 0.85),
                        '%s Gyr' % round(self.header_time(), 2),
                        coord_system='figure',
                        text_args={'color': 'black'})
        p.save('%s' % savename)
        return
Ejemplo n.º 5
0
print('')
print('-------------------------------------------------------------------\n')

idx_start = args.idx_start
idx_end = args.idx_end
didx = args.didx
prefix = args.prefix

colormap = 'arbre'
dpi = 150
field = 'particle_mass'

yt.enable_parallelism()

ts = yt.load([
    prefix + '/Data_%06d' % idx for idx in range(idx_start, idx_end + 1, didx)
])

for ds in ts.piter():
    par = yt.ParticleProjectionPlot(ds, 2, field, center='c')
    par.set_background_color(field)
    par.set_zlim(field, 6.0e-6, 3.0e-4, dynamic_range=None)
    par.set_cmap(field, colormap)
    par.set_font({'size': 16})
    par.set_axes_unit('code_length')
    par.set_unit(field, 'code_mass')
    par.annotate_timestamp(time_unit='code_time',
                           corner='upper_right',
                           text_args={'color': 'k'})
    par.save(mpl_kwargs={"dpi": dpi})
Ejemplo n.º 6
0
ds.add_particle_filter("stars_old")

# What are the total masses of different ages of star in the whole simulation
# volume?
ad = ds.all_data()
mass_young = ad["stars_young", "particle_mass"].in_units("Msun").sum()
mass_medium = ad["stars_medium", "particle_mass"].in_units("Msun").sum()
mass_old = ad["stars_old", "particle_mass"].in_units("Msun").sum()
print("Mass of young stars = %g Msun" % mass_young)
print("Mass of medium stars = %g Msun" % mass_medium)
print("Mass of old stars = %g Msun" % mass_old)

# Generate 4 projections: gas density, young stars, medium stars, old stars
fields = [
    ("stars_young", "particle_mass"),
    ("stars_medium", "particle_mass"),
    ("stars_old", "particle_mass"),
]

prj1 = yt.ProjectionPlot(ds,
                         "z", ("gas", "density"),
                         center="max",
                         width=(100, "kpc"))
prj1.save()
prj2 = yt.ParticleProjectionPlot(ds,
                                 "z",
                                 fields,
                                 center="max",
                                 width=(100, "kpc"))
prj2.save()
Ejemplo n.º 7
0
def make_figure(figdir,
                DD,
                cen_name,
                simdir,
                haloname,
                simname,
                wd=30,
                wdd=30,
                wd2=300,
                wdd2=300):
    DDname = 'DD%.4i' % DD
    ds = yt.load('%s/%s/%s/%s/%s' %
                 (simdir, haloname, simname, DDname, DDname))

    def _stars(pfilter, data):
        return data[(pfilter.filtered_type, "particle_type")] == 2

    yt.add_particle_filter("stars",
                           function=_stars,
                           filtered_type='all',
                           requires=["particle_type"])
    ds.add_particle_filter('stars')
    cen_fits = fits.open(
        '/nobackupp2/rcsimons/foggie_momentum/anchor_files/%s/%s_DD%.4i_anchorprops.fits'
        % (cen_name, simname, DD))

    central_xyz_fit = np.load(
        '/nobackupp2/rcsimons/foggie_momentum/catalogs/center_natural.npy')[()]

    xf = central_xyz_fit['x']
    yf = central_xyz_fit['y']
    zf = central_xyz_fit['z']

    central_x = xf[0] * DD**4. + xf[1] * DD**3. + xf[2] * DD**2. + xf[
        3] * DD + xf[4]
    central_y = yf[0] * DD**4. + yf[1] * DD**3. + yf[2] * DD**2. + yf[
        3] * DD + yf[4]
    central_z = zf[0] * DD**4. + zf[1] * DD**3. + zf[2] * DD**2. + zf[
        3] * DD + zf[4]

    cen_central = yt.YTArray([central_x, central_y, central_z], 'kpc')

    W = yt.YTArray([wd, wd, wd], 'kpc')
    W2 = yt.YTArray([wd2, wd2, wd2], 'kpc')

    for sat_n in arange(12):
        if len(cen_fits['SAT_%.2i' % sat_n].data['box_avg']) > 0:
            cenx = cen_fits['SAT_%.2i' % sat_n].data['box_avg'][0]
            ceny = cen_fits['SAT_%.2i' % sat_n].data['box_avg'][1]
            cenz = cen_fits['SAT_%.2i' % sat_n].data['box_avg'][2]
            cen_g = yt.YTArray([cenx, ceny, cenz], 'kpc')
            for axis in ['x', 'y', 'z']:
                figname_zoomin = '%s_%.4i_%.2i_%s_zoomin.png' % (cen_name, DD,
                                                                 sat_n, axis)
                figname_zoomout = '%s_%.4i_%.2i_%s_zoomout.png' % (
                    cen_name, DD, sat_n, axis)
                if not os.path.exists('%s/%s' % (figdir, figname_zoomin)):
                    if axis == 'x':
                        box = ds.r[cen_g[0] - 0.5 * yt.YTArray(wdd, 'kpc'): cen_g[0]   + 0.5 * yt.YTArray(wdd, 'kpc'), \
                                   cen_g[1] - 0.5 * yt.YTArray(3*wd,  'kpc'): cen_g[1] + 0.5 * yt.YTArray(3*wd,  'kpc'), \
                                   cen_g[2] - 0.5 * yt.YTArray(3*wd,  'kpc'): cen_g[2] + 0.5 * yt.YTArray(3*wd,  'kpc')]

                        box2 = ds.r[cen_central[0] - 0.5 * yt.YTArray(wdd2, 'kpc'):   cen_central[0] + 0.5 * yt.YTArray(wdd2, 'kpc'), \
                                    cen_central[1] - 0.5 * yt.YTArray(3*wd2,  'kpc'): cen_central[1] + 0.5 * yt.YTArray(3*wd2,  'kpc'), \
                                    cen_central[2] - 0.5 * yt.YTArray(3*wd2,  'kpc'): cen_central[2] + 0.5 * yt.YTArray(3*wd2,  'kpc')]

                        p_1 = cen_g[1] - cen_central[1]
                        p_2 = cen_g[2] - cen_central[2]

                    elif axis == 'y':
                        box = ds.r[cen_g[0] - 0.5 * yt.YTArray(3*wd, 'kpc'): cen_g[0]   + 0.5 * yt.YTArray(3*wd, 'kpc'), \
                                   cen_g[1] - 0.5 * yt.YTArray(wdd,  'kpc'): cen_g[1]   + 0.5 * yt.YTArray(wdd,  'kpc'), \
                                   cen_g[2] - 0.5 * yt.YTArray(3*wd,  'kpc'): cen_g[2]  + 0.5 * yt.YTArray(3*wd,  'kpc')]

                        box2 = ds.r[cen_central[0] - 0.5 * yt.YTArray(3*wd2, 'kpc') : cen_central[0]  + 0.5 * yt.YTArray(3*wd2, 'kpc'), \
                                    cen_central[1] - 0.5 * yt.YTArray(wdd2,  'kpc') : cen_central[1]  + 0.5 * yt.YTArray(wdd2,  'kpc'), \
                                    cen_central[2] - 0.5 * yt.YTArray(3*wd2,  'kpc'): cen_central[2]  + 0.5 * yt.YTArray(3*wd2,  'kpc')]

                        p_1 = cen_g[0] - cen_central[0]
                        p_2 = cen_g[2] - cen_central[2]

                    elif axis == 'z':
                        box = ds.r[cen_g[0] - 0.5 * yt.YTArray(3*wd, 'kpc'): cen_g[0]   + 0.5 * yt.YTArray(3*wd, 'kpc'), \
                                   cen_g[1] - 0.5 * yt.YTArray(3*wd,  'kpc'): cen_g[1]  + 0.5 * yt.YTArray(3*wd,  'kpc'), \
                                   cen_g[2] - 0.5 * yt.YTArray(wdd,  'kpc'): cen_g[2] + 0.5 * yt.YTArray(wdd,  'kpc')]

                        box2 = ds.r[cen_central[0] - 0.5 * yt.YTArray(3*wd2, 'kpc'):  cen_central[0]   + 0.5 * yt.YTArray(3*wd2, 'kpc'), \
                                    cen_central[1] - 0.5 * yt.YTArray(3*wd2,  'kpc'): cen_central[1]  + 0.5 * yt.YTArray(3*wd2,  'kpc'), \
                                    cen_central[2] - 0.5 * yt.YTArray(wdd2,  'kpc'):  cen_central[2] + 0.5 * yt.YTArray(wdd2,  'kpc')]

                        p_1 = cen_g[0] - cen_central[0]
                        p_2 = cen_g[1] - cen_central[1]

                    fig = plt.figure(sat_n)

                    grid = AxesGrid(fig, (0.0, 0.0, 1.0, 1.0),
                                    nrows_ncols=(1, 2),
                                    axes_pad=0.0,
                                    label_mode="1",
                                    share_all=False,
                                    cbar_mode=None,
                                    aspect=False)

                    p = yt.ProjectionPlot(ds,
                                          axis, ("gas", "density"),
                                          center=cen_g,
                                          data_source=box,
                                          width=W)
                    p.set_unit(('gas', 'density'), 'Msun/pc**2')
                    p.set_zlim(('gas', 'density'),
                               zmin=density_proj_min * 0.1,
                               zmax=density_proj_max)
                    p.set_cmap(('gas', 'density'), density_color_map)
                    p.annotate_timestamp(corner='upper_left',
                                         redshift=True,
                                         draw_inset_box=True)
                    p.hide_axes()
                    p.annotate_timestamp(corner='upper_left',
                                         redshift=True,
                                         draw_inset_box=True)
                    p.annotate_scale(size_bar_args={'color': 'white'})
                    plot = p.plots[("gas", "density")]
                    plot.figure = fig
                    plot.axes = grid[0].axes
                    p._setup_plots()

                    p = yt.ParticleProjectionPlot(ds,
                                                  axis,
                                                  ('stars', 'particle_mass'),
                                                  center=cen_g,
                                                  data_source=box,
                                                  width=W)
                    cmp = plt.cm.Greys_r
                    cmp.set_bad('k')
                    p.set_cmap(field=('stars', 'particle_mass'), cmap=cmp)
                    p.hide_axes()
                    p.annotate_scale(size_bar_args={'color': 'white'})

                    p.set_zlim(field=('stars', 'particle_mass'),
                               zmin=2.e35 * 0.3,
                               zmax=1.e42 * 0.9)
                    plot = p.plots[('stars', 'particle_mass')]
                    plot.figure = fig
                    plot.axes = grid[1].axes
                    p._setup_plots()

                    fig.set_size_inches(12, 6)
                    fig.savefig('%s/%s' % (figdir, figname_zoomin))
                    plt.close(fig)

                    fig = plt.figure(sat_n)

                    grid = AxesGrid(fig, (0.0, 0.0, 1.0, 1.0),
                                    nrows_ncols=(1, 2),
                                    axes_pad=0.0,
                                    label_mode="1",
                                    share_all=False,
                                    cbar_mode=None,
                                    aspect=False)

                    p = yt.ProjectionPlot(ds,
                                          axis, ("gas", "density"),
                                          center=cen_central,
                                          data_source=box2,
                                          width=W2)
                    p.set_unit(('gas', 'density'), 'Msun/pc**2')
                    p.set_zlim(('gas', 'density'),
                               zmin=density_proj_min * 0.1,
                               zmax=density_proj_max)
                    p.set_cmap(('gas', 'density'), density_color_map)
                    p.annotate_timestamp(corner='upper_left',
                                         redshift=True,
                                         draw_inset_box=True)
                    p.hide_axes()
                    p.annotate_timestamp(corner='upper_left',
                                         redshift=True,
                                         draw_inset_box=True)
                    p.annotate_scale(size_bar_args={'color': 'white'})
                    plot = p.plots[("gas", "density")]
                    plot.figure = fig
                    plot.axes = grid[0].axes
                    p._setup_plots()
                    if (abs(p_1) < W2 / 2.) & (abs(p_2) < W2 / 2.):
                        plot.axes.scatter(p_1,
                                          p_2,
                                          marker='o',
                                          facecolor="none",
                                          edgecolor='red',
                                          lw=2,
                                          s=800)

                    p = yt.ParticleProjectionPlot(ds,
                                                  axis,
                                                  ('stars', 'particle_mass'),
                                                  center=cen_central,
                                                  data_source=box2,
                                                  width=W2)
                    cmp = plt.cm.Greys_r
                    cmp.set_bad('k')
                    p.set_cmap(field=('stars', 'particle_mass'), cmap=cmp)
                    p.hide_axes()
                    p.annotate_scale(size_bar_args={'color': 'white'})

                    p.set_zlim(field=('stars', 'particle_mass'),
                               zmin=2.e35 * 0.3,
                               zmax=1.e42 * 0.9)
                    plot = p.plots[('stars', 'particle_mass')]
                    plot.figure = fig
                    plot.axes = grid[1].axes
                    p._setup_plots()
                    if (abs(p_1) < W2 / 2.) & (abs(p_2) < W2 / 2.):
                        plot.axes.scatter(p_1,
                                          p_2,
                                          marker='o',
                                          facecolor="none",
                                          edgecolor='red',
                                          lw=2,
                                          s=800)
                    fig.set_size_inches(12, 6)
                    fig.savefig('%s/%s' % (figdir, figname_zoomout))
                    plt.close(fig)

        ds.index.clear_all_data()
Ejemplo n.º 8
0
print( '-------------------------------------------------------------------' )
for t in range( len(sys.argv) ):
   print str(sys.argv[t]),
print( '' )
print( '-------------------------------------------------------------------\n' )

idx_start  = args.idx_start
idx_end    = args.idx_end
didx       = args.didx
prefix_in  = args.prefix_in
prefix_out = args.prefix_out


yt.enable_parallelism()

ts = yt.load( [ prefix_in+'/Data_%06d'%idx for idx in range(idx_start, idx_end+1, didx) ] )
#ts = yt.load( 'Data_??????' )


for ds in ts.piter():

#  plot
   p = yt.ParticleProjectionPlot( ds, proj_axis, fields=field, center=center, width=(width_x,width_y), depth=width_z )
#  p.set_unit( field, 'Msun' )
#  p.set_zlim( field, 1.0e6, 1.0e8 )
   p.set_cmap( field, colormap )
   p.annotate_timestamp( time_unit='code_time', corner='upper_right', text_args={'color':'k'} )

#  save the image
   p.save( prefix_out+'_'+ds.basename+'.png', mpl_kwargs={'dpi':dpi} )
Ejemplo n.º 9
0
def ProjectionPlot(Param_Dict, worker):
    """Takes a DataSet object loaded with yt and performs a projectionPlot on
    it.
    Parameters:
        Param_Dict: Dict with Parameters
    """
    ds = Param_Dict["CurrentDataSet"]
    field = Param_Dict["ZAxis"]
    if Param_Dict["DomainDiv"]:
        # in case the user wants to divide everything by the domain_height,
        # we define a new field which is just the old field divided by height
        # and then do a projectionPlot for that.
        height = Param_Dict["FieldMaxs"]["DomainHeight"] - Param_Dict["FieldMins"]["DomainHeight"]
        field = "Normed " + field
        unit = yt.units.unit_object.Unit(Param_Dict["ZUnit"] + "/cm")
        realHeight = height.to_value("au")  # Important! Bugs occur if we just used "height"
        def _NormField(field, data):
            return data[Param_Dict["ZAxis"]]/realHeight/yt.units.au
        if Param_Dict["ParticlePlot"]:
            ds.add_field(("io", field), function=_NormField,
                     units="auto", dimensions=unit.dimensions,
                     force_override=True, particle_type=True)
        else:
            ds.add_field(("gas", field), function=_NormField,
                         units="auto", dimensions=unit.dimensions,
                         force_override=True)
    gridUnit = Param_Dict["GridUnit"]
    c0 = yt.YTQuantity(Param_Dict["XCenter"], gridUnit)
    c1 = yt.YTQuantity(Param_Dict["YCenter"], gridUnit)
    if Param_Dict["Geometry"] == "cartesian":
        c2 = yt.YTQuantity(Param_Dict["ZCenter"], gridUnit)
    else:
        c2 = Param_Dict["ZCenter"]
    width = (Param_Dict["HorWidth"], gridUnit)
    height = (Param_Dict["VerWidth"], gridUnit)
    if Param_Dict["ParticlePlot"]:
        plot = yt.ParticleProjectionPlot(ds, Param_Dict["NAxis"], field,
                                         axes_unit=Param_Dict["GridUnit"],
                                         weight_field=Param_Dict["WeightField"],
                                         fontsize=14, center=[c0, c1, c2],
                                         width=(width, height))
    else:
        if Param_Dict["NormVecMode"] == "Axis-Aligned":
            plot = yt.ProjectionPlot(ds, Param_Dict["NAxis"], field,
                                     axes_unit=Param_Dict["GridUnit"],
                                     weight_field=Param_Dict["WeightField"],
                                     fontsize=14, center=[c0, c1, c2],
                                     width=(width, height))
        else:
            normVec = [Param_Dict[axis + "NormDir"] for axis in ["X", "Y", "Z"]]
            northVec = [Param_Dict[axis + "NormNorth"] for axis in ["X", "Y", "Z"]]
            plot = yt.OffAxisProjectionPlot(ds, normVec, field,
                                            north_vector=northVec,
                                            weight_field=Param_Dict["WeightField"],
                                            axes_unit=Param_Dict["GridUnit"],
                                            fontsize=14, center=[c0, c1, c2],
                                            width=(width, height))
    emitStatus(worker, "Setting projection plot modifications")
    # Set min, max, unit log and color scheme:
    setAxisSettings(plot, Param_Dict, "Z")
    plot.zoom(Param_Dict["Zoom"])
    emitStatus(worker, "Annotating the projection plot")
    annotatePlot(Param_Dict, plot)
    finallyDrawPlot(plot, Param_Dict, worker)
Ejemplo n.º 10
0
                       function=new_star,
                       filtered_type="all",
                       requires=["ParCreTime"])

AllPar = ('all', 'particle_mass')
NewPar = ('new_star', 'particle_mass')

for ds in ts.piter():

    #  add the particle filter
    ds.add_particle_filter("new_star")

    #  face-on (all particles)
    pz = yt.ParticleProjectionPlot(ds,
                                   'z',
                                   AllPar,
                                   center=center_mode,
                                   width=(width_kpc, 'kpc'),
                                   depth=(depth_kpc, 'kpc'))
    pz.set_unit(AllPar, 'Msun')
    pz.set_zlim(AllPar, 1.0e6, 1.0e8)
    pz.set_cmap(AllPar, colormap)
    pz.annotate_timestamp(time_unit='Myr',
                          corner='upper_right',
                          text_args={'color': 'k'})
    pz.save(name=ds.basename + '_AllPar', mpl_kwargs={"dpi": dpi})

    #  face-on (new particles)
    pz = yt.ParticleProjectionPlot(ds,
                                   'z',
                                   NewPar,
                                   center=center_mode,
Ejemplo n.º 11
0
            p.annotate_timestamp(corner='upper_left',
                                 redshift=True,
                                 draw_inset_box=True)
            p.hide_axes()
            p.annotate_timestamp(corner='upper_left',
                                 redshift=True,
                                 draw_inset_box=True)
            p.annotate_scale(size_bar_args={'color': 'white'})
            plot = p.plots[("gas", "density")]
            plot.figure = fig
            plot.axes = grid[0].axes
            p._setup_plots()

            p = yt.ParticleProjectionPlot(ds,
                                          'y', ('stars', 'particle_mass'),
                                          center=cen_g,
                                          data_source=box,
                                          width=W)
            cmp = plt.cm.Greys_r
            cmp.set_bad('k')
            p.set_cmap(field=('stars', 'particle_mass'), cmap=cmp)
            p.hide_axes()
            p.annotate_scale(size_bar_args={'color': 'white'})

            p.set_zlim(field=('stars', 'particle_mass'),
                       zmin=2.e35,
                       zmax=1.e42)
            plot = p.plots[('stars', 'particle_mass')]
            plot.figure = fig
            plot.axes = grid[1].axes
            p._setup_plots()
Ejemplo n.º 12
0
    plt.legend()
    plt.xlim(t1, t2)
    plt.yscale('log')
    plt.title(r'$z={:.2f}$'.format(z))
    plt.tight_layout()
    plt.savefig(rep + 'tt_dis_' + str(sn) + '_' + str(ind) + '.pdf')
    plt.close()


ad = ds.box(le, re)

#"""
prj = yt.ParticleProjectionPlot(ds,
                                2, ('PartType0', 'Metallicity_00'),
                                center=cen,
                                width=((ext, 'kpccm/h'), (ext / asp,
                                                          'kpccm/h')),
                                depth=thk,
                                weight_field=('PartType0',
                                              'Masses'))  #, data_source=ad)
prj.set_zlim('all', 1e-6 * 0.02, 0.2)
prj.set_buff_size((xb, yb))
prj.annotate_title('$z={:.2f}$'.format(z))
prj.save(rep + 'metaldis_' + str(sn) + '.png')

prj = yt.ParticleProjectionPlot(ds,
                                2, ('PartType1', 'Masses'),
                                center=cen,
                                width=((ext, 'kpccm/h'), (ext / asp,
                                                          'kpccm/h')),
                                depth=thk,
                                density=True)  #, data_source=ad)
Ejemplo n.º 13
0
def make_figure(figdir,
                DD,
                cen_name,
                simdir,
                haloname,
                simname,
                wd=100.,
                wdd=100.,
                wd2=150.,
                wdd2=150.,
                wd3=1000.,
                wdd3=1000.):
    #figname_zoomoutfar = '%s_%.4i_%.2i_%s_zoomoutfar.png'%(cen_name, DD, 6, 'x')
    #figname_check = '%s/%s/%s/%s'%(figdir,'x', 'zoomoutfar', figname_zoomoutfar)
    #if os.path.isfile(figname_check): return

    DDname = 'DD%.4i' % DD
    ds = yt.load('%s/%s/%s/%s/%s' %
                 (simdir, haloname, simname, DDname, DDname))

    def _stars(pfilter, data):
        return data[(pfilter.filtered_type, "particle_type")] == 2

    yt.add_particle_filter("stars",
                           function=_stars,
                           filtered_type='all',
                           requires=["particle_type"])
    ds.add_particle_filter('stars')
    cen_fits = np.load(
        '/nobackupp2/rcsimons/foggie_momentum/catalogs/sat_interpolations/%s_interpolations_DD0150_new.npy'
        % cen_name,
        allow_pickle=True)[()]
    '''
        #encoding='latin1' is needed for loading python 2 pickles in python 3
        if 'natural' in cen_name:
            central_xyz_fit = np.load('/nobackupp2/rcsimons/foggie_momentum/catalogs/center_natural.npy', allow_pickle=True, encoding='latin1')[()]

        elif ('nref11n_nref10f' in cen_name) | ('nref11c_nref9f' in cen_name):
            central_xyz_fit = np.load('/nobackupp2/rcsimons/foggie_momentum/catalogs/center_nref11n_nref10f.npy', allow_pickle=True, encoding='latin1')[()]
        '''

    #central_x = cen_fits['CENTRAL']['fxe'](DD)
    #central_y = cen_fits['CENTRAL']['fye'](DD)
    #central_z = cen_fits['CENTRAL']['fze'](DD)

    central_x = cen_fits['CENTRAL']['fxe'](DD)
    central_y = cen_fits['CENTRAL']['fye'](DD)
    central_z = cen_fits['CENTRAL']['fze'](DD)

    print(central_x, central_y, central_z)
    '''
        xf = central_xyz_fit['x']
        yf = central_xyz_fit['y']
        zf = central_xyz_fit['z']
        '''
    #central_x = xf[0] * DD**4. + xf[1] * DD**3. + xf[2] * DD**2. + xf[3] * DD + xf[4]
    #central_y = yf[0] * DD**4. + yf[1] * DD**3. + yf[2] * DD**2. + yf[3] * DD + yf[4]
    #central_z = zf[0] * DD**4. + zf[1] * DD**3. + zf[2] * DD**2. + zf[3] * DD + zf[4]

    cen_central = yt.YTArray([central_x, central_y, central_z], 'kpc')

    W = yt.YTArray([wd, wd, wd], 'kpc')
    W2 = yt.YTArray([wd2, wd2, wd2], 'kpc')
    W3 = yt.YTArray([wd3, wd3, wd3], 'kpc')

    for axis in ['x']:  #@, 'y', 'z']:
        if axis == 'x':
            box2 = ds.r[cen_central[0] - 0.5 * yt.YTArray(wdd2, 'kpc'):   cen_central[0] + 0.5 * yt.YTArray(wdd2, 'kpc'), \
                        cen_central[1] - 0.5 * yt.YTArray(3*wd2,  'kpc'): cen_central[1] + 0.5 * yt.YTArray(3*wd2,  'kpc'), \
                        cen_central[2] - 0.5 * yt.YTArray(3*wd2,  'kpc'): cen_central[2] + 0.5 * yt.YTArray(3*wd2,  'kpc')]


            box3 = ds.r[cen_central[0] - 0.5 * yt.YTArray(wdd3, 'kpc'):   cen_central[0] + 0.5 * yt.YTArray(wdd3, 'kpc'), \
                        cen_central[1] - 0.5 * yt.YTArray(3*wd3,  'kpc'): cen_central[1] + 0.5 * yt.YTArray(3*wd3,  'kpc'), \
                        cen_central[2] - 0.5 * yt.YTArray(3*wd3,  'kpc'): cen_central[2] + 0.5 * yt.YTArray(3*wd3,  'kpc')]

        if axis == 'y':

            box2 = ds.r[cen_central[0] - 0.5 * yt.YTArray(3*wd2, 'kpc') : cen_central[0]  + 0.5 * yt.YTArray(3*wd2, 'kpc'), \
                        cen_central[1] - 0.5 * yt.YTArray(wdd2,  'kpc') : cen_central[1]  + 0.5 * yt.YTArray(wdd2,  'kpc'), \
                        cen_central[2] - 0.5 * yt.YTArray(3*wd2,  'kpc'): cen_central[2]  + 0.5 * yt.YTArray(3*wd2,  'kpc')]


            box3 = ds.r[cen_central[0] - 0.5 * yt.YTArray(3*wd3, 'kpc') : cen_central[0]  + 0.5 * yt.YTArray(3*wd3, 'kpc'), \
                        cen_central[1] - 0.5 * yt.YTArray(wdd3,  'kpc') : cen_central[1]  + 0.5 * yt.YTArray(wdd3,  'kpc'), \
                        cen_central[2] - 0.5 * yt.YTArray(3*wd3,  'kpc'): cen_central[2]  + 0.5 * yt.YTArray(3*wd3,  'kpc')]

        if axis == 'z':

            box2 = ds.r[cen_central[0] - 0.5 * yt.YTArray(3*wd2, 'kpc'):  cen_central[0]   + 0.5 * yt.YTArray(3*wd2, 'kpc'), \
                        cen_central[1] - 0.5 * yt.YTArray(3*wd2,  'kpc'): cen_central[1]  + 0.5 * yt.YTArray(3*wd2,  'kpc'), \
                        cen_central[2] - 0.5 * yt.YTArray(wdd2,  'kpc'):  cen_central[2] + 0.5 * yt.YTArray(wdd2,  'kpc')]


            box3 = ds.r[cen_central[0] - 0.5 * yt.YTArray(3*wd3, 'kpc'):  cen_central[0]   + 0.5 * yt.YTArray(3*wd3, 'kpc'), \
                        cen_central[1] - 0.5 * yt.YTArray(3*wd3,  'kpc'): cen_central[1]  + 0.5 * yt.YTArray(3*wd3,  'kpc'), \
                        cen_central[2] - 0.5 * yt.YTArray(wdd3,  'kpc'):  cen_central[2] + 0.5 * yt.YTArray(wdd3,  'kpc')]
        '''

            a = time.time()
            p_wd2_g= yt.ProjectionPlot(ds, axis, ("gas","density"), center = cen_central, data_source=box2, width=W2)
            b = time.time()
            print ('p_wd2_g', b-a)

            p_wd2_g.set_unit(('gas','density'), 'Msun/pc**2')
            p_wd2_g.set_zlim(('gas', 'density'), zmin = density_proj_min, zmax =  density_proj_max)
            p_wd2_g.set_cmap(('gas', 'density'), density_color_map)
            p_wd2_g.annotate_timestamp(corner='upper_left', redshift=True, draw_inset_box=True)
            p_wd2_g.hide_axes()
            p_wd2_g.annotate_timestamp(corner='upper_left', redshift=True, draw_inset_box=True)
            p_wd2_g.annotate_scale(size_bar_args={'color':'white'})



            a = time.time()
            p_wd2_s = yt.ParticleProjectionPlot(ds, axis, ('stars', 'particle_mass'), center = cen_central, data_source=box2, width = W2)   
            b = time.time()
            print ('p_wd2_s', b-a)

            cmp = plt.cm.Greys_r
            cmp.set_bad('k')
            p_wd2_s.set_cmap(field = ('stars','particle_mass'), cmap = cmp)
            p_wd2_s.hide_axes()
            p_wd2_s.annotate_scale(size_bar_args={'color':'white'})

            p_wd2_s.set_zlim(field = ('stars','particle_mass'), zmin = 2.e35 * 0.3, zmax = 1.e42*0.9)



            a = time.time()
            p_wd3_g= yt.ProjectionPlot(ds, axis, ("gas","density"), center = cen_central, data_source=box3, width=W3)
            b = time.time()
            print ('p_wd3_g', b-a)

            p_wd3_g.set_unit(('gas','density'), 'Msun/pc**2')
            p_wd3_g.set_zlim(('gas', 'density'), zmin = density_proj_min, zmax =  density_proj_max)
            p_wd3_g.set_cmap(('gas', 'density'), density_color_map)
            p_wd3_g.annotate_timestamp(corner='upper_left', redshift=True, draw_inset_box=True)
            p_wd3_g.hide_axes()
            p_wd3_g.annotate_timestamp(corner='upper_left', redshift=True, draw_inset_box=True)
            p_wd3_g.annotate_scale(size_bar_args={'color':'white'})


            a = time.time()
            p_wd3_s = yt.ParticleProjectionPlot(ds, axis, ('stars', 'particle_mass'), center = cen_central, data_source=box3, width = W3)   
            b = time.time()
            print ('p_wd3_s', b-a)
        
    
            cmp = plt.cm.Greys_r
            cmp.set_bad('k')
            p_wd3_s.set_cmap(field = ('stars','particle_mass'), cmap = cmp)
            p_wd3_s.hide_axes()
            p_wd3_s.annotate_scale(size_bar_args={'color':'white'})
            p_wd3_s.set_zlim(field = ('stars','particle_mass'), zmin = 2.e35 * 0.3, zmax = 1.e42*0.9)
            '''

        for sat_n in arange(6, 7):
            if sat_n < 6:
                cenx = cen_fits['SAT_%.2i' % sat_n]['fxe'](DD)
                ceny = cen_fits['SAT_%.2i' % sat_n]['fye'](DD)
                cenz = cen_fits['SAT_%.2i' % sat_n]['fze'](DD)

            if sat_n == 6:
                #cenx = cen_fits['CENTRAL']['fxe'](DD)
                #ceny = cen_fits['CENTRAL']['fye'](DD)
                #cenz = cen_fits['CENTRAL']['fze'](DD)

                cenx = cen_fits['CENTRAL']['fxe'](DD)
                ceny = cen_fits['CENTRAL']['fye'](DD)
                cenz = cen_fits['CENTRAL']['fze'](DD)

            cen_g = yt.YTArray([cenx, ceny, cenz], 'kpc')
            print('satellite center: ', cen_g)
            print('central center: ', cen_central)

            figname_zoomin = '%s_%.4i_%.2i_%s_zoomin_100kpc.png' % (
                cen_name, DD, sat_n, axis)
            figname_zoomout = '%s_%.4i_%.2i_%s_zoomout.png' % (cen_name, DD,
                                                               sat_n, axis)
            figname_zoomoutfar = '%s_%.4i_%.2i_%s_zoomoutfar.png' % (
                cen_name, DD, sat_n, axis)

            if axis == 'x':
                box = ds.r[cen_g[0] - 0.5 * yt.YTArray(wdd, 'kpc'): cen_g[0]   + 0.5 * yt.YTArray(wdd, 'kpc'), \
                           cen_g[1] - 0.5 * yt.YTArray(3*wd,  'kpc'): cen_g[1] + 0.5 * yt.YTArray(3*wd,  'kpc'), \
                           cen_g[2] - 0.5 * yt.YTArray(3*wd,  'kpc'): cen_g[2] + 0.5 * yt.YTArray(3*wd,  'kpc')]

                p_1 = cen_g[1] - cen_central[1]
                p_2 = cen_g[2] - cen_central[2]
                p_3 = cen_g[0] - cen_central[0]

            elif axis == 'y':
                box = ds.r[cen_g[0] - 0.5 * yt.YTArray(3*wd, 'kpc'): cen_g[0]   + 0.5 * yt.YTArray(3*wd, 'kpc'), \
                           cen_g[1] - 0.5 * yt.YTArray(wdd,  'kpc'): cen_g[1]   + 0.5 * yt.YTArray(wdd,  'kpc'), \
                           cen_g[2] - 0.5 * yt.YTArray(3*wd,  'kpc'): cen_g[2]  + 0.5 * yt.YTArray(3*wd,  'kpc')]
                p_1 = cen_g[2] - cen_central[2]
                p_2 = cen_g[0] - cen_central[0]
                p_3 = cen_g[1] - cen_central[1]

            elif axis == 'z':
                box = ds.r[cen_g[0] - 0.5 * yt.YTArray(3*wd, 'kpc'): cen_g[0]   + 0.5 * yt.YTArray(3*wd, 'kpc'), \
                           cen_g[1] - 0.5 * yt.YTArray(3*wd,  'kpc'): cen_g[1]  + 0.5 * yt.YTArray(3*wd,  'kpc'), \
                           cen_g[2] - 0.5 * yt.YTArray(wdd,  'kpc'): cen_g[2] + 0.5 * yt.YTArray(wdd,  'kpc')]

                p_1 = cen_g[0] - cen_central[0]
                p_2 = cen_g[1] - cen_central[1]
                p_3 = cen_g[2] - cen_central[2]

            fig = plt.figure(sat_n)

            grid = AxesGrid(fig, (0.0, 0.0, 1.0, 1.0),
                            nrows_ncols=(1, 2),
                            axes_pad=0.0,
                            label_mode="1",
                            share_all=False,
                            cbar_mode=None,
                            aspect=False)

            p = yt.ProjectionPlot(ds,
                                  axis, ("gas", "density"),
                                  center=cen_g,
                                  data_source=box,
                                  width=W)
            p.set_unit(('gas', 'density'), 'Msun/pc**2')
            p.set_zlim(('gas', 'density'),
                       zmin=density_proj_min,
                       zmax=density_proj_max)
            p.set_cmap(('gas', 'density'), density_color_map)
            p.annotate_timestamp(corner='upper_left',
                                 redshift=True,
                                 draw_inset_box=True)
            p.hide_axes()
            p.annotate_timestamp(corner='upper_left',
                                 redshift=True,
                                 draw_inset_box=True)
            p.annotate_scale(size_bar_args={'color': 'white'})
            plot = p.plots[("gas", "density")]
            plot.figure = fig
            plot.axes = grid[0].axes
            p._setup_plots()

            p = yt.ParticleProjectionPlot(ds,
                                          axis, ('stars', 'particle_mass'),
                                          center=cen_g,
                                          data_source=box,
                                          width=W)
            cmp = plt.cm.Greys_r
            cmp.set_bad('k')
            p.set_cmap(field=('stars', 'particle_mass'), cmap=cmp)
            p.hide_axes()
            p.annotate_scale(size_bar_args={'color': 'white'})

            p.set_zlim(field=('stars', 'particle_mass'),
                       zmin=2.e35 * 0.3,
                       zmax=1.e42 * 0.9)
            plot = p.plots[('stars', 'particle_mass')]
            plot.figure = fig
            plot.axes = grid[1].axes
            p._setup_plots()

            fig.set_size_inches(12, 6)
            fig.savefig('%s/%s/%s/%s' %
                        (figdir, axis, 'zoomin', figname_zoomin))
            plt.close(fig)
            '''
                fig = plt.figure(sat_n)
                
                grid = AxesGrid(fig, (0.0,0.0,1.0,1.0),
                                nrows_ncols = (1, 2),
                                axes_pad = 0.0, label_mode = "1",
                                share_all = False, cbar_mode=None,
                                aspect = False)        

                p = copy.copy(p_wd2_g)
                plot = p.plots[("gas","density")]
                plot.figure = fig
                plot.axes = grid[0].axes
                p._setup_plots()
                print (abs(p_1), abs(p_2), W2)
                if (abs(p_1) < wd2/2.) & (abs(p_2) < wd2/2.) & (abs(p_3) < wd2/2.): plot.axes.scatter(p_1, p_2, marker = 'o', facecolor = "none", edgecolor='red', lw = 2, s = 800)

                p = copy.copy(p_wd2_s)
                plot = p.plots[('stars','particle_mass')]
                plot.figure = fig
                plot.axes = grid[1].axes
                p._setup_plots()
                #if (abs(p_1) < wd2/2.) & (abs(p_2) < wd2/2.) & (abs(p_3) < wd2/2.): plot.axes.scatter(p_1, p_2, marker = 'o', facecolor = "none", edgecolor='red', lw = 2, s = 800)
                fig.set_size_inches(12, 6)                    
                fig.savefig('%s/%s/%s/%s'%(figdir,axis, 'zoomout', figname_zoomout))
                plt.close(fig)





                fig = plt.figure(sat_n)
                
                grid = AxesGrid(fig, (0.0,0.0,1.0,1.0),
                                nrows_ncols = (1, 2),
                                axes_pad = 0.0, label_mode = "1",
                                share_all = False, cbar_mode=None,
                                aspect = False)        
                p = copy.copy(p_wd3_g)
                plot = p.plots[("gas","density")]
                plot.figure = fig
                plot.axes = grid[0].axes
                p._setup_plots()
                print (abs(p_1), abs(p_2), W2)
                #if (abs(p_1) < wd3/2.) & (abs(p_2) < wd3/2.) & (abs(p_3) < wdd3/2.): plot.axes.scatter(p_1, p_2, marker = 'o', facecolor = "none", edgecolor='red', lw = 2, s = 800)

                p = copy.copy(p_wd3_s)
                plot = p.plots[('stars','particle_mass')]
                plot.figure = fig
                plot.axes = grid[1].axes
                p._setup_plots()
                #if (abs(p_1) < wd3/2.) & (abs(p_2) < wd3/2.) & (abs(p_3) < wdd3/2.): plot.axes.scatter(p_1, p_2, marker = 'o', facecolor = "none", edgecolor='red', lw = 2, s = 800)
                fig.set_size_inches(12, 6)                    
                fig.savefig('%s/%s/%s/%s'%(figdir,axis, 'zoomoutfar', figname_zoomoutfar))
                plt.close(fig)
                '''

    ds.index.clear_all_data()
Ejemplo n.º 14
0
ds = yt.load(filename)
ds.add_particle_filter('stars_young')
ds.add_particle_filter('stars_medium')
ds.add_particle_filter('stars_old')

# What are the total masses of different ages of star in the whole simulation
# volume?
ad = ds.all_data()
mass_young = ad['stars_young', 'particle_mass'].in_units('Msun').sum()
mass_medium = ad['stars_medium', 'particle_mass'].in_units('Msun').sum()
mass_old = ad['stars_old', 'particle_mass'].in_units('Msun').sum()
print("Mass of young stars = %g Msun" % mass_young)
print("Mass of medium stars = %g Msun" % mass_medium)
print("Mass of old stars = %g Msun" % mass_old)

# Generate 4 projections: gas density, young stars, medium stars, old stars
fields = [('stars_young', 'particle_mass'), ('stars_medium', 'particle_mass'),
          ('stars_old', 'particle_mass')]

prj1 = yt.ProjectionPlot(ds,
                         'z', ("gas", "density"),
                         center="max",
                         width=(100, "kpc"))
prj1.save()
prj2 = yt.ParticleProjectionPlot(ds,
                                 'z',
                                 fields,
                                 center="max",
                                 width=(100, 'kpc'))
prj2.save()
   y = data[2]
   z = data[3]

   data_dic = { 'particle_mass'      : m,
                'particle_position_x': x,
                'particle_position_y': y,
                'particle_position_z': z }

   bbox_width = [ max(x)-min(x), max(y)-min(y), max(z)-min(z) ]
   bbox       = np.array(  [  [ min(x)-bext*bbox_width[0], max(x)+bext*bbox_width[0] ],
                              [ min(y)-bext*bbox_width[1], max(y)+bext*bbox_width[1] ],
                              [ min(z)-bext*bbox_width[2], max(z)+bext*bbox_width[2] ]  ]  )

   ds = yt.load_particles( data_dic, length_unit=unit_l, mass_unit=unit_m, time_unit=unit_t,
                           n_ref=nref, bbox=bbox, sim_time=time, periodicity=(False,False,False) )


#  plot
   p = yt.ParticleProjectionPlot( ds, proj_axis, fields=field, center=plot_center,
                                  width=(plot_width[0],plot_width[1]), depth=plot_width[2] )
#  p = yt.ParticlePlot( ds, 'particle_position_x', 'particle_position_y', 'particle_mass' )

   p.set_unit( field, 'Msun' )
   p.set_unit( 'particle_position_x', 'Mpc' )
   p.set_unit( 'particle_position_y', 'Mpc' )
   p.set_zlim( field, 1.0e0, 6.0e0 )
   p.set_cmap( field, colormap )
   p.annotate_timestamp( time_unit='Myr', corner='upper_right', text_args={'color':'k'} )

   p.save( prefix_out+'_%06d'%idx+'.png', mpl_kwargs={'dpi':dpi} )