Esempio n. 1
0
def plot_series(ts):
    for sto, ds in ts.piter(storage=storage):
        for z in z_fields:
            for xy in xy_fields:
                ad = ds.all_data()

                outflow_criteria = hot_domain + a + high_Z + a + pos_Vr
                inflow_criteria = low_Z + a + cold_domain + a + neg_Vr

                outflow_region = ad.cut_region([outflow_criteria])
                inflow_region = ad.cut_region([inflow_criteria])
                cgm_region = ad - outflow_region - inflow_region

                for region in regions.keys():
                    if (xy[0] == 'radius'):
                        pp = yt.PhasePlot(regions.get(region),
                                          xy[0],
                                          xy[1],
                                          'entropy',
                                          weight_field=None)
                    else:
                        pp = yt.PhasePlot(regions.get(region),
                                          xy[0],
                                          xy[1],
                                          z,
                                          weight_field=None)

                    x_and_y_fields = xy[0] + '_vs_' + xy[1]
                    path = "%s/%s/%s" % (region, z, x_and_y_fields)
                    #pp.set_zlim(z, 1e-1, 1e5)
                    #pp.set_log(z, False)
                    pp.annotate_title(region)
                    pp.set_cmap(z, "kamae")
                    #print('dataset: %s' % ds)
                    pp.save(path + "_%s" % ds)
Esempio n. 2
0
def test_create_from_dataset():
    ds = fake_random_ds(16)
    plot1 = yt.ProfilePlot(
        ds,
        ("index", "radius"),
        [("gas", "velocity_x"), ("gas", "density")],
        weight_field=None,
    )
    plot2 = yt.ProfilePlot(
        ds.all_data(),
        ("index", "radius"),
        [("gas", "velocity_x"), ("gas", "density")],
        weight_field=None,
    )
    assert_allclose_units(plot1.profiles[0][("gas", "density")],
                          plot2.profiles[0][("gas", "density")])
    assert_allclose_units(plot1.profiles[0]["velocity_x"],
                          plot2.profiles[0]["velocity_x"])

    plot1 = yt.PhasePlot(ds, ("gas", "density"), ("gas", "velocity_x"),
                         ("gas", "cell_mass"))
    plot2 = yt.PhasePlot(ds.all_data(), ("gas", "density"),
                         ("gas", "velocity_x"), ("gas", "cell_mass"))
    assert_allclose_units(plot1.profile["cell_mass"],
                          plot2.profile["cell_mass"])
def test_phase():
    es = sim_dir_load(_pf_name, path=_dir_name)
    es.get_time_series(redshifts=[0])
    ds = es[-1]
    ad = ds.all_data()
    profile = ad.profile([("gas", "density")], [("gas", "temperature"),
                                                ("gas", "cell_mass")])
    profile1 = ad.profile([("gas", "density")], [("gas", "temperature"),
                                                 ("gas", "cooling_time")],
                          weight_field=('gas', 'cell_mass'))
    density = profile.x
    temperature = profile[('gas', 'temperature')]
    cooling_time = profile1[('gas', 'cooling_time')]
    cell_mass = profile[('gas', 'cell_mass')]

    filename = 'phase_data.h5'
    save_filename = os.path.join(_dir_name, filename)
    data = {
        ('data', 'density'): density,
        ('data', 'temperature'): temperature,
        ('data', 'cooling_time'): cooling_time,
        ('data', 'cell_mass'): cell_mass
    }
    yt.save_as_dataset(ds, save_filename, data)

    pp = yt.PhasePlot(ad, ('gas', 'density'), ('gas', 'temperature'),
                      ('gas', 'cell_mass'))
    pp.set_unit(('gas', 'cell_mass'), 'Msun')
    pp.save(_dir_name)
    pp1 = yt.PhasePlot(ad, ('gas', 'density'), ('gas', 'temperature'),
                       ('gas', 'cooling_time'),
                       weight_field=('gas', 'cell_mass'))
    pp1.save(_dir_name)

    compare_filename = os.path.join(test_data_dir, filename)
    if generate_answers:
        os.rename(save_filename, compare_filename)
        return

        # do the comparison
    ds_comp = yt.load(compare_filename)

    # assert quality to 8 decimals
    assert_rel_equal(data[('data', 'density')],
                     ds_comp.data[('data', 'density')], 8)
    assert_rel_equal(data[('data', 'temperature')],
                     ds_comp.data[('data', 'temperature')], 8)
    assert_rel_equal(data[('data', 'cooling_time')],
                     ds_comp.data[('data', 'cooling_time')], 8)
    assert_rel_equal(data[('data', 'cell_mass')],
                     ds_comp.data[('data', 'cell_mass')], 8)
Esempio n. 4
0
def test_create_from_dataset():
    ds = fake_random_ds(16)
    plot1 = yt.ProfilePlot(ds, "radius", ["velocity_x", "density"],
                           weight_field=None)
    plot2 = yt.ProfilePlot(ds.all_data(), "radius", ["velocity_x", "density"],
                           weight_field=None)
    assert_allclose_units(
        plot1.profiles[0]['density'], plot2.profiles[0]['density'])
    assert_allclose_units(
        plot1.profiles[0]['velocity_x'], plot2.profiles[0]['velocity_x'])

    plot1 = yt.PhasePlot(ds, 'density', 'velocity_x', 'cell_mass')
    plot2 = yt.PhasePlot(ds.all_data(), 'density', 'velocity_x', 'cell_mass')
    assert_allclose_units(
        plot1.profile['cell_mass'], plot2.profile['cell_mass'])
Esempio n. 5
0
    def generate_plot(self):
        source = self.parent.active_data_object.data
        x_field = self.x_field.get_field()
        y_field = self.y_field.get_field()
        z_field = self.z_field.get_fields()
        weight_field = self.weight_field.get_field()
        if weight_field[0] == 'None':
            weight_field = None
        elif weight_field[0] == 'Default':
            weight_field = 'cell_mass'
        x_bins = self.x_bins.value()
        y_bins = self.y_bins.value()
        accumulation = self.accumulation.currentText() == 'True'
        fractional = self.fractional.currentText() == 'True'
        fontsize = self.fontsize.value()

        plot = yt.PhasePlot(source,
                            x_field,
                            y_field,
                            z_field,
                            weight_field=weight_field,
                            x_bins=x_bins,
                            y_bins=y_bins,
                            accumulation=accumulation,
                            fractional=fractional,
                            fontsize=fontsize)
        view = PlotWindowView(plot)
        self.plot_ref.addSubWindow(view)
        view.show()
Esempio n. 6
0
def test_phaseplot_set_log():
    fields = ('density', 'temperature')
    units = (
        'g/cm**3',
        'K',
    )
    ds = fake_random_ds(16, fields=fields, units=units)
    sp = ds.sphere("max", (1.0, "Mpc"))
    p1 = yt.ProfilePlot(sp, "radius", ("gas", "density"))
    p2 = yt.PhasePlot(sp, ("gas", "density"), ("gas", "temperature"),
                      "cell_mass")
    # make sure we can set the log-scaling using the tuple without erroring out
    p1.set_log(("gas", "density"), False)
    p2.set_log(("gas", "temperature"), False)
    assert not p1.y_log["gas", "density"]
    assert not p2.y_log

    # make sure we can set the log-scaling using a string without erroring out
    p1.set_log("density", True)
    p2.set_log("temperature", True)
    assert p1.y_log["gas", "density"]
    assert p2.y_log

    # make sure we can set the log-scaling using a field object
    p1.set_log(ds.fields.gas.density, False)
    p2.set_log(ds.fields.gas.temperature, False)
    assert not p1.y_log["gas", "density"]
    assert not p2.y_log
Esempio n. 7
0
    def test_unequal_bin_field_profile(self):
        density = np.random.random(128)
        temperature = np.random.random(127)
        mass = np.random.random((128, 128))

        my_data = {
            ("gas", "density"): density,
            ("gas", "temperature"): temperature,
            ("gas", "mass"): mass,
        }
        fake_ds_med = {"current_time": yt.YTQuantity(10, "Myr")}
        field_types = {field: "gas" for field in my_data.keys()}
        yt.save_as_dataset(fake_ds_med,
                           "mydata.h5",
                           my_data,
                           field_types=field_types)

        ds = yt.load("mydata.h5")

        with assert_raises(YTProfileDataShape):
            yt.PhasePlot(
                ds.data,
                ("gas", "temperature"),
                ("gas", "density"),
                ("gas", "mass"),
            )
Esempio n. 8
0
def test_phaseplot_showhide_colorbar_axes():
    fields = ('density', 'temperature')
    units = ('g/cm**3', 'K',)
    ds = fake_random_ds(16, fields=fields, units=units)
    ad = ds.all_data()
    plot = yt.PhasePlot(ad, ("gas", "density"), ("gas", "temperature"), "cell_mass")

    # make sure we can hide colorbar
    plot.hide_colorbar()
    with tempfile.NamedTemporaryFile(suffix='png') as f1:
        plot.save(f1.name)

    # make sure we can show colorbar
    plot.show_colorbar()
    with tempfile.NamedTemporaryFile(suffix='png') as f2:
        plot.save(f2.name)

    # make sure we can hide axes
    plot.hide_axes()
    with tempfile.NamedTemporaryFile(suffix='png') as f3:
        plot.save(f3.name)

    # make sure we can show axes
    plot.show_axes()
    with tempfile.NamedTemporaryFile(suffix='png') as f4:
        plot.save(f4.name)
Esempio n. 9
0
def PhasePlot(Param_Dict, worker):
    """Takes a DataSet object loaded with yt and performs a phasePlot on it.
    Parameters:
        Param_Dict: to access the relevant parameters
    """
    if Param_Dict["WeightField"] is None:
        GUILogger.warning('Having <font color="DarkViolet">None</font> as the '
                          "weight field just accumulates, "
                          "so the extrema might be inaccurate.")
    ds = Param_Dict["CurrentDataSet"]
    XField, YField, ZField = Param_Dict["XAxis"], Param_Dict["YAxis"], \
        Param_Dict["ZAxis"]
    ad = ds.all_data()
    if Param_Dict["ParticlePlot"]:
        plot = yt.ParticlePhasePlot(ad, XField, YField, ZField,
                                    weight_field=Param_Dict["WeightField"],
                                    fontsize=14)
    else:
        plot = yt.PhasePlot(ad, XField, YField, ZField,
                            weight_field=Param_Dict["WeightField"],
                            fontsize=14)
    emitStatus(worker, "Setting phase plot modifications")
    # Set min, max, unit log and color scheme:
    setAxisSettings(plot, Param_Dict, "X")
    setAxisSettings(plot, Param_Dict, "Y")
    setAxisSettings(plot, Param_Dict, "Z")
    emitStatus(worker, "Annotating the phase plot")
    plot.annotate_title(Param_Dict["PlotTitle"])
    finallyDrawPlot(plot, Param_Dict, worker)
Esempio n. 10
0
def test_set_units():
    ds = yt.load(ETC46)
    sp = ds.sphere("max", (1.0, "Mpc"))
    p1 = yt.ProfilePlot(sp, "radius", ("enzo", "Density"))
    p2 = yt.PhasePlot(sp, ("enzo", "Density"), ("enzo", "Temperature"),
                      "cell_mass")
    # make sure we can set the units using the tuple without erroring out
    p1.set_unit(("enzo", "Density"), "Msun/kpc**3")
    p2.set_unit(("enzo", "Temperature"), "R")
Esempio n. 11
0
def phase_plots(ds, to_plot = 'all', region = None):

    # construct a list of phase diagrams here. List contains list of tuples, where each
    # list is the following set of 4 items:  [ x-axis field, y-axis field, cbar field, weight_field ]
    #
    pp_def    = { 'T_n' :  [ ('gas','number_density'), ('enzo','Temperature'), ('gas','cell_mass'), None],
                  'T_n_Fe' :  [ ('gas','number_density'), ('enzo','Temperature'), ('gas','Fe_Mass'), None],
                  'T_n_O'  :  [ ('gas','number_density'), ('enzo','Temperature'), ('gas','O_Mass'), None],
                  'T_n_C'  :  [ ('gas','number_density'), ('enzo','Temperature'), ('gas','C_Mass'), None],
                  'P_T' :  [ ('enzo','Temperature'), ('gas','pressure'), ('gas', 'cell_mass'), None],
                  'Go_n' : [ ('gas','number_density'), ('gas','G_o'), ('gas','cell_mass'), None],
                  'Go_r' : [ ('index','magnitude_cylindrical_radius'), ('gas','G_o'), ('gas','cell_mass'), None]
                 }

    pdict = {}
    if to_plot == 'all':
        for n in ['T_n_Fe','T_n_O','T_n','P_T','Go_n','T_n_C']:
            pdict[n] = pp_def[n]

    if region is None:
        region = ds.all_data()

    #print(cbar_lim)

    for name in pdict:
        pdef = pdict[name]

        pp = yt.PhasePlot( region, pdef[0], pdef[1], pdef[2],
                           weight_field = pdef[3])

        if pdef[0] == ('gas','magnitude_cylindrical_radius'):
            pp.set_log('magnitude_cylindrical_radius', False)

        # set units on each axis
        for f in pdef[:3]:
            pp.set_unit(f[1], field_units[f].units)

        # set plot limits for horizonatal and vertical axes
        if not plim[pdef[0]] is None:
            pp.set_xlim(plim[pdef[0]][0], plim[pdef[0]][1])
        if not plim[pdef[1]] is None:
            pp.set_ylim(plim[pdef[1]][0], plim[pdef[1]][1])

        # set color map limits
        #print((cbar_lim[pdef[2]], pdef[2]))
        if not (cbar_lim[pdef[2]] is None):
            pp.set_zlim( pdef[2], cbar_lim[pdef[2]][0], cbar_lim[pdef[2]][1])

        pp.set_cmap( pdef[2], 'cubehelix')

        pp.save('./phase_plots/')

        del(pp)


    return
Esempio n. 12
0
def test_set_units():
    fields = ('density', 'temperature')
    units = ('g/cm**3', 'K',)
    ds = fake_random_ds(16, fields=fields, units=units)
    sp = ds.sphere("max", (1.0, "Mpc"))
    p1 = yt.ProfilePlot(sp, "radius", ("gas", "density"))
    p2 = yt.PhasePlot(sp, ("gas", "density"), ("gas", "temperature"), "cell_mass")
    # make sure we can set the units using the tuple without erroring out
    p1.set_unit(("gas", "density"), "Msun/kpc**3")
    p2.set_unit(("gas", "temperature"), "R")
def plot_phase(output, sim, tctf, beta_list, cr_list, diff_list, stream_list,
               heat_list, title_list):

    cmap_list = [palettable.cmocean.sequential.Tempo_20.mpl_colormap]
    ncols = int(len(cr_list) / 2)
    nrows = 2
    fig, ax = plt.subplots(ncols=ncols,
                           nrows=nrows,
                           figsize=(4 * ncols, 4.4 * nrows))

    for i, cr in enumerate(cr_list):
        sim_loc = pt.get_sim_location(sim, tctf, beta_list[i], cr, \
                                      diff = diff_list[i], stream = stream_list[i], heat = heat_list[i], work_dir = workdir)
        ds = ytf.load('%s/DD%04d/DD%04d' % (sim_loc, output, output))

        ad = ds.all_data()
        ad_cut = ad.cut_region([
            "(obj[('gas', 'z')].in_units('kpc') > 4.3) | (obj[('gas', 'z')].in_units('kpc') < -4.3)"
        ])
        ph = yt.PhasePlot(ad_cut, ('gas', 'density'), ('gas', 'temperature'), ('gas', 'cell_mass'),\
                          weight_field = None, fractional = True)
        ph.save()
        prof = ph.profile
        xbins = prof.x
        ybins = prof.y
        data = prof[('gas', 'cell_mass')].T

        print(xbins, ybins, data)
        vmin = 1e-5
        vmax = 1e-2
        cmap = cmap_list[0]
        cmap = palettable.cubehelix.jim_special_16_r.mpl_colormap

        row = int(i / ncols)
        col = i - row * ncols
        print(i, row, col)
        ax[row][col].set_xscale('log')
        ax[row][col].set_yscale('log')
        ax[row][col].set_xlim(1.5e-28, 8e-26)
        ax[row][col].set_ylim(4e4, 1e7)

        pcm = ax[row][col].pcolormesh(xbins, ybins, data, norm = LogNorm(), cmap = cmap, \
                               vmax = vmax, vmin = vmin)

        ax[row][col].set_title(title_list[i], fontsize=16)
        ax[row][col].set_xlabel('Density (g cm$^{-3}$)')
        ax[row][col].set_ylabel('Temperature (K)')

    figname = '../../plots/production/phase_density_temperature_mass_%s_tctf_%.1f_cr_%.2f_%.1f.png' % (
        sim, tctf, cr, output)

    fig.tight_layout()
    print(figname)
    plt.savefig(figname, dpi=300)
def plot_phase(output, folder='.'):

    cmap_list = [palettable.cmocean.sequential.Tempo_20.mpl_colormap]
    ncols = int(len(cr_list) / 2)
    nrows = 2
    fig, ax = plt.subplots(ncols=ncols,
                           nrows=nrows,
                           figsize=(4 * ncols, 4.4 * nrows))

    for i, cr in enumerate(cr_list):
        sim_loc = pt.get_sim_location(sim, tctf, beta_list[i], cr, \
                diff = diff_list[i], stream = stream_list[i], heat = heat_list[i])

        ds = ytf.load('%s/DD%04d/DD%04d' % (sim_loc, output, output))

        ad = ds.all_data()
        ph = yt.PhasePlot(ad, ('gas', 'temperature'), ('gas', 'cr_eta'), ('gas', 'cell_mass'),\
                          weight_field = None, fractional = True)

        ph.set_ylim(cr / 1e3, cr * 1e3)
        prof = ph.profile

        xbins = prof.x
        ybins = prof.y
        data = prof[('gas', 'cell_mass')].T

        vmin = 1e-5
        vmax = 1e-2
        cmap = cmap_list[0]
        cmap = palettable.cubehelix.jim_special_16_r.mpl_colormap

        row = int(i / ncols)
        col = i - row * ncols
        print(i, row, col)
        ax[row][col].set_xscale('log')
        ax[row][col].set_yscale('log')
        #        ax[row][col].set_xlim(1.5e-28, 8e-26)
        ax[row][col].set_xlim(4e4, 1e7)

        pcm = ax[row][col].pcolormesh(xbins, ybins, data, norm = LogNorm(), cmap = cmap, \
                               vmax = vmax, vmin = vmin)

        ax[row][col].set_title(title_list[i], fontsize=16)
        #        ax[row][col].set_ylabel('Density (g cm$^{-3}$)')
        ax[row][col].set_ylabel('CR Pressure / Gas Pressure')
        ax[row][col].set_xlabel('Temperature (K)')

    figname = '../../plots/phase_temperature_cr_eta_tctf_%.1f_%.1f.png' % (
        tctf, output)
    #    if diff > 0:
    #        figname = '../../plots/phase_temperature_cr_eta_mass_tctf_%.1f_cr_diff_%.1f_%.1f.png'%(tctf, diff, output)
    fig.tight_layout()
    print(figname)
    plt.savefig(figname, dpi=300)
Esempio n. 15
0
def plot_timestep(ds):
    for z in z_fields:
        for xy in xy_fields:
            ad = ds.all_data()
            center = [0.5, 0.5, 0.5]
            inner_sp = ds.sphere(center, (50, 'Mpc'))
            outer_sp = ds.sphere(center, (300, 'Mpc'))

            outer_shell = outer_sp - inner_sp
            outer_shell_domain = ad.cut_region([outer_shell])

            outflow_domain = ad.cut_region([outflow])
            inflow_domain = ad.cut_region([inflow])
            cgm_domain = ad.cut_region([CGM])
            regions = {
                'outflow_domain': outflow_domain,
                'inflow_domain': inflow_domain,
                'cgm_domain': cgm_domain
            }
            #regions = {'inflow_domain': inflow_domain}

            for region in regions.keys():
                if (xy[0] == 'radius'):
                    pp = yt.PhasePlot(regions.get(region),
                                      xy[0],
                                      xy[1],
                                      'entropy',
                                      weight_field=None)
                else:
                    pp = yt.PhasePlot(regions.get(region),
                                      xy[0],
                                      xy[1],
                                      z,
                                      weight_field=None)

                x_and_y_fields = xy[0] + '_vs_' + xy[1]
                path = "%s/%s/%s" % (region, z, x_and_y_fields)
                #pp.set_zlim(z, 1e-1, 1e5)
                pp.annotate_title(region)
                pp.set_cmap(z, "kamae")
                pp.save(path + "_%s" % ds)
Esempio n. 16
0
 def test_set_linear_scaling_for_none_extrema(self):
     # See Issue #3431
     # Ensures that extrema are calculated in the same way on subsequent passes
     # through the PhasePlot machinery.
     ds = fake_sph_orientation_ds()
     p = yt.PhasePlot(
         ds,
         ("all", "particle_position_spherical_theta"),
         ("all", "particle_position_spherical_radius"),
         ("all", "particle_mass"),
         weight_field=None,
     )
     p.set_log(("all", "particle_position_spherical_theta"), False)
     p.save()
Esempio n. 17
0
def make_phase(ds, data_source):
    """
    """
    ph = yt.PhasePlot(data_source, 'density', 'temperature', ['mass'], weight_field=None)
    ph.set_log('density', True)
    ph.set_unit('density', 'g/cm**3')
    ph.set_log('temperature', True)
    ph.set_unit('temperature', 'K')
    ph.set_xlim(1e-30,1e-20)
    ph.set_ylim(1e1,1e7)
    ph.set_cmap('mass', 'dusk')
    ph.set_unit('mass', 'Msun')
    ph.set_zlim('mass', 5e4,5e8)
    ph.save('images/')
Esempio n. 18
0
def get_ion_plots(ds, halo_center, ray):

    line_list = ['H', 'O'] # 'C', 'N', 'Si', 'O'] 

    for axis in ['z','y','x']:

        p = yt.ProjectionPlot(ds, axis, 'density', center=halo_center, width=(500,'kpc'))
        p.annotate_ray(ray, arrow=True)
        p.annotate_grids()
        p.save()

        p = yt.SlicePlot(ds, axis, 'metallicity', center=halo_center, width=(500,'kpc'))
        p.annotate_ray(ray, arrow=True)
        p.annotate_grids()
        p.save()

        proj = yt.SlicePlot(ds, axis, "O_p5_number_density", center=halo_center, width=(500,'kpc'))
        p.annotate_grids()
        proj.save('OVI_Slice')

        # O VI map?
        p = yt.ProjectionPlot(ds, axis, 'O_p5_number_density', center=halo_center, width=(500,'kpc'))
        p.annotate_grids()
        p.save('OVI_Column')


        proj = yt.SlicePlot(ds, axis, "H_p0_number_density", center=halo_center, width=(500,'kpc'))
        proj.save('HI')
        p = yt.ProjectionPlot(ds, axis, 'H_p0_number_density', center=halo_center, width=(500,'kpc'))
        p.annotate_grids()
        p.save('HI_Column')

        proj = yt.SlicePlot(ds, axis, "Si_p2_number_density", center=halo_center, width=(500,'kpc'))
        p.annotate_grids()
        proj.save('SiIII_Column')

        sph = ds.sphere(center=halo_center, radius=(500,'kpc'))

        phase = yt.PhasePlot(sph, "density", "temperature", ["O_p5_mass"], weight_field="O_p5_mass", fractional=True)
        phase.save()
Esempio n. 19
0
def test_phaseplot_set_log():
    ds = yt.load(ETC46)
    sp = ds.sphere("max", (1.0, "Mpc"))
    p1 = yt.ProfilePlot(sp, "radius", ("enzo", "Density"))
    p2 = yt.PhasePlot(sp, ("enzo", "Density"), ("enzo", "Temperature"),
                      "cell_mass")
    # make sure we can set the log-scaling using the tuple without erroring out
    p1.set_log(("enzo", "Density"), False)
    p2.set_log(("enzo", "Temperature"), False)
    assert p1.y_log["enzo", "Density"] is False
    assert p2.y_log is False

    # make sure we can set the log-scaling using a string without erroring out
    p1.set_log("Density", True)
    p2.set_log("Temperature", True)
    assert p1.y_log["enzo", "Density"] is True
    assert p2.y_log is True

    # make sure we can set the log-scaling using a field object
    p1.set_log(ds.fields.enzo.Density, False)
    p2.set_log(ds.fields.enzo.Temperature, False)
    assert p1.y_log["enzo", "Density"] is False
    assert p2.y_log is False
Esempio n. 20
0
def mach_number(
    path,
    idx_start=1,
    idx_end=100,
    didx=1,
):
    ts = yt.load([
        path + '/Data_%06d' % idx
        for idx in range(idx_start, idx_end + 1, didx)
    ])
    ds = yt.load(path + '/Data_000001')

    cg = ds.covering_grid(0, left_edge=[0.0, 0.0, 0.0], dims=[256, 256, 256])
    cg.get_data(["density", "mach_number", "cell_mass"])
    density_data = cg["density"]
    mach_number_data = cg["mach_number"]
    cell_mass_data = cg["cell_mass"]

    dens_min = density_data.min()
    dens_max = density_data.max()
    mach_min = mach_number_data.min()
    mach_max = mach_number_data.max()
    cell_min = cell_mass_data.min()
    cell_max = cell_mass_data.max()

    for ds in ts.piter():

        ad = ds.all_data()
        plot = yt.PhasePlot(ad,
                            "density",
                            "mach_number", ["cell_mass"],
                            weight_field=None)

        plot.set_xlim(dens_min, dens_max)
        plot.set_ylim(mach_min, mach_max)
        plot.set_zlim("cell_mass", cell_min, cell_max)
        plot.save(name=path + '/images/' + str(ds))
Esempio n. 21
0
import yt

# Load the dataset.
ds = yt.load("GalaxyClusterMerger/fiducial_1to3_b0.273d_hdf5_plt_cnt_0175")

# Create a data object that represents the whole box.
ad = ds.all_data()

# This is identical to the simple phase plot, except we supply
# the fractional=True keyword to divide the profile data by the sum.
plot = yt.PhasePlot(ad,
                    "density",
                    "temperature",
                    "mass",
                    weight_field=None,
                    fractional=True)

# Save the image.
# Optionally, give a string as an argument
# to name files with a keyword.
plot.save()
Esempio n. 22
0
def make_plots(ds, c, boxside):
    box = ds.box(c - boxside, c + boxside)
    c = ds.arr(c, 'code_length')
    basename = ds.basename + "_nref" + str(
        ds.get_parameter('MaximumRefinementLevel'))
    width = (197. / ds.hubble_constant) / (1 + ds.current_redshift)
    print "width = ", width, "kpc"

    # for axis in ("x", "y", "z"):
    if False:
        for axis in ("y"):
            dpy = yt.ProjectionPlot(ds,
                                    axis, ('gas', 'density'),
                                    center=c,
                                    width=(width, "kpc"),
                                    data_source=box)
            cmap = sns.blend_palette(
                ("black", "#984ea3", "#d73027", "darkorange", "#ffe34d",
                 "#4daf4a", "white"),
                n_colors=60,
                as_cmap=True)
            dpy.set_zlim(("gas", "density"), 5e-2, 1e4)
            dpy.set_cmap(("gas", "density"), cmap)
            dpy.annotate_scale(size_bar_args={'color': 'white'})
            dpy.hide_axes()
            dpy.set_unit(('gas', 'density'), 'Msun/pc**2')
            plotname = dpy.save()
            newname = plotname[0].replace(ds.basename, basename)
            os.rename(plotname[0], newname)

            if True:
                dty = yt.ProjectionPlot(ds,
                                        axis, ('gas', 'temperature'),
                                        weight_field=("gas", "density"),
                                        center=c,
                                        width=(width, "kpc"),
                                        data_source=box)
                dty.set_zlim(("gas", "temperature"), 1e3, 6e5)
                cmap = sns.blend_palette(
                    ("black", "#d73027", "darkorange", "#ffe34d"),
                    n_colors=50,
                    as_cmap=True)
                dty.set_cmap(("gas", "temperature"), cmap)
                plotname = dty.save()
                newname = plotname[0].replace(ds.basename, basename)
                os.rename(plotname[0], newname)

                dpz = yt.ProjectionPlot(ds,
                                        axis, ('gas', 'metallicity'),
                                        weight_field=("gas", "density"),
                                        center=c,
                                        width=(width, "kpc"),
                                        data_source=box)
                dpz.set_zlim(("gas", "metallicity"), 0.005, 1.5)
                cmap = sns.blend_palette(("black", "#984ea3", "#4575b4",
                                          "#4daf4a", "#ffe34d", "darkorange"),
                                         as_cmap=True)
                dpz.set_cmap(("gas", "metallicity"), cmap)
                plotname = dpz.save()
                newname = plotname[0].replace(ds.basename, basename)
                os.rename(plotname[0], newname)

    trident.add_ion_fields(ds, ions=['O VI'])
    trident.add_ion_fields(ds, ions=['C II'])
    for axis in "y":
        ### HI
        dph = yt.ProjectionPlot(ds,
                                axis, ('gas', 'H_p0_number_density'),
                                center=c,
                                width=(width, "kpc"),
                                data_source=box)
        dph.set_zlim(("gas", "H_p0_number_density"), 1e13, 1e23)
        cmap = sns.blend_palette(
            ("white", "#ababab", "#565656", "black", "#4575b4", "#984ea3",
             "#d73027", "darkorange", "#ffe34d"),
            as_cmap=True)
        dph.set_cmap(("gas", "H_p0_number_density"), cmap)
        dph.annotate_scale(size_bar_args={'color': 'black'})
        # dph.annotate_marker((25, 25), coord_system='plot')
        dph.hide_axes()
        # dph.hide_colorbar()
        p = dph.plots['H_p0_number_density']
        colorbar = p.cb(orientation='horizontal')
        dph._setup_plots()
        colorbar.set_ticks([1e13, 1e15, 1e17, 1e19, 1e21, 1e23])
        colorbar.set_ticklabels(['13', '15', '17', '19', '21', '23'])
        colorbar.ax.tick_params(labelsize=20)
        plotname = dph.save()
        newname = plotname[0].replace(ds.basename, basename)
        os.rename(plotname[0], newname)

        ### CII
        dpo = yt.ProjectionPlot(ds,
                                axis, ('gas', 'C_p1_number_density'),
                                center=c,
                                width=(width, "kpc"),
                                data_source=box)
        dpo.set_zlim(("gas", "C_p1_number_density"), 1e5, 1e20)
        cmap = sns.blend_palette(
            ("white", "#ababab", "#565656", "black", "#4575b4", "#984ea3",
             "#d73027", "darkorange", "#ffe34d"),
            as_cmap=True)
        dpo.set_cmap(("gas", "C_p1_number_density"), cmap)
        dpo.hide_axes()
        plotname = dpo.save()
        newname = plotname[0].replace(ds.basename, basename)
        os.rename(plotname[0], newname)

        ### OVI
        dpo = yt.ProjectionPlot(ds,
                                axis, ('gas', 'O_p5_number_density'),
                                center=c,
                                width=(width, "kpc"),
                                data_source=box)
        dpo.set_zlim(("gas", "O_p5_number_density"), 1e12, 1e15)
        cmap = sns.blend_palette(("white", "black", "#4daf4a", "#4575b4",
                                  "#984ea3", "#d73027", "darkorange"),
                                 as_cmap=True)
        dpo.set_cmap(("gas", "O_p5_number_density"), cmap)
        dpo.hide_axes()
        plotname = dpo.save()
        newname = plotname[0].replace(ds.basename, basename)
        os.rename(plotname[0], newname)

    if False:
        dTm = yt.PhasePlot(box, ('gas', 'density'), ('gas', 'temperature'),
                           ['cell_mass'],
                           weight_field=None,
                           x_bins=512,
                           y_bins=512)
        dTm.set_cmap("cell_mass", "plasma")
        dTm.set_xlim(5e-31, 1e-20)
        dTm.set_ylim(100, 3e8)
        dTm.set_zlim("cell_mass", 1e32, 5e40)
        plotname = dTm.save()
        newname = plotname[0].replace(ds.basename, basename)
        os.rename(plotname[0], newname)
# =============================================================================
# def velMagnitude(field, data):
#     return np.hypot(data['velx'], data['vely'])
# ds.add_field((ds, "velMagnitude"), units="cm/s", function=velMagnitude)
#

# =============================================================================

##################
# Make phase plots
##################

ad = ds.all_data()
# Use tuples to find individual files; otherwise it will pick a default
plot = yt.PhasePlot(ad, ('gas', "density"),
                    "temperature", ['velocity_magnitude'],
                    fractional=False,
                    accumulation=False)
plot.set_unit('velocity_magnitude', 'cm/s')  #vely units weird
plot.annotate_title(
    "Velocity magnitude probability distribution, yes accumulation")
plot.save("YT_Test_Plots/HDF5/TestC")

selection = ds.CutRegion([0 < ('index', 'x') and ('index', 'x') < 2.3 * kpc])
plot = yt.SlicePlot(selection, 'z', 'density')
plot.save("YT_Test_Plots/HDF5/VectorSelection")

# Streamlines.streamline(ds, dict['velx'], dict['vely'])
# Streamlines.streamlines.integrate_through_volume()

# print("Saving figures...")
# plt.savefig('Plots/VelocityPlot_m2_c1_0076_stream1.png', dpi=1000);
Esempio n. 24
0
ds = ytf.load_romulusC(output, ions=ion_list)

cen = rom_help.get_romulus_yt_center('romulusC', output, ds)
sp = ds.sphere(cen, (3300, 'kpc'))
#icm = sp.cut_region(["obj[('gas', 'metallicity')] > 0"])
icm = sp.cut_region([
    "(obj[('gas', 'metal_cooling_time')]>0) & (obj[('gas', 'metal_primordial_cooling_time_ratio')] > 0) & (obj[('gas', 'temperature')] >= 1e4)  & (obj[('gas', 'temperature')] <= 1e6) & (obj[('gas', 'particle_H_nuclei_density')] > 1e-6) & (obj[('gas', 'particle_H_nuclei_density')] < 1e-2)"
])
#icm_mask = sp[('gas', 'particle_H_nuclei_density')] > 0.1
#icm = sp.cut_region(["obj[('gas', 'particle_H_nuclei_density')] < 0.1"])

xfield = ('gas', 'spherical_position_radius')
zfield = ('Gas', 'Mass')
yfield = ('gas', 'metal_primordial_cooling_time_ratio')
#icm =
p = yt.PhasePlot(icm, xfield, yfield, zfield, weight_field=None)
p.set_unit(xfield, 'kpc')
p.set_unit(zfield, 'Msun')
p.set_log(xfield, False)
p.set_log(yfield, True)
p.set_ylim(1e-2, 1e2)
p.save('%s_cgm' % (yfield[1]))

yfield = ('gas', 'primordial_cooling_time')

p = yt.PhasePlot(icm, xfield, yfield, zfield, weight_field=None)
p.set_unit(xfield, 'kpc')
p.set_unit(yfield, 'yr')
p.set_unit(zfield, 'Msun')
p.set_log(xfield, False)
p.set_log(yfield, True)
Esempio n. 25
0
                                    's': 20
                                })
    prj.save(suffix='pdf', mpl_kwargs={"bbox_inches": "tight"})

ad = ds.all_data()
#units = dict(cell_mass='Msun')
#profile = yt.create_profile(ad, ['overdensity','temperature'],\
#                            n_bins=[128, 128], fields=['cell_mass'],\
#                            weight_field=None, units=units)
#plot = yt.PhasePlot.from_profile(profile)
#plot.set_zlim('cell_mass',10**5, 10**11)
#plot.annotate_title('%s z = %0.2f'%(title,ds.current_redshift))
#plot.save('r-t-profile%0.2f'%ds.current_redshift,suffix='pdf',mpl_kwargs={"bbox_inches":"tight"})

units = dict(cell_mass='Msun')

#profile = yt.create_profile(ad, ['H_p0_fraction','overdensity'],\
#                            n_bins=[256, 256], fields=['cell_mass'],\
#                            weight_field=None, units=units)
#plot = yt.PhasePlot.from_profile(profile)
plot = yt.PhasePlot(ad,
                    'overdensity',
                    'H_fraction', ['cell_mass'],
                    weight_field=None)
plot.set_unit('cell_mass', 'Msun')
plot.set_zlim('cell_mass', 10**3, 10**12)
plot.annotate_title(title + ' z = %0.2f' % ds.current_redshift)
plot.save('h-r-profile%0.2f' % ds.current_redshift,
          suffix='pdf',
          mpl_kwargs={"bbox_inches": "tight"})
Esempio n. 26
0
        fn_head = fn.split('/')[-1]
        ds = GizmoDataset(fn)
        c = find_center_iteratively(fn, ds=ds)
        trident.add_ion_fields(ds, 'H')
        #c = read_amiga_center(amiga_data, fn, ds)
        #_, c = ds.find_max('density')
        rvir = ds.quan(50, 'kpc')
        sp = ds.sphere(c, rvir)
        bulk_vel = sp.quantities.bulk_velocity()
        #print("Bulk Velocity of Halo = %s" % bulk_vel.to('km/s'))
        sp.set_field_parameter("bulk_velocity", bulk_vel)
        ad = ds.all_data()
        ad.set_field_parameter('center', c)
        ad.set_field_parameter('normal', np.array([1, 0, 0]))
        ad.set_field_parameter('bulk_velocity', bulk_vel)
        p = yt.PhasePlot(ad, ('gas', 'radius'), ('gas', 'radial_velocity'),
                         ('gas', 'H_p0_mass'),
                         weight_field=('gas', 'ones'))
        p.set_unit(('gas', 'radius'), 'kpc')
        p.set_unit(('gas', 'radial_velocity'), 'km/s')
        p.set_unit(('gas', 'H_p0_mass'), 'Msun')
        #p.set_log(('gas', 'radius'), False)
        #p.set_log(('gas', 'radial_velocity'), False)
        p.set_xlim(1e1, 1e4)
        p.set_ylim(-1000, 1000)
        p.set_cmap(('gas', 'H_p0_mass'), 'thermal')
        #p.set_zlim(('gas', 'H_p0_mass'), 1e12, 1e25)
        p.set_xlabel('Radius (kpc)')
        p.set_ylabel('Radial Velocity (km/s)')
        p.save()
Esempio n. 27
0
    cbar_location="right",
    cbar_mode="single",
    cbar_size="3%",
    cbar_pad="0%",
    aspect=False,
)

for i, SnapNum in enumerate([10, 40]):
    # Load the data and create a single plot
    ds = yt.load("enzo_tiny_cosmology/DD00%2d/DD00%2d" % (SnapNum, SnapNum))
    ad = ds.all_data()
    p = yt.PhasePlot(
        ad,
        "density",
        "temperature",
        [
            "cell_mass",
        ],
        weight_field=None,
    )

    # Ensure the axes and colorbar limits match for all plots
    p.set_xlim(1.0e-32, 8.0e-26)
    p.set_ylim(1.0e1, 2.0e7)
    p.set_zlim(("gas", "cell_mass"), 1e42, 1e46)

    # This forces the ProjectionPlot to redraw itself on the AxesGrid axes.
    plot = p.plots[("gas", "cell_mass")]
    plot.figure = fig
    plot.axes = grid[i].axes
    if i == 0:
Esempio n. 28
0
        plot.cax = grid.cbar_axes[cnt]
        prj._setup_plots()
        cnt += 1
        del (prj)
plt.rcParams.update({"font.size": 8})
plt.savefig('%s-%s_compare.pdf'%(simtitle[0], simtitle[1]),\
      dpi=200, bbox_inches="tight", pad_inches=0.0)

## phase plots done similarly

for i, dset in enumerate(sets):
    ds = yt.load(dset)
    ds.add_field(('gas', 'log_Density'), function=_logden, units=None)
    ds.add_field(('gas', 'log_T'), function=_logT, units=None)
    ad = ds.all_data()
    plot = yt.PhasePlot(ad, 'density','temperature',['cell_mass'],\
            weight_field=None)
    profile = yt.create_profile(ad, ['density','temperature'],\
            n_bins=[128,128], fields=['cell_mass'],\
            weight_field=None, units={'cell_mass':'Msun'})
    plot = yt.PhasePlot.from_profile(profile)
    plot.set_zlim('cell_mass', 1e5, 1e10)
    plot.set_ylim(2e3, 5e6)
    plot.set_xlim(3e-30, 1e-24)
    plot.set_unit('cell_mass', 'Msun')
    plot.set_cmap('cell_mass', "inferno")
    print(simtitle[i])
    plot.annotate_title('%s' % simtitle[i])
    plot.set_font_size(35)
    plot.title.set_font_size(55)
    if i != 0:
        plot.set_xlabel("")
Esempio n. 29
0
import yt

# Load the dataset.
ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")

# Create a sphere of radius 100 kpc in the center of the domain.
my_sphere = ds.sphere("c", (100.0, "kpc"))

# Create a PhasePlot object.
# Setting weight to None will calculate a sum.
# Setting weight to a field will calculate an average
# weighted by that field.
plot = yt.PhasePlot(my_sphere,
                    "density",
                    "temperature",
                    "cell_mass",
                    weight_field=None)

# Set the units of mass to be in solar masses (not the default in cgs)
plot.set_unit('cell_mass', 'Msun')

# Save the image.
# Optionally, give a string as an argument
# to name files with a keyword.
plot.save()
Esempio n. 30
0
import yt

# Load the dataset.
ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")

# Create a sphere of radius 100 kpc in the center of the domain.
my_sphere = ds.sphere("c", (100.0, "kpc"))

# Create a PhasePlot object.
# Setting weight to None will calculate a sum.
# Setting weight to a field will calculate an average
# weighted by that field.
plot = yt.PhasePlot(
    my_sphere,
    ("gas", "density"),
    ("gas", "temperature"),
    ("gas", "mass"),
    weight_field=None,
)

# Set the units of mass to be in solar masses (not the default in cgs)
plot.set_unit(("gas", "mass"), "Msun")

# Save the image.
# Optionally, give a string as an argument
# to name files with a keyword.
plot.save()