def test_particle_profiles(): for nproc in [1, 2, 4, 8]: ds = fake_random_ds(32, nprocs=nproc, particles = 32**3) dd = ds.all_data() p1d = Profile1D(dd, "particle_position_x", 128, 0.0, 1.0, False, weight_field = None) p1d.add_fields(["particle_ones"]) assert_equal(p1d["particle_ones"].sum(), 32**3) p1d = create_profile(dd, ["particle_position_x"], ["particle_ones"], weight_field=None, n_bins=128, extrema=extrema_s, logs=logs_s) assert_equal(p1d["particle_ones"].sum(), 32**3) p1d = create_profile(dd, [("all", "particle_position_x")], [("all", "particle_ones")], weight_field=None, n_bins=128, extrema=extrema_t, logs=logs_t) assert_equal(p1d["particle_ones"].sum(), 32**3) p2d = Profile2D(dd, "particle_position_x", 128, 0.0, 1.0, False, "particle_position_y", 128, 0.0, 1.0, False, weight_field = None) p2d.add_fields(["particle_ones"]) assert_equal(p2d["particle_ones"].sum(), 32**3) p3d = Profile3D(dd, "particle_position_x", 128, 0.0, 1.0, False, "particle_position_y", 128, 0.0, 1.0, False, "particle_position_z", 128, 0.0, 1.0, False, weight_field = None) p3d.add_fields(["particle_ones"]) assert_equal(p3d["particle_ones"].sum(), 32**3)
def test_particle_profiles(): for nproc in [1, 2, 4, 8]: ds = fake_random_ds(32, nprocs=nproc, particles = 32**3) dd = ds.all_data() p1d = Profile1D(dd, "particle_position_x", 128, 0.0, 1.0, False, weight_field = None) p1d.add_fields(["particle_ones"]) yield assert_equal, p1d["particle_ones"].sum(), 32**3 p1d = create_profile(dd, ["particle_position_x"], ["particle_ones"], weight_field=None, n_bins=128, extrema=extrema_s, logs=logs_s) yield assert_equal, p1d["particle_ones"].sum(), 32**3 p1d = create_profile(dd, [("all", "particle_position_x")], [("all", "particle_ones")], weight_field=None, n_bins=128, extrema=extrema_t, logs=logs_t) yield assert_equal, p1d["particle_ones"].sum(), 32**3 p2d = Profile2D(dd, "particle_position_x", 128, 0.0, 1.0, False, "particle_position_y", 128, 0.0, 1.0, False, weight_field = None) p2d.add_fields(["particle_ones"]) yield assert_equal, p2d["particle_ones"].sum(), 32**3 p3d = Profile3D(dd, "particle_position_x", 128, 0.0, 1.0, False, "particle_position_y", 128, 0.0, 1.0, False, "particle_position_z", 128, 0.0, 1.0, False, weight_field = None) p3d.add_fields(["particle_ones"]) yield assert_equal, p3d["particle_ones"].sum(), 32**3
def test_profile_plot(): fields = ('density', 'temperature', 'velocity_x', 'velocity_y', 'velocity_z') units = ('g/cm**3', 'K', 'cm/s', 'cm/s', 'cm/s') test_ds = fake_random_ds(16, fields=fields, units=units) regions = [test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3), test_ds.all_data()] pr_fields = [('density', 'temperature'), ('density', 'velocity_x'), ('temperature', 'cell_mass'), ('density', 'radius'), ('velocity_magnitude', 'cell_mass')] profiles = [] for reg in regions: for x_field, y_field in pr_fields: profiles.append(ProfilePlot(reg, x_field, y_field)) profiles.append(ProfilePlot(reg, x_field, y_field, fractional=True, accumulation=True)) p1d = create_profile(reg, x_field, y_field) profiles.append(ProfilePlot.from_profiles(p1d)) p1 = create_profile(test_ds.all_data(), 'density', 'temperature') p2 = create_profile(test_ds.all_data(), 'density', 'velocity_x') profiles.append(ProfilePlot.from_profiles( [p1, p2], labels=['temperature', 'velocity'])) profiles[0]._repr_html_() for idx, plot in enumerate(profiles): test_prefix = "%s_%s" % (plot.plots.keys(), idx) yield compare(test_ds, plot, test_prefix=test_prefix, test_name="profile_plots")
def test_domain_sphere(): # Now we test that we can get different radial velocities based on field # parameters. # Get the first sphere ds = fake_random_ds( 16, fields=("density", "velocity_x", "velocity_y", "velocity_z") ) sp0 = ds.sphere(ds.domain_center, 0.25) # Compute the bulk velocity from the cells in this sphere bulk_vel = sp0.quantities.bulk_velocity() # Get the second sphere sp1 = ds.sphere(ds.domain_center, 0.25) # Set the bulk velocity field parameter sp1.set_field_parameter("bulk_velocity", bulk_vel) assert_equal(np.any(sp0["radial_velocity"] == sp1["radial_velocity"]), False) # Radial profile without correction # Note we set n_bins = 8 here. rp0 = create_profile( sp0, "radius", "radial_velocity", units={"radius": "kpc"}, logs={"radius": False}, n_bins=8, ) # Radial profile with correction for bulk velocity rp1 = create_profile( sp1, "radius", "radial_velocity", units={"radius": "kpc"}, logs={"radius": False}, n_bins=8, ) assert_equal(rp0.x_bins, rp1.x_bins) assert_equal(rp0.used, rp1.used) assert_equal(rp0.used.sum() > rp0.used.size / 2.0, True) assert_equal( np.any(rp0["radial_velocity"][rp0.used] == rp1["radial_velocity"][rp1.used]), False, ) ref_sp = ds.sphere("c", 0.25) for f in _fields_to_compare: ref_sp[f].sort() for center in periodicity_cases(ds): sp = ds.sphere(center, 0.25) for f in _fields_to_compare: sp[f].sort() assert_equal(sp[f], ref_sp[f])
def test_profile_plot(self): fields = ('density', 'temperature', 'velocity_x', 'velocity_y', 'velocity_z') units = ('g/cm**3', 'K', 'cm/s', 'cm/s', 'cm/s') test_ds = fake_random_ds(16, fields=fields, units=units) regions = [ test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3), test_ds.all_data() ] pr_fields = [('density', 'temperature'), ('density', 'velocity_x'), ('temperature', 'cell_mass'), ('density', 'radius'), ('velocity_magnitude', 'cell_mass')] profiles = [] for reg in regions: for x_field, y_field in pr_fields: profiles.append(ProfilePlot(reg, x_field, y_field)) profiles.append( ProfilePlot(reg, x_field, y_field, fractional=True, accumulation=True)) p1d = create_profile(reg, x_field, y_field) profiles.append(ProfilePlot.from_profiles(p1d)) p1 = create_profile(test_ds.all_data(), 'density', 'temperature') p2 = create_profile(test_ds.all_data(), 'density', 'velocity_x') profiles.append( ProfilePlot.from_profiles([p1, p2], labels=['temperature', 'velocity'])) profiles[0]._repr_html_() for p in profiles: for fname in TEST_FLNMS: assert_fname(p.save(fname)[0])
def setUpClass(cls): fields = ('density', 'temperature', 'velocity_x', 'velocity_y', 'velocity_z') units = ('g/cm**3', 'K', 'cm/s', 'cm/s', 'cm/s') test_ds = fake_random_ds(64, fields=fields, units=units) regions = [test_ds.region([0.5]*3, [0.4]*3, [0.6]*3), test_ds.all_data()] profiles = [] phases = [] pr_fields = [('density', 'temperature'), ('density', 'velocity_x'), ('temperature', 'cell_mass'), ('density', 'radius'), ('velocity_magnitude', 'cell_mass')] ph_fields = [('density', 'temperature', 'cell_mass'), ('density', 'velocity_x', 'cell_mass'), ('radius', 'temperature', 'velocity_magnitude')] for reg in regions: for x_field, y_field in pr_fields: profiles.append(ProfilePlot(reg, x_field, y_field)) profiles.append(ProfilePlot(reg, x_field, y_field, fractional=True, accumulation=True)) p1d = create_profile(reg, x_field, y_field) profiles.append(ProfilePlot.from_profiles(p1d)) for x_field, y_field, z_field in ph_fields: # set n_bins to [16, 16] since matplotlib's postscript # renderer is slow when it has to write a lot of polygons phases.append(PhasePlot(reg, x_field, y_field, z_field, x_bins=16, y_bins=16)) phases.append(PhasePlot(reg, x_field, y_field, z_field, fractional=True, accumulation=True, x_bins=16, y_bins=16)) p2d = create_profile(reg, [x_field, y_field], z_field, n_bins=[16, 16]) phases.append(PhasePlot.from_profile(p2d)) cls.profiles = profiles cls.phases = phases cls.ds = test_ds
def setUpClass(cls): fields = ('density', 'temperature', 'velocity_x', 'velocity_y', 'velocity_z') units = ('g/cm**3', 'K', 'cm/s', 'cm/s', 'cm/s') test_ds = fake_random_ds(64, fields=fields, units=units) regions = [ test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3), test_ds.all_data() ] profiles = [] phases = [] pr_fields = [('density', 'temperature'), ('density', 'velocity_x'), ('temperature', 'cell_mass'), ('density', 'radius'), ('velocity_magnitude', 'cell_mass')] ph_fields = [('density', 'temperature', 'cell_mass'), ('density', 'velocity_x', 'cell_mass'), ('radius', 'temperature', 'velocity_magnitude')] for reg in regions: for x_field, y_field in pr_fields: profiles.append(ProfilePlot(reg, x_field, y_field)) profiles.append( ProfilePlot(reg, x_field, y_field, fractional=True, accumulation=True)) p1d = create_profile(reg, x_field, y_field) profiles.append(ProfilePlot.from_profiles(p1d)) for x_field, y_field, z_field in ph_fields: # set n_bins to [16, 16] since matplotlib's postscript # renderer is slow when it has to write a lot of polygons phases.append( PhasePlot(reg, x_field, y_field, z_field, x_bins=16, y_bins=16)) phases.append( PhasePlot(reg, x_field, y_field, z_field, fractional=True, accumulation=True, x_bins=16, y_bins=16)) p2d = create_profile(reg, [x_field, y_field], z_field, n_bins=[16, 16]) phases.append(PhasePlot.from_profile(p2d)) cls.profiles = profiles cls.phases = phases cls.ds = test_ds
def setUpClass(cls): fields = ('density', 'temperature', 'velocity_x', 'velocity_y', 'velocity_z') units = ('g/cm**3', 'K', 'cm/s', 'cm/s', 'cm/s') test_ds = fake_random_ds(64, fields=fields, units=units) regions = [test_ds.region([0.5]*3, [0.4]*3, [0.6]*3), test_ds.all_data()] profiles = [] phases = [] pr_fields = [('density', 'temperature'), ('density', 'velocity_x'), ('temperature', 'cell_mass'), ('density', 'radius'), ('velocity_magnitude', 'cell_mass')] ph_fields = [('density', 'temperature', 'cell_mass'), ('density', 'velocity_x', 'cell_mass'), ('radius', 'temperature', 'velocity_magnitude')] for reg in regions: for x_field, y_field in pr_fields: profiles.append(ProfilePlot(reg, x_field, y_field)) profiles.append(ProfilePlot(reg, x_field, y_field, fractional=True, accumulation=True)) p1d = create_profile(reg, x_field, y_field) profiles.append(ProfilePlot.from_profiles(p1d)) for x_field, y_field, z_field in ph_fields: # set n_bins to [16, 16] since matplotlib's postscript # renderer is slow when it has to write a lot of polygons phases.append(PhasePlot(reg, x_field, y_field, z_field, x_bins=16, y_bins=16)) phases.append(PhasePlot(reg, x_field, y_field, z_field, fractional=True, accumulation=True, x_bins=16, y_bins=16)) p2d = create_profile(reg, [x_field, y_field], z_field, n_bins=[16, 16]) phases.append(PhasePlot.from_profile(p2d)) pp = PhasePlot(test_ds.all_data(), 'density', 'temperature', 'cell_mass') pp.set_xlim(0.3, 0.8) pp.set_ylim(0.4, 0.6) pp._setup_plots() xlim = pp.plots['cell_mass'].axes.get_xlim() ylim = pp.plots['cell_mass'].axes.get_ylim() assert_array_almost_equal(xlim, (0.3, 0.8)) assert_array_almost_equal(ylim, (0.4, 0.6)) phases.append(pp) p1 = create_profile(test_ds.all_data(), 'density', 'temperature') p2 = create_profile(test_ds.all_data(), 'density', 'velocity_x') profiles.append(ProfilePlot.from_profiles( [p1, p2], labels=['temperature', 'velocity'])) cls.profiles = profiles cls.phases = phases cls.ds = test_ds
def test_particle_phase_plot(self): test_ds = fake_particle_ds() data_sources = [test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3), test_ds.all_data()] particle_phases = [] for source in data_sources: for x_field, y_field, z_fields in PHASE_FIELDS: particle_phases.append(ParticlePhasePlot(source, x_field, y_field, z_fields, x_bins=16, y_bins=16)) particle_phases.append(ParticlePhasePlot(source, x_field, y_field, z_fields, x_bins=16, y_bins=16, deposition='cic')) pp = create_profile(source, [x_field, y_field], z_fields, weight_field='particle_ones', n_bins=[16, 16]) particle_phases.append(ParticlePhasePlot.from_profile(pp)) particle_phases[0]._repr_html_() for p in particle_phases: for fname in TEST_FLNMS: assert assert_fname(p.save(fname)[0])
def setUpClass(cls): test_ds = fake_particle_ds() data_sources = [test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3), test_ds.all_data()] particle_phases = [] for source in data_sources: for x_field, y_field, z_fields in PHASE_FIELDS: particle_phases.append(ParticlePhasePlot(source, x_field, y_field, z_fields, x_bins=16, y_bins=16)) particle_phases.append(ParticlePhasePlot(source, x_field, y_field, z_fields, x_bins=16, y_bins=16, deposition='cic')) pp = create_profile(source, [x_field, y_field], z_fields, weight_field='particle_ones', n_bins=[16, 16]) particle_phases.append(ParticlePhasePlot.from_profile(pp)) cls.particle_phases = particle_phases cls.ds = test_ds
def __init__(self, data_source, x_field, y_field, z_fields=None, color='b', x_bins=800, y_bins=800, weight_field=None, deposition='ngp', fontsize=18, figure_size=8.0): # if no z_fields are passed in, use a constant color if z_fields is None: self.use_cbar = False self.splat_color = color z_fields = ['particle_ones'] profile = create_profile(data_source, [x_field, y_field], ensure_list(z_fields), n_bins=[x_bins, y_bins], weight_field=weight_field, deposition=deposition) type(self)._initialize_instance(self, data_source, profile, fontsize, figure_size)
def __init__(self, data_source, x_field, y_fields, weight_field="cell_mass", n_bins=64, accumulation=False, fractional=False, label=None, plot_spec=None, x_log=None, y_log=None): if x_log is None: logs = None else: logs = {x_field:x_log} profiles = [create_profile(data_source, [x_field], n_bins=[n_bins], fields=ensure_list(y_fields), weight_field=weight_field, accumulation=accumulation, fractional=fractional, logs=logs)] if plot_spec is None: plot_spec = [dict() for p in profiles] if not isinstance(plot_spec, list): plot_spec = [plot_spec.copy() for p in profiles] ProfilePlot._initialize_instance(self, profiles, label, plot_spec, y_log)
def __init__(self, data_source, x_field, y_fields, weight_field="cell_mass", n_bins=64, accumulation=False, fractional=False, label=None, plot_spec=None, x_log=None, y_log=None): if x_log is None: logs = None else: logs = {x_field:x_log} if isinstance(data_source.ds, YTProfileDataset): profiles = [data_source.ds.profile] else: profiles = [create_profile(data_source, [x_field], n_bins=[n_bins], fields=ensure_list(y_fields), weight_field=weight_field, accumulation=accumulation, fractional=fractional, logs=logs)] if plot_spec is None: plot_spec = [dict() for p in profiles] if not isinstance(plot_spec, list): plot_spec = [plot_spec.copy() for p in profiles] ProfilePlot._initialize_instance(self, profiles, label, plot_spec, y_log)
def __init__( self, data_source, x_field, y_field, z_fields=None, color="b", x_bins=800, y_bins=800, weight_field=None, deposition="ngp", fontsize=18, figure_size=8.0, shading="nearest", ): # if no z_fields are passed in, use a constant color if z_fields is None: self.use_cbar = False self.splat_color = color z_fields = [("all", "particle_ones")] profile = create_profile( data_source, [x_field, y_field], list(iter_fields(z_fields)), n_bins=[x_bins, y_bins], weight_field=weight_field, deposition=deposition, ) type(self)._initialize_instance( self, data_source, profile, fontsize, figure_size, shading )
def test_field_access(): ds = fake_random_ds(16) ad = ds.all_data() sp = ds.sphere(ds.domain_center, 0.25) cg = ds.covering_grid(0, ds.domain_left_edge, ds.domain_dimensions) scg = ds.smoothed_covering_grid(0, ds.domain_left_edge, ds.domain_dimensions) sl = ds.slice(0, ds.domain_center[0]) proj = ds.proj(("gas", "density"), 0) prof = create_profile(ad, ("index", "radius"), ("gas", "density")) for data_object in [ad, sp, cg, scg, sl, proj, prof]: assert_equal(data_object["gas", "density"], data_object[ds.fields.gas.density]) for field in [("gas", "density"), ds.fields.gas.density]: ad = ds.all_data() prof = ProfilePlot(ad, ("index", "radius"), field) phase = PhasePlot(ad, ("index", "radius"), field, ("gas", "cell_mass")) s = SlicePlot(ds, 2, field) oas = SlicePlot(ds, [1, 1, 1], field) p = ProjectionPlot(ds, 2, field) oap = OffAxisProjectionPlot(ds, [1, 1, 1], field) for plot_object in [s, oas, p, oap, prof, phase]: plot_object._setup_plots() if hasattr(plot_object, "_frb"): plot_object._frb[field]
def __init__(self, data_source, x_field, y_field, z_fields, weight_field="cell_mass", x_bins=128, y_bins=128, accumulation=False, fractional=False, fontsize=18, figure_size=8.0): if isinstance(data_source.ds, YTProfileDataset): profile = data_source.ds.profile else: profile = create_profile(data_source, [x_field, y_field], ensure_list(z_fields), n_bins=[x_bins, y_bins], weight_field=weight_field, accumulation=accumulation, fractional=fractional) type(self)._initialize_instance(self, data_source, profile, fontsize, figure_size)
def _recreate_profile(self): p = self._profile units = {p.x_field: str(p.x.units), p.y_field: str(p.y.units)} zunits = dict( (field, str(p.field_units[field])) for field in p.field_units) extrema = {p.x_field: self._xlim, p.y_field: self._ylim} if self.x_log is not None or self.y_log is not None: logs = {} else: logs = None if self.x_log is not None: logs[p.x_field] = self.x_log if self.y_log is not None: logs[p.y_field] = self.y_log deposition = getattr(p, "deposition", None) additional_kwargs = { 'accumulation': p.accumulation, 'fractional': p.fractional, 'deposition': deposition } self._profile = create_profile( p.data_source, [p.x_field, p.y_field], list(p.field_map.values()), n_bins=[len(p.x_bins) - 1, len(p.y_bins) - 1], weight_field=p.weight_field, units=units, extrema=extrema, logs=logs, **additional_kwargs) for field in zunits: self._profile.set_field_unit(field, zunits[field]) self._profile_valid = True
def test_phase_plot(): fields = ("density", "temperature", "velocity_x", "velocity_y", "velocity_z") units = ("g/cm**3", "K", "cm/s", "cm/s", "cm/s") test_ds = fake_random_ds(16, fields=fields, units=units) regions = [ test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3), test_ds.all_data() ] phases = [] ph_fields = [ [("gas", "density"), ("gas", "temperature"), ("gas", "mass")], [("gas", "density"), ("gas", "velocity_x"), ("gas", "mass")], [("index", "radius"), ("gas", "temperature"), ("gas", "velocity_magnitude")], ] for reg in regions: for x_field, y_field, z_field in ph_fields: # set n_bins to [16, 16] since matplotlib's postscript # renderer is slow when it has to write a lot of polygons phases.append( PhasePlot(reg, x_field, y_field, z_field, x_bins=16, y_bins=16)) phases.append( PhasePlot( reg, x_field, y_field, z_field, fractional=True, accumulation=True, x_bins=16, y_bins=16, )) p2d = create_profile(reg, [x_field, y_field], z_field, n_bins=[16, 16]) phases.append(PhasePlot.from_profile(p2d)) pp = PhasePlot( test_ds.all_data(), ("gas", "density"), ("gas", "temperature"), ("gas", "mass"), ) pp.set_xlim(0.3, 0.8) pp.set_ylim(0.4, 0.6) pp._setup_plots() xlim = pp.plots[("gas", "mass")].axes.get_xlim() ylim = pp.plots[("gas", "mass")].axes.get_ylim() assert_array_almost_equal(xlim, (0.3, 0.8)) assert_array_almost_equal(ylim, (0.4, 0.6)) phases.append(pp) phases[0]._repr_html_() for idx, plot in enumerate(phases): test_prefix = f"{plot.plots.keys()}_{idx}" yield compare(test_ds, plot, test_prefix=test_prefix, test_name="phase_plots")
def test_profile_plot(): fields = ("density", "temperature", "velocity_x", "velocity_y", "velocity_z") units = ("g/cm**3", "K", "cm/s", "cm/s", "cm/s") test_ds = fake_random_ds(16, fields=fields, units=units) regions = [ test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3), test_ds.all_data() ] pr_fields = [ [("gas", "density"), ("gas", "temperature")], [("gas", "density"), ("gas", "velocity_x")], [("gas", "temperature"), ("gas", "mass")], [("gas", "density"), ("index", "radius")], [("gas", "velocity_magnitude"), ("gas", "mass")], ] profiles = [] for reg in regions: for x_field, y_field in pr_fields: profiles.append(ProfilePlot(reg, x_field, y_field)) profiles.append( ProfilePlot(reg, x_field, y_field, fractional=True, accumulation=True)) p1d = create_profile(reg, x_field, y_field) profiles.append(ProfilePlot.from_profiles(p1d)) p1 = create_profile(test_ds.all_data(), ("gas", "density"), ("gas", "temperature")) p2 = create_profile(test_ds.all_data(), ("gas", "density"), ("gas", "velocity_x")) profiles.append( ProfilePlot.from_profiles([p1, p2], labels=["temperature", "velocity"])) profiles[0]._repr_html_() for idx, plot in enumerate(profiles): test_prefix = f"{plot.plots.keys()}_{idx}" yield compare(test_ds, plot, test_prefix=test_prefix, test_name="profile_plots")
def set_xlim(self, xmin=None, xmax=None): """Sets the limits of the bin field Parameters ---------- xmin : float or None The new x minimum. Defaults to None, which leaves the xmin unchanged. xmax : float or None The new x maximum. Defaults to None, which leaves the xmax unchanged. Examples -------- >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> pp = yt.ProfilePlot(ds.all_data(), 'density', 'temperature') >>> pp.set_xlim(1e-29, 1e-24) >>> pp.save() """ self.axes.xlim = (xmin, xmax) for i, p in enumerate(self.profiles): if xmin is None: xmi = p.x_bins.min() else: xmi = xmin if xmax is None: xma = p.x_bins.max() else: xma = xmax extrema = { p.x_field: ((xmi, str(p.x.units)), (xma, str(p.x.units))) } units = {p.x_field: str(p.x.units)} if self.x_log is None: logs = None else: logs = {p.x_field: self.x_log} for field in p.field_map.values(): units[field] = str(p.field_data[field].units) self.profiles[i] = \ create_profile(p.data_source, p.x_field, n_bins=len(p.x_bins)-1, fields=list(p.field_map.values()), weight_field=p.weight_field, accumulation=p.accumulation, fractional=p.fractional, logs=logs, extrema=extrema, units=units) return self
def setup_profile(self, profile_field=None, profile_weight=None): if profile_field is None: profile_field = 'cell_volume' prof = create_profile(self.ds.all_data(), self.field, profile_field, n_bins=128, extrema={self.field: self.bounds}, weight_field=profile_weight, logs={self.field: self.log}) self.profiles[self.field] = prof return
def test_update_data_grid(): ds = fake_random_ds(64, nprocs=8) ds.index dims = (32, 32, 32) grid_data = [{ "temperature": np.random.uniform(size=dims) } for i in range(ds.index.num_grids)] ds.index.update_data(grid_data) prj = ds.proj("temperature", 2) prj["temperature"] dd = ds.all_data() profile = create_profile(dd, "density", "temperature", 10) profile["temperature"]
def test_particle_phase_plot(self): test_ds = fake_particle_ds() data_sources = [ test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3), test_ds.all_data(), ] particle_phases = [] for source in data_sources: for x_field, y_field, z_fields in PHASE_FIELDS: particle_phases.append( ParticlePhasePlot( source, x_field, y_field, z_fields, x_bins=16, y_bins=16, )) particle_phases.append( ParticlePhasePlot( source, x_field, y_field, z_fields, x_bins=16, y_bins=16, deposition="cic", )) pp = create_profile( source, [x_field, y_field], z_fields, weight_field=("all", "particle_ones"), n_bins=[16, 16], ) particle_phases.append(ParticlePhasePlot.from_profile(pp)) particle_phases[0]._repr_html_() with mock.patch( "yt.visualization._mpl_imports.FigureCanvasAgg.print_figure" ), mock.patch( "yt.visualization._mpl_imports.FigureCanvasPdf.print_figure" ), mock.patch( "yt.visualization._mpl_imports.FigureCanvasPS.print_figure"): for p in particle_phases: for fname in TEST_FLNMS: p.save(fname)
def test_phase_plot(self): fields = ('density', 'temperature', 'velocity_x', 'velocity_y', 'velocity_z') units = ('g/cm**3', 'K', 'cm/s', 'cm/s', 'cm/s') test_ds = fake_random_ds(16, fields=fields, units=units) regions = [ test_ds.region([0.5] * 3, [0.4] * 3, [0.6] * 3), test_ds.all_data() ] phases = [] ph_fields = [('density', 'temperature', 'cell_mass'), ('density', 'velocity_x', 'cell_mass'), ('radius', 'temperature', 'velocity_magnitude')] for reg in regions: for x_field, y_field, z_field in ph_fields: # set n_bins to [16, 16] since matplotlib's postscript # renderer is slow when it has to write a lot of polygons phases.append( PhasePlot(reg, x_field, y_field, z_field, x_bins=16, y_bins=16)) phases.append( PhasePlot(reg, x_field, y_field, z_field, fractional=True, accumulation=True, x_bins=16, y_bins=16)) p2d = create_profile(reg, [x_field, y_field], z_field, n_bins=[16, 16]) phases.append(PhasePlot.from_profile(p2d)) pp = PhasePlot(test_ds.all_data(), 'density', 'temperature', 'cell_mass') pp.set_xlim(0.3, 0.8) pp.set_ylim(0.4, 0.6) pp._setup_plots() xlim = pp.plots['cell_mass'].axes.get_xlim() ylim = pp.plots['cell_mass'].axes.get_ylim() assert_array_almost_equal(xlim, (0.3, 0.8)) assert_array_almost_equal(ylim, (0.4, 0.6)) phases.append(pp) phases[0]._repr_html_() for p in phases: for fname in TEST_FLNMS: assert_fname(p.save(fname)[0])
def set_xlim(self, xmin=None, xmax=None): """Sets the limits of the bin field Parameters ---------- xmin : float or None The new x minimum. Defaults to None, which leaves the xmin unchanged. xmax : float or None The new x maximum. Defaults to None, which leaves the xmax unchanged. Examples -------- >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> pp = yt.ProfilePlot(ds.all_data(), 'density', 'temperature') >>> pp.set_xlim(1e-29, 1e-24) >>> pp.save() """ for i, p in enumerate(self.profiles): if xmin is None: xmi = p.x_bins.min() else: xmi = xmin if xmax is None: xma = p.x_bins.max() else: xma = xmax extrema = {p.x_field: ((xmi, str(p.x.units)), (xma, str(p.x.units)))} units = {p.x_field: str(p.x.units)} if self.x_log is None: logs = None else: logs = {p.x_field: self.x_log} for field in p.field_map.values(): units[field] = str(p.field_data[field].units) self.profiles[i] = \ create_profile(p.data_source, p.x_field, n_bins=len(p.x_bins)-1, fields=list(p.field_map.values()), weight_field=p.weight_field, accumulation=p.accumulation, fractional=p.fractional, logs=logs, extrema=extrema, units=units) return self
def set_ylim(self, ymin=None, ymax=None): """Sets the plot limits for the y bin field. Parameters ---------- ymin : float or None The new y minimum. Defaults to None, which leaves the ymin unchanged. ymax : float or None The new y maximum. Defaults to None, which leaves the ymax unchanged. Examples -------- >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> pp = yt.PhasePlot(ds.all_data(), 'density', 'temperature', 'cell_mass') >>> pp.set_ylim(1e4, 1e6) >>> pp.save() """ p = self.profile if ymin is None: ymin = p.y_bins.min() if ymax is None: ymax = p.y_bins.max() units = {p.x_field: str(p.x.units), p.y_field: str(p.y.units)} zunits = dict((field, str(p.field_units[field])) for field in p.field_units) extrema = {p.x_field: ((p.x_bins.min(), str(p.x.units)), (p.x_bins.max(), str(p.x.units))), p.y_field: ((ymin, str(p.y.units)), (ymax, str(p.y.units)))} self.profile = create_profile( p.data_source, [p.x_field, p.y_field], p.field_map.values(), n_bins=[len(p.x_bins), len(p.y_bins)], weight_field=p.weight_field, accumulation=p.accumulation, fractional=p.fractional, units=units, extrema=extrema) for field in zunits: self.profile.set_field_unit(field, zunits[field]) return self
def __init__(self, data_source, x_field, y_field, z_fields, weight_field="cell_mass", x_bins=128, y_bins=128, accumulation=False, fractional=False, fontsize=18, figure_size=8.0): profile = create_profile( data_source, [x_field, y_field], ensure_list(z_fields), n_bins=[x_bins, y_bins], weight_field=weight_field, accumulation=accumulation, fractional=fractional) type(self)._initialize_instance(self, data_source, profile, fontsize, figure_size)
def __init__(self, data_source, x_field, y_field, z_fields=None, color='b', x_bins=800, y_bins=800, weight_field=None, deposition='ngp', fontsize=18, figure_size=8.0): # if no z_fields are passed in, use a constant color if z_fields is None: self.use_cbar = False self.splat_color = color z_fields = ['particle_ones'] profile = create_profile( data_source, [x_field, y_field], ensure_list(z_fields), n_bins=[x_bins, y_bins], weight_field=weight_field, deposition=deposition) type(self)._initialize_instance(self, data_source, profile, fontsize, figure_size)
def test_profiles(): ds = fake_random_ds(64, nprocs=8, fields=_fields, units=_units) nv = ds.domain_dimensions.prod() dd = ds.all_data() (rmi, rma), (tmi, tma), (dmi, dma) = dd.quantities["Extrema"]( ["density", "temperature", "dinosaurs"]) rt, tt, dt = dd.quantities["TotalQuantity"]( ["density", "temperature", "dinosaurs"]) # First we look at the e1, e2 = 0.9, 1.1 for nb in [8, 16, 32, 64]: # We log all the fields or don't log 'em all. No need to do them # individually. for lf in [True, False]: direct_profile = Profile1D(dd, "density", nb, rmi * e1, rma * e2, lf, weight_field=None) direct_profile.add_fields(["ones", "temperature"]) indirect_profile_s = create_profile( dd, "density", ["ones", "temperature"], n_bins=nb, extrema={'density': (rmi * e1, rma * e2)}, logs={'density': lf}, weight_field=None) indirect_profile_t = create_profile( dd, ("gas", "density"), [("index", "ones"), ("gas", "temperature")], n_bins=nb, extrema={'density': (rmi * e1, rma * e2)}, logs={'density': lf}, weight_field=None) for p1d in [ direct_profile, indirect_profile_s, indirect_profile_t ]: yield assert_equal, p1d["index", "ones"].sum(), nv yield assert_rel_equal, tt, p1d["gas", "temperature"].sum(), 7 p2d = Profile2D(dd, "density", nb, rmi * e1, rma * e2, lf, "temperature", nb, tmi * e1, tma * e2, lf, weight_field=None) p2d.add_fields(["ones", "temperature"]) yield assert_equal, p2d["ones"].sum(), nv yield assert_rel_equal, tt, p2d["temperature"].sum(), 7 p3d = Profile3D(dd, "density", nb, rmi * e1, rma * e2, lf, "temperature", nb, tmi * e1, tma * e2, lf, "dinosaurs", nb, dmi * e1, dma * e2, lf, weight_field=None) p3d.add_fields(["ones", "temperature"]) yield assert_equal, p3d["ones"].sum(), nv yield assert_rel_equal, tt, p3d["temperature"].sum(), 7 p1d = Profile1D(dd, "x", nb, 0.0, 1.0, False, weight_field=None) p1d.add_fields("ones") av = nv / nb yield assert_equal, p1d["ones"], np.ones(nb) * av # We re-bin ones with a weight now p1d = Profile1D(dd, "x", nb, 0.0, 1.0, False, weight_field="temperature") p1d.add_fields(["ones"]) yield assert_equal, p1d["ones"], np.ones(nb) # Verify we can access "ones" after adding a new field # See issue 988 p1d.add_fields(["density"]) yield assert_equal, p1d["ones"], np.ones(nb) p2d = Profile2D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, weight_field=None) p2d.add_fields("ones") av = nv / nb**2 yield assert_equal, p2d["ones"], np.ones((nb, nb)) * av # We re-bin ones with a weight now p2d = Profile2D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, weight_field="temperature") p2d.add_fields(["ones"]) yield assert_equal, p2d["ones"], np.ones((nb, nb)) p3d = Profile3D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, "z", nb, 0.0, 1.0, False, weight_field=None) p3d.add_fields("ones") av = nv / nb**3 yield assert_equal, p3d["ones"], np.ones((nb, nb, nb)) * av # We re-bin ones with a weight now p3d = Profile3D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, "z", nb, 0.0, 1.0, False, weight_field="temperature") p3d.add_fields(["ones"]) yield assert_equal, p3d["ones"], np.ones((nb, nb, nb))
def set_ylim(self, ymin=None, ymax=None): """Sets the plot limits for the y bin field. Parameters ---------- ymin : float or None The new y minimum. Defaults to None, which leaves the ymin unchanged. ymax : float or None The new y maximum. Defaults to None, which leaves the ymax unchanged. Examples -------- >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> pp = yt.PhasePlot(ds.all_data(), 'density', 'temperature', 'cell_mass') >>> pp.set_ylim(1e4, 1e6) >>> pp.save() """ p = self.profile if ymin is None: ymin = p.y_bins.min() if ymax is None: ymax = p.y_bins.max() units = {p.x_field: str(p.x.units), p.y_field: str(p.y.units)} zunits = dict((field, str(p.field_units[field])) for field in p.field_units) extrema = {p.x_field: ((p.x_bins.min(), str(p.x.units)), (p.x_bins.max(), str(p.x.units))), p.y_field: ((ymin, str(p.y.units)), (ymax, str(p.y.units)))} if self.x_log is not None or self.y_log is not None: logs = {} else: logs = None if self.x_log is not None: logs[p.x_field] = self.x_log if self.y_log is not None: logs[p.y_field] = self.y_log deposition = getattr(self.profile, "deposition", None) if deposition is None: additional_kwargs = {'accumulation': p.accumulation, 'fractional': p.fractional} else: additional_kwargs = {'deposition': p.deposition} self.profile = create_profile( p.data_source, [p.x_field, p.y_field], list(p.field_map.values()), n_bins=[len(p.x_bins)-1, len(p.y_bins)-1], weight_field=p.weight_field, units=units, extrema=extrema, logs=logs, **additional_kwargs) for field in zunits: self.profile.set_field_unit(field, zunits[field]) return self
def profile(halo, bin_fields, profile_fields, n_bins=32, extrema=None, logs=None, units=None, weight_field="cell_mass", accumulation=False, fractional=False, storage="profiles", output_dir="."): r""" Create 1, 2, or 3D profiles of a halo. Store profile data in a dictionary associated with the halo object. Parameters ---------- halo : Halo object The Halo object to be provided by the HaloCatalog. bin_fields : list of strings The binning fields for the profile. profile_fields : string or list of strings The fields to be profiled. n_bins : int or list of ints The number of bins in each dimension. If None, 32 bins for each bin are used for each bin field. Default: 32. extrema : dict of min, max tuples Minimum and maximum values of the bin_fields for the profiles. The keys correspond to the field names. Defaults to the extrema of the bin_fields of the dataset. If a units dict is provided, extrema are understood to be in the units specified in the dictionary. logs : dict of boolean values Whether or not to log the bin_fields for the profiles. The keys correspond to the field names. Defaults to the take_log attribute of the field. units : dict of strings The units of the fields in the profiles, including the bin_fields. weight_field : string Weight field for profiling. Default : "cell_mass" accumulation : bool or list of bools If True, the profile values for a bin n are the cumulative sum of all the values from bin 0 to n. If -True, the sum is reversed so that the value for bin n is the cumulative sum from bin N (total bins) to n. If the profile is 2D or 3D, a list of values can be given to control the summation in each dimension independently. Default: False. fractional : If True the profile values are divided by the sum of all the profile data such that the profile represents a probability distribution function. storage : string Name of the dictionary to store profiles. Default: "profiles" output_dir : string Name of directory where profile data will be written. The full path will be the output_dir of the halo catalog concatenated with this directory. Default : "." """ mylog.info("Calculating 1D profile for halo %d." % halo.quantities["particle_identifier"]) dds = halo.halo_catalog.data_ds if dds is None: raise RuntimeError("Profile callback requires a data ds.") if not hasattr(halo, "data_object"): raise RuntimeError("Profile callback requires a data container.") if halo.data_object is None: mylog.info("Skipping halo %d since data_object is None." % halo.quantities["particle_identifier"]) return if output_dir is None: output_dir = storage output_dir = os.path.join(halo.halo_catalog.output_dir, output_dir) bin_fields = ensure_list(bin_fields) my_profile = create_profile(halo.data_object, bin_fields, profile_fields, n_bins=n_bins, extrema=extrema, logs=logs, units=units, weight_field=weight_field, accumulation=accumulation, fractional=fractional) prof_store = dict([(field, my_profile[field]) \ for field in my_profile.field_data]) prof_store[my_profile.x_field] = my_profile.x if len(bin_fields) > 1: prof_store[my_profile.y_field] = my_profile.y if len(bin_fields) > 2: prof_store[my_profile.z_field] = my_profile.z if hasattr(halo, storage): halo_store = getattr(halo, storage) if "used" in halo_store: halo_store["used"] &= my_profile.used else: halo_store = {"used": my_profile.used} setattr(halo, storage, halo_store) halo_store.update(prof_store) if my_profile.standard_deviation is not None: variance_store = dict([(field, my_profile.standard_deviation[field]) \ for field in my_profile.standard_deviation]) variance_storage = "%s_variance" % storage if hasattr(halo, variance_storage): halo_variance_store = getattr(halo, variance_storage) else: halo_variance_store = {} setattr(halo, variance_storage, halo_variance_store) halo_variance_store.update(variance_store)
def set_ylim(self, ymin=None, ymax=None): """Sets the plot limits for the y bin field. Parameters ---------- ymin : float or None The new y minimum. Defaults to None, which leaves the ymin unchanged. ymax : float or None The new y maximum. Defaults to None, which leaves the ymax unchanged. Examples -------- >>> import yt >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030') >>> pp = yt.PhasePlot(ds.all_data(), 'density', 'temperature', 'cell_mass') >>> pp.set_ylim(1e4, 1e6) >>> pp.save() """ p = self.profile if ymin is None: ymin = p.y_bins.min() if ymax is None: ymax = p.y_bins.max() units = {p.x_field: str(p.x.units), p.y_field: str(p.y.units)} zunits = dict((field, str(p.field_units[field])) for field in p.field_units) extrema = {p.x_field: ((p.x_bins.min(), str(p.x.units)), (p.x_bins.max(), str(p.x.units))), p.y_field: ((ymin, str(p.y.units)), (ymax, str(p.y.units)))} if self.x_log is not None or self.y_log is not None: logs = {} else: logs = None if self.x_log is not None: logs[p.x_field] = self.x_log if self.y_log is not None: logs[p.y_field] = self.y_log deposition = getattr(self.profile, "deposition", None) if deposition is None: additional_kwargs = {'accumulation': p.accumulation, 'fractional': p.fractional} else: additional_kwargs = {'deposition': p.deposition} self.profile = create_profile( p.data_source, [p.x_field, p.y_field], list(p.field_map.values()), n_bins=[len(p.x_bins)-1, len(p.y_bins)-1], weight_field=p.weight_field, units=units, extrema=extrema, logs=logs, **additional_kwargs) for field in zunits: self.profile.set_field_unit(field, zunits[field]) self._ylim = (ymin, ymax) return self
def test_profiles(): ds = fake_random_ds(64, nprocs=8, fields=_fields, units=_units) nv = ds.domain_dimensions.prod() dd = ds.all_data() (rmi, rma), (tmi, tma), (dmi, dma) = dd.quantities["Extrema"]( ["density", "temperature", "dinosaurs"]) rt, tt, dt = dd.quantities["TotalQuantity"]( ["density", "temperature", "dinosaurs"]) e1, e2 = 0.9, 1.1 for nb in [8, 16, 32, 64]: for input_units in ['mks', 'cgs']: for ex in [rmi, rma, tmi, tma, dmi, dma]: getattr(ex, 'convert_to_%s' % input_units)() # We log all the fields or don't log 'em all. No need to do them # individually. for lf in [True, False]: direct_profile = Profile1D(dd, "density", nb, rmi * e1, rma * e2, lf, weight_field=None) direct_profile.add_fields(["ones", "temperature"]) indirect_profile_s = create_profile( dd, "density", ["ones", "temperature"], n_bins=nb, extrema={'density': (rmi * e1, rma * e2)}, logs={'density': lf}, weight_field=None) indirect_profile_t = create_profile( dd, ("gas", "density"), [("index", "ones"), ("gas", "temperature")], n_bins=nb, extrema={'density': (rmi * e1, rma * e2)}, logs={'density': lf}, weight_field=None) for p1d in [ direct_profile, indirect_profile_s, indirect_profile_t ]: assert_equal(p1d["index", "ones"].sum(), nv) assert_rel_equal(tt, p1d["gas", "temperature"].sum(), 7) p2d = Profile2D(dd, "density", nb, rmi * e1, rma * e2, lf, "temperature", nb, tmi * e1, tma * e2, lf, weight_field=None) p2d.add_fields(["ones", "temperature"]) assert_equal(p2d["ones"].sum(), nv) assert_rel_equal(tt, p2d["temperature"].sum(), 7) p3d = Profile3D(dd, "density", nb, rmi * e1, rma * e2, lf, "temperature", nb, tmi * e1, tma * e2, lf, "dinosaurs", nb, dmi * e1, dma * e2, lf, weight_field=None) p3d.add_fields(["ones", "temperature"]) assert_equal(p3d["ones"].sum(), nv) assert_rel_equal(tt, p3d["temperature"].sum(), 7) p1d = Profile1D(dd, "x", nb, 0.0, 1.0, False, weight_field=None) p1d.add_fields("ones") av = nv / nb assert_equal(p1d["ones"], np.ones(nb) * av) # We re-bin ones with a weight now p1d = Profile1D(dd, "x", nb, 0.0, 1.0, False, weight_field="temperature") p1d.add_fields(["ones"]) assert_equal(p1d["ones"], np.ones(nb)) # Verify we can access "ones" after adding a new field # See issue 988 p1d.add_fields(["density"]) assert_equal(p1d["ones"], np.ones(nb)) p2d = Profile2D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, weight_field=None) p2d.add_fields("ones") av = nv / nb**2 assert_equal(p2d["ones"], np.ones((nb, nb)) * av) # We re-bin ones with a weight now p2d = Profile2D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, weight_field="temperature") p2d.add_fields(["ones"]) assert_equal(p2d["ones"], np.ones((nb, nb))) p3d = Profile3D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, "z", nb, 0.0, 1.0, False, weight_field=None) p3d.add_fields("ones") av = nv / nb**3 assert_equal(p3d["ones"], np.ones((nb, nb, nb)) * av) # We re-bin ones with a weight now p3d = Profile3D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, "z", nb, 0.0, 1.0, False, weight_field="temperature") p3d.add_fields(["ones"]) assert_equal(p3d["ones"], np.ones((nb, nb, nb))) p2d = create_profile(dd, ('gas', 'density'), ('gas', 'temperature'), weight_field=('gas', 'cell_mass'), extrema={'density': (None, rma * e2)}) assert_equal(p2d.x_bins[0], rmi - np.spacing(rmi)) assert_equal(p2d.x_bins[-1], rma * e2) p2d = create_profile(dd, ('gas', 'density'), ('gas', 'temperature'), weight_field=('gas', 'cell_mass'), extrema={'density': (rmi * e2, None)}) assert_equal(p2d.x_bins[0], rmi * e2) assert_equal(p2d.x_bins[-1], rma + np.spacing(rma))
def test_profiles(): ds = fake_random_ds(64, nprocs = 8, fields = _fields, units = _units) nv = ds.domain_dimensions.prod() dd = ds.all_data() (rmi, rma), (tmi, tma), (dmi, dma) = dd.quantities["Extrema"]( ["density", "temperature", "dinosaurs"]) rt, tt, dt = dd.quantities["TotalQuantity"]( ["density", "temperature", "dinosaurs"]) # First we look at the e1, e2 = 0.9, 1.1 for nb in [8, 16, 32, 64]: # We log all the fields or don't log 'em all. No need to do them # individually. for lf in [True, False]: direct_profile = Profile1D( dd, "density", nb, rmi*e1, rma*e2, lf, weight_field = None) direct_profile.add_fields(["ones", "temperature"]) indirect_profile_s = create_profile( dd, "density", ["ones", "temperature"], n_bins=nb, extrema={'density': (rmi*e1, rma*e2)}, logs={'density': lf}, weight_field=None) indirect_profile_t = create_profile( dd, ("gas", "density"), [("index", "ones"), ("gas", "temperature")], n_bins=nb, extrema={'density': (rmi*e1, rma*e2)}, logs={'density': lf}, weight_field=None) for p1d in [direct_profile, indirect_profile_s, indirect_profile_t]: yield assert_equal, p1d["index", "ones"].sum(), nv yield assert_rel_equal, tt, p1d["gas", "temperature"].sum(), 7 p2d = Profile2D(dd, "density", nb, rmi*e1, rma*e2, lf, "temperature", nb, tmi*e1, tma*e2, lf, weight_field = None) p2d.add_fields(["ones", "temperature"]) yield assert_equal, p2d["ones"].sum(), nv yield assert_rel_equal, tt, p2d["temperature"].sum(), 7 p3d = Profile3D(dd, "density", nb, rmi*e1, rma*e2, lf, "temperature", nb, tmi*e1, tma*e2, lf, "dinosaurs", nb, dmi*e1, dma*e2, lf, weight_field = None) p3d.add_fields(["ones", "temperature"]) yield assert_equal, p3d["ones"].sum(), nv yield assert_rel_equal, tt, p3d["temperature"].sum(), 7 p1d = Profile1D(dd, "x", nb, 0.0, 1.0, False, weight_field = None) p1d.add_fields("ones") av = nv / nb yield assert_equal, p1d["ones"], np.ones(nb)*av # We re-bin ones with a weight now p1d = Profile1D(dd, "x", nb, 0.0, 1.0, False, weight_field = "temperature") p1d.add_fields(["ones"]) yield assert_equal, p1d["ones"], np.ones(nb) # Verify we can access "ones" after adding a new field # See issue 988 p1d.add_fields(["density"]) yield assert_equal, p1d["ones"], np.ones(nb) p2d = Profile2D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, weight_field = None) p2d.add_fields("ones") av = nv / nb**2 yield assert_equal, p2d["ones"], np.ones((nb, nb))*av # We re-bin ones with a weight now p2d = Profile2D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, weight_field = "temperature") p2d.add_fields(["ones"]) yield assert_equal, p2d["ones"], np.ones((nb, nb)) p3d = Profile3D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, "z", nb, 0.0, 1.0, False, weight_field = None) p3d.add_fields("ones") av = nv / nb**3 yield assert_equal, p3d["ones"], np.ones((nb, nb, nb))*av # We re-bin ones with a weight now p3d = Profile3D(dd, "x", nb, 0.0, 1.0, False, "y", nb, 0.0, 1.0, False, "z", nb, 0.0, 1.0, False, weight_field = "temperature") p3d.add_fields(["ones"]) yield assert_equal, p3d["ones"], np.ones((nb,nb,nb))
def my_profile(dobj, bin_fields, profile_fields, n_bins=None, extrema=None, logs=None, units=None, weight_field=("gas", "cell_mass"), accumulation=False, fractional=False, bin_density=None): r""" Create 1, 2, or 3D profiles. Store profile data in a dictionary associated with the halo object. Parameters ---------- dobj : data container The object to use for profiling. bin_fields : list of strings The binning fields for the profile. profile_fields : string or list of strings The fields to be profiled. n_bins : int or list of ints The number of bins in each dimension. If None, 32 bins for each bin are used for each bin field. Default: 32. extrema : dict of min, max tuples Minimum and maximum values of the bin_fields for the profiles. The keys correspond to the field names. Defaults to the extrema of the bin_fields of the dataset. If a units dict is provided, extrema are understood to be in the units specified in the dictionary. logs : dict of boolean values Whether or not to log the bin_fields for the profiles. The keys correspond to the field names. Defaults to the take_log attribute of the field. units : dict of strings The units of the fields in the profiles, including the bin_fields. weight_field : string Weight field for profiling. Default : "cell_mass" accumulation : bool or list of bools If True, the profile values for a bin n are the cumulative sum of all the values from bin 0 to n. If -True, the sum is reversed so that the value for bin n is the cumulative sum from bin N (total bins) to n. If the profile is 2D or 3D, a list of values can be given to control the summation in each dimension independently. Default: False. fractional : If True the profile values are divided by the sum of all the profile data such that the profile represents a probability distribution function. """ ds = dobj.ds if units is None: units = {} if isinstance(bin_fields[0], str): bin_fields = [bin_fields] if bin_density is None: if n_bins is None: n_bins = dict((bin_field, 32) for bin_field in bin_fields) else: if n_bins is None: n_bins = {} elif not isinstance(n_bins, dict): raise RuntimeError("Can only specify n_bins or bin_density, but not both.") if extrema is None: extrema = {} ex_fields = set(bin_fields).difference(extrema.keys()) if ex_fields: exs = dobj.quantities.extrema(bin_fields) if isinstance(exs, unyt_array): exs = (exs,) for field, ex in zip(bin_fields, exs): extrema[field] = ex for bin_field, ex in extrema.items(): if bin_field in n_bins: continue if bin_field in units: ex.convert_to_units(units[bin_field]) if logs is None: my_log = True else: my_log = logs.get(bin_field, True) if ex[1] <= ex[0]: raise ValueError(f"Min is greater than max for {bin_field}: {ex}.") if np.inf in np.abs(ex): fd = dobj[bin_field] if bin_field in units: fd.convert_to_units(units[bin_field]) if ex[0] == -np.inf: ex[0] = fd[fd > -np.inf].min() if ex[1] == np.inf: ex[1] = fd[fd < np.inf].max() del fd if my_log: if ex[0] <= 0: fd = dobj[bin_field] if bin_field in units: fd.convert_to_units(units[bin_field]) ex[0] = fd[fd > 0].min() del fd mi = 10**np.floor(np.log10(ex[0])) ma = 10**np.ceil(np.log10(ex[1])) else: mi = np.floor(ex[0]) ma = np.ceil(ex[1]) extrema[bin_field] = (mi, ma) my_ex = extrema[bin_field] if my_log: my_n_bins = int(np.log10(my_ex[1] / my_ex[0]) * bin_density) else: my_n_bins = int((my_ex[1] - my_ex[0]) * bin_density) n_bins[bin_field] = my_n_bins if isinstance(n_bins, dict): n_bins = tuple([n_bins[bin_field] for bin_field in bin_fields]) bin_fields = list(always_iterable(bin_fields)) prof = create_profile( dobj, bin_fields, profile_fields, n_bins=n_bins, extrema=extrema, logs=logs, units=units, weight_field=weight_field, accumulation=accumulation, fractional=fractional) return prof