def test_plot_data(): tmpdir = tempfile.mkdtemp() curdir = os.getcwd() os.chdir(tmpdir) ds = fake_random_ds(16) plot = SlicePlot(ds, 'z', 'density') plot.data_source.save_as_dataset('slice.h5') ds_slice = load('slice.h5') p = SlicePlot(ds_slice, 'z', 'density') fn = p.save() assert_fname(fn[0]) plot = ProjectionPlot(ds, 'z', 'density') plot.data_source.save_as_dataset('proj.h5') ds_proj = load('slice.h5') p = ProjectionPlot(ds_proj, 'z', 'density') fn = p.save() assert_fname(fn[0]) plot = SlicePlot(ds, [1, 1, 1], 'density') plot.data_source.save_as_dataset('oas.h5') ds_oas = load('oas.h5') p = SlicePlot(ds_oas, [1, 1, 1], 'density') fn = p.save() assert_fname(fn[0]) os.chdir(curdir) shutil.rmtree(tmpdir)
def test_plot_data(): tmpdir = tempfile.mkdtemp() curdir = os.getcwd() os.chdir(tmpdir) ds = fake_random_ds(16) plot = SlicePlot(ds, "z", ("gas", "density")) fn = plot.data_source.save_as_dataset("slice.h5") ds_slice = load(fn) p = SlicePlot(ds_slice, "z", ("gas", "density")) fn = p.save() assert_fname(fn[0]) plot = ProjectionPlot(ds, "z", ("gas", "density")) fn = plot.data_source.save_as_dataset("proj.h5") ds_proj = load(fn) p = ProjectionPlot(ds_proj, "z", ("gas", "density")) fn = p.save() assert_fname(fn[0]) plot = SlicePlot(ds, [1, 1, 1], ("gas", "density")) fn = plot.data_source.save_as_dataset("oas.h5") ds_oas = load(fn) p = SlicePlot(ds_oas, [1, 1, 1], ("gas", "density")) fn = p.save() assert_fname(fn[0]) os.chdir(curdir) if tmpdir != ".": shutil.rmtree(tmpdir)
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 setUp(self): if self.ds is None: self.ds = fake_random_ds(64) self.slc = SlicePlot(self.ds, 0, ("gas", "density")) self.tmpdir = tempfile.mkdtemp() self.curdir = os.getcwd() os.chdir(self.tmpdir)
def test_dispatch_plot_classes(): ds = fake_random_ds(16) p1 = ProjectionPlot(ds, "z", ("gas", "density")) p2 = ProjectionPlot(ds, (1, 2, 3), ("gas", "density")) s1 = SlicePlot(ds, "z", ("gas", "density")) s2 = SlicePlot(ds, (1, 2, 3), ("gas", "density")) assert isinstance(p1, AxisAlignedProjectionPlot) assert isinstance(p2, OffAxisProjectionPlot) assert isinstance(s1, AxisAlignedSlicePlot) assert isinstance(s2, OffAxisSlicePlot)
def test_nan_data(): data = np.random.random((16, 16, 16)) - 0.5 data[:9, :9, :9] = np.nan data = {"density": data} ds = load_uniform_grid(data, [16, 16, 16]) plot = SlicePlot(ds, "z", ("gas", "density")) with tempfile.NamedTemporaryFile(suffix="png") as f: plot.save(f.name)
def test_old_plot_data(): tmpdir = tempfile.mkdtemp() curdir = os.getcwd() os.chdir(tmpdir) fn = "slice.h5" full_fn = os.path.join(ytdata_dir, fn) ds_slice = data_dir_load(full_fn) p = SlicePlot(ds_slice, "z", ("gas", "density")) fn = p.save() assert_fname(fn[0]) fn = "proj.h5" full_fn = os.path.join(ytdata_dir, fn) ds_proj = data_dir_load(full_fn) p = ProjectionPlot(ds_proj, "z", ("gas", "density")) fn = p.save() assert_fname(fn[0]) fn = "oas.h5" full_fn = os.path.join(ytdata_dir, fn) ds_oas = data_dir_load(full_fn) p = SlicePlot(ds_oas, [1, 1, 1], ("gas", "density")) fn = p.save() assert_fname(fn[0]) os.chdir(curdir) shutil.rmtree(tmpdir)
def test_code_units_xy_labels(): ds = data_dir_load("amrvac/bw_3d0000.dat", kwargs=dict(unit_system="code")) p = SlicePlot(ds, "x", ("gas", "density")) ax = p.plots[("gas", "density")].axes assert "code length" in ax.get_xlabel().replace("\\", "") assert "code length" in ax.get_ylabel().replace("\\", "")
def __call__(self, args): if sys.version_info >= (3, 0, 0): print("yt mapserver is disabled for Python 3.") return -1 ds = args.ds if args.axis == 4: print("Doesn't work with multiple axes!") return if args.projection: p = ProjectionPlot(ds, args.axis, args.field, weight_field=args.weight) else: p = SlicePlot(ds, args.axis, args.field) from yt.visualization.mapserver.pannable_map import PannableMapServer PannableMapServer(p.data_source, args.field) import yt.extern.bottle as bottle bottle.debug(True) bottle_dir = os.path.dirname(bottle.__file__) sys.path.append(bottle_dir) if args.host is not None: colonpl = args.host.find(":") if colonpl >= 0: port = int(args.host.split(":")[-1]) args.host = args.host[:colonpl] else: port = 8080 bottle.run(server='rocket', host=args.host, port=port) else: bottle.run(server='rocket') sys.path.remove(bottle_dir)
def __call__(self, args): ds = args.ds center = args.center if args.center == (-1, -1, -1): mylog.info("No center fed in; seeking.") v, center = ds.find_max("density") if args.max: v, center = ds.find_max("density") elif args.center is None: center = 0.5 * (ds.domain_left_edge + ds.domain_right_edge) center = np.array(center) if ds.dimensionality < 3: dummy_dimensions = np.nonzero( ds.index.grids[0].ActiveDimensions <= 1) axes = dummy_dimensions[0][0] elif args.axis == 4: axes = range(3) else: axes = args.axis unit = args.unit if unit is None: unit = "unitary" if args.width is None: width = None else: width = (args.width, args.unit) for ax in always_iterable(axes): mylog.info("Adding plot for axis %i", ax) if args.projection: plt = ProjectionPlot( ds, ax, args.field, center=center, width=width, weight_field=args.weight, ) else: plt = SlicePlot(ds, ax, args.field, center=center, width=width) if args.grids: plt.annotate_grids() if args.time: plt.annotate_timestamp() if args.show_scale_bar: plt.annotate_scale() if args.field_unit: plt.set_unit(args.field, args.field_unit) plt.set_cmap(args.field, args.cmap) plt.set_log(args.field, args.takelog) if args.zlim: plt.set_zlim(args.field, *args.zlim) ensure_dir_exists(args.output) plt.save(os.path.join(args.output, f"{ds}"))
def test_deeply_nested_zoom(): ds = data_dir_load(dnz) # carefully chosen to just barely miss a grid in the middle of the image center = [0.4915073260199302, 0.5052605316800006, 0.4905805557500548] plot = SlicePlot(ds, 'z', 'density', width=(0.001, 'pc'), center=center) image = plot.frb['density'] assert (image > 0).all()
def test_symlog_extremely_small_vals(): # check that the plot can be constructed without crashing # see https://github.com/yt-project/yt/issues/3858 shape = (64, 64, 1) arr = np.full(shape, 5.0e-324) arr[0, 0] = -1e12 arr[1, 1] = 200 d = {"scalar": arr} ds = load_uniform_grid(d, shape) p = SlicePlot(ds, "z", ("stream", "scalar")) p["stream", "scalar"]
def test_invalid_swap_projection(): # projections and transforms will not work ds = fake_amr_ds(geometry="geographic") slc = SlicePlot(ds, "altitude", ds.field_list[0], origin="native") slc.set_mpl_projection("Robinson") slc.swap_axes() # should raise mylog.warning and not toggle _swap_axes assert slc._has_swapped_axes is False
def test_symlog_colorbar(): ds = fake_random_ds(16) def _thresh_density(field, data): wh = data[("gas", "density")] < 0.5 ret = data[("gas", "density")] ret[wh] = 0 return ret def _neg_density(field, data): return -data[("gas", "threshold_density")] ds.add_field( ("gas", "threshold_density"), function=_thresh_density, units="g/cm**3", sampling_type="cell", ) ds.add_field( ("gas", "negative_density"), function=_neg_density, units="g/cm**3", sampling_type="cell", ) for field in [ ("gas", "density"), ("gas", "threshold_density"), ("gas", "negative_density"), ]: plot = SlicePlot(ds, 2, field) plot.set_log(field, True, linthresh=0.1) with tempfile.NamedTemporaryFile(suffix="png") as f: plot.save(f.name)
def test_frb_regen(): ds = fake_random_ds(32) slc = SlicePlot(ds, 2, ("gas", "density")) slc.set_buff_size(1200) assert_equal(slc.frb[("gas", "density")].shape, (1200, 1200)) slc.set_buff_size((400.0, 200.7)) assert_equal(slc.frb[("gas", "density")].shape, (200, 400))
def test_on_off_compare(): # fake density field that varies in the x-direction only den = np.arange(32**3) / 32**2 + 1 den = den.reshape(32, 32, 32) den = np.array(den, dtype=np.float64) data = dict(density=(den, "g/cm**3")) bbox = np.array([[-1.5, 1.5], [-1.5, 1.5], [-1.5, 1.5]]) ds = load_uniform_grid(data, den.shape, length_unit="Mpc", bbox=bbox, nprocs=64) sl_on = SlicePlot(ds, "z", [("gas", "density")]) L = [0, 0, 1] north_vector = [0, 1, 0] sl_off = OffAxisSlicePlot(ds, L, ("gas", "density"), center=[0, 0, 0], north_vector=north_vector) assert_array_almost_equal(sl_on.frb[("gas", "density")], sl_off.frb[("gas", "density")]) sl_on.set_buff_size((800, 400)) sl_on._recreate_frb() sl_off.set_buff_size((800, 400)) sl_off._recreate_frb() assert_array_almost_equal(sl_on.frb[("gas", "density")], sl_off.frb[("gas", "density")])
def test_set_background_color(): ds = fake_random_ds(32) plot = SlicePlot(ds, 2, ("gas", "density")) plot.set_background_color(("gas", "density"), "red") plot._setup_plots() ax = plot.plots[("gas", "density")].axes assert_equal(ax.get_facecolor(), (1.0, 0.0, 0.0, 1.0))
def __call__(self, args): ds = args.ds center = args.center if args.center == (-1, -1, -1): mylog.info("No center fed in; seeking.") v, center = ds.find_max("density") if args.max: v, center = ds.find_max("density") elif args.center is None: center = 0.5 * (ds.domain_left_edge + ds.domain_right_edge) center = np.array(center) if ds.dimensionality < 3: dummy_dimensions = np.nonzero( ds.index.grids[0].ActiveDimensions <= 1) axes = ensure_list(dummy_dimensions[0][0]) elif args.axis == 4: axes = range(3) else: axes = [args.axis] unit = args.unit if unit is None: unit = 'unitary' if args.width is None: width = None else: width = (args.width, args.unit) for ax in axes: mylog.info("Adding plot for axis %i", ax) if args.projection: plt = ProjectionPlot(ds, ax, args.field, center=center, width=width, weight_field=args.weight) else: plt = SlicePlot(ds, ax, args.field, center=center, width=width) if args.grids: plt.annotate_grids() if args.time: time = ds.current_time.in_units("yr") plt.annotate_text((0.2, 0.8), 't = %5.2e yr' % time) plt.set_cmap(args.field, args.cmap) plt.set_log(args.field, args.takelog) if args.zlim: plt.set_zlim(args.field, *args.zlim) ensure_dir_exists(args.output) plt.save(os.path.join(args.output, "%s" % (ds)))
def test_plot_2d(): # Cartesian ds = fake_random_ds((32, 32, 1), fields=("temperature", ), units=("K", )) slc = SlicePlot( ds, "z", [("gas", "temperature")], width=(0.2, "unitary"), center=[0.4, 0.3, 0.5], ) slc2 = plot_2d(ds, ("gas", "temperature"), width=(0.2, "unitary"), center=[0.4, 0.3]) slc3 = plot_2d( ds, ("gas", "temperature"), width=(0.2, "unitary"), center=ds.arr([0.4, 0.3], "cm"), ) assert_array_equal(slc.frb[("gas", "temperature")], slc2.frb[("gas", "temperature")]) assert_array_equal(slc.frb[("gas", "temperature")], slc3.frb[("gas", "temperature")]) # Cylindrical ds = data_dir_load(WD) slc = SlicePlot(ds, "theta", [("gas", "density")], width=(30000.0, "km")) slc2 = plot_2d(ds, ("gas", "density"), width=(30000.0, "km")) assert_array_equal(slc.frb[("gas", "density")], slc2.frb[("gas", "density")]) # Spherical ds = data_dir_load(blast_wave) slc = SlicePlot(ds, "phi", [("gas", "density")], width=(1, "unitary")) slc2 = plot_2d(ds, ("gas", "density"), width=(1, "unitary")) assert_array_equal(slc.frb[("gas", "density")], slc2.frb[("gas", "density")])
def test_deeply_nested_zoom(): ds = data_dir_load(dnz) # carefully chosen to just barely miss a grid in the middle of the image center = [0.4915073260199302, 0.5052605316800006, 0.4905805557500548] plot = SlicePlot(ds, "z", "density", width=(0.001, "pc"), center=center) image = plot.frb[("gas", "density")] assert (image > 0).all() v, c = ds.find_max(("gas", "density")) assert_allclose_units(v, ds.quan(0.005878286377124154, "g/cm**3")) c_actual = [0.49150732540021, 0.505260532936791, 0.49058055816398] c_actual = ds.arr(c_actual, "code_length") assert_allclose_units(c, c_actual) assert_equal(max([g[("gas", "density")].max() for g in ds.index.grids]), v)
def test_symlog_min_zero(): # see https://github.com/yt-project/yt/issues/3791 shape = (32, 16, 1) a = np.linspace(0, 1, 16) b = np.ones((32, 16)) c = np.reshape(a * b, shape) data = {("gas", "density"): c} ds = load_uniform_grid( data, shape, bbox=np.array([[0.0, 5.0], [0, 1], [-0.1, +0.1]]), ) p = SlicePlot(ds, "z", "density") im_arr = p["gas", "density"].image.get_array() # check that no data value was mapped to a NaN (log(0)) assert np.all(~np.isnan(im_arr)) # 0 should be mapped to itself since we expect a symlog norm assert np.min(im_arr) == 0.0
def test_deeply_nested_zoom(): ds = data_dir_load(dnz) # carefully chosen to just barely miss a grid in the middle of the image center = [0.4915073260199302, 0.5052605316800006, 0.4905805557500548] plot = SlicePlot(ds, 'z', 'density', width=(0.001, 'pc'), center=center) image = plot.frb['density'] assert (image > 0).all() v, c = ds.find_max('density') assert_allclose_units(v, ds.quan(0.005879315652144976, 'g/cm**3')) c_actual = [0.49150732540021, 0.505260532936791, 0.49058055816398] c_actual = ds.arr(c_actual, 'code_length') assert_allclose_units(c, c_actual) assert_equal(max([g['density'].max() for g in ds.index.grids]), v)
def test_set_unit(): ds = fake_random_ds(32, fields=(("gas", "temperature"), ), units=("K", )) slc = SlicePlot(ds, 2, ("gas", "temperature")) orig_array = slc.frb["gas", "temperature"].copy() slc.set_unit(("gas", "temperature"), "degF") assert str(slc.frb["gas", "temperature"].units) == "°F" assert_array_almost_equal(np.array(slc.frb["gas", "temperature"]), np.array(orig_array) * 1.8 - 459.67) # test that a plot modifying function that destroys the frb preserves the # new unit slc.set_buff_size(1000) assert str(slc.frb["gas", "temperature"].units) == "°F" slc.set_buff_size(800) slc.set_unit(("gas", "temperature"), "K") assert str(slc.frb["gas", "temperature"].units) == "K" assert_array_almost_equal(slc.frb["gas", "temperature"], orig_array) slc.set_unit(("gas", "temperature"), "keV", equivalency="thermal") assert str(slc.frb["gas", "temperature"].units) == "keV" assert_array_almost_equal(slc.frb["gas", "temperature"], (orig_array * kboltz).to("keV")) # test that a plot modifying function that destroys the frb preserves the # new unit with an equivalency slc.set_buff_size(1000) assert str(slc.frb["gas", "temperature"].units) == "keV" # test that destroying the FRB then changing the unit using an equivalency # doesn't error out, see issue #1316 slc = SlicePlot(ds, 2, ("gas", "temperature")) slc.set_buff_size(1000) slc.set_unit(("gas", "temperature"), "keV", equivalency="thermal") assert str(slc.frb["gas", "temperature"].units) == "keV"
class TestSetWidth(unittest.TestCase): ds = None def setUp(self): if self.ds is None: self.ds = fake_random_ds(64) self.slc = SlicePlot(self.ds, 0, ("gas", "density")) def tearDown(self): del self.ds del self.slc def _assert_05cm(self): assert_array_equal( [self.slc.xlim, self.slc.ylim, self.slc.width], [ (YTQuantity(0.25, "cm"), YTQuantity(0.75, "cm")), (YTQuantity(0.25, "cm"), YTQuantity(0.75, "cm")), (YTQuantity(0.5, "cm"), YTQuantity(0.5, "cm")), ], ) def _assert_05_075cm(self): assert_array_equal( [self.slc.xlim, self.slc.ylim, self.slc.width], [ (YTQuantity(0.25, "cm"), YTQuantity(0.75, "cm")), (YTQuantity(0.125, "cm"), YTQuantity(0.875, "cm")), (YTQuantity(0.5, "cm"), YTQuantity(0.75, "cm")), ], ) def test_set_width_one(self): assert_equal( [self.slc.xlim, self.slc.ylim, self.slc.width], [(0.0, 1.0), (0.0, 1.0), (1.0, 1.0)], ) assert_true(self.slc._axes_unit_names is None) def test_set_width_nonequal(self): self.slc.set_width((0.5, 0.8)) assert_rel_equal( [self.slc.xlim, self.slc.ylim, self.slc.width], [(0.25, 0.75), (0.1, 0.9), (0.5, 0.8)], 15, ) assert_true(self.slc._axes_unit_names is None) def test_twoargs_eq(self): self.slc.set_width(0.5, "cm") self._assert_05cm() assert_true(self.slc._axes_unit_names == ("cm", "cm")) def test_tuple_eq(self): self.slc.set_width((0.5, "cm")) self._assert_05cm() assert_true(self.slc._axes_unit_names == ("cm", "cm")) def test_tuple_of_tuples_neq(self): self.slc.set_width(((0.5, "cm"), (0.75, "cm"))) self._assert_05_075cm() assert_true(self.slc._axes_unit_names == ("cm", "cm"))
def test_setup_origin(): origin_inputs = ( "domain", "left-window", "center-domain", "lower-right-window", ("window", ), ("right", "domain"), ("lower", "window"), ("lower", "right", "window"), (0.5, 0.5, "domain"), ((50, "cm"), (50, "cm"), "domain"), ) w = (10, "cm") ds = fake_random_ds(32, length_unit=100.0) generated_limits = [] # lower limit -> llim # upper limit -> ulim # xllim xulim yllim yulim correct_limits = [ 45.0, 55.0, 45.0, 55.0, 0.0, 10.0, 0.0, 10.0, -5.0, 5.0, -5.0, 5.0, -10.0, 0, 0, 10.0, 0.0, 10.0, 0.0, 10.0, -55.0, -45.0, -55.0, -45.0, -5.0, 5.0, 0.0, 10.0, -10.0, 0, 0, 10.0, -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, ] for o in origin_inputs: slc = SlicePlot(ds, 2, ("gas", "density"), width=w, origin=o) ax = slc.plots[("gas", "density")].axes xlims = ax.get_xlim() ylims = ax.get_ylim() lims = [xlims[0], xlims[1], ylims[0], ylims[1]] for l in lims: generated_limits.append(l) assert_array_almost_equal(correct_limits, generated_limits)
def test_repr_html(self): test_ds = fake_random_ds(16) slc = SlicePlot(test_ds, 0, ("gas", "density")) slc._repr_html_()
def test_slice_plot(self): test_ds = fake_random_ds(16) for dim in range(3): slc = SlicePlot(test_ds, dim, ("gas", "density")) for fname in TEST_FLNMS: assert_fname(slc.save(fname)[0])
def __call__(self, args): from yt.frontends.ramses.data_structures import RAMSESDataset from yt.visualization.mapserver.pannable_map import PannableMapServer # For RAMSES datasets, use the bbox feature to make the dataset load faster if RAMSESDataset._is_valid(args.ds) and args.center and args.width: kwa = dict(bbox=[ [c - args.width / 2 for c in args.center], [c + args.width / 2 for c in args.center], ]) else: kwa = dict() ds = _fix_ds(args.ds, **kwa) if args.center and args.width: center = args.center width = args.width ad = ds.box( left_edge=[c - args.width / 2 for c in args.center], right_edge=[c + args.width / 2 for c in args.center], ) else: center = [0.5] * 3 width = 1.0 ad = ds.all_data() if args.axis >= 4: print("Doesn't work with multiple axes!") return if args.projection: p = ProjectionPlot( ds, args.axis, args.field, weight_field=args.weight, data_source=ad, center=center, width=width, ) else: p = SlicePlot(ds, args.axis, args.field, data_source=ad, center=center, width=width) p.set_log("all", args.takelog) p.set_cmap("all", args.cmap) PannableMapServer(p.data_source, args.field, args.takelog, args.cmap) try: import bottle except ImportError as e: raise ImportError( "The mapserver functionality requires the bottle " "package to be installed. Please install using `pip " "install bottle`.") from e bottle.debug(True) if args.host is not None: colonpl = args.host.find(":") if colonpl >= 0: port = int(args.host.split(":")[-1]) args.host = args.host[:colonpl] else: port = 8080 bottle.run(server="auto", host=args.host, port=port) else: bottle.run(server="auto")
def setUp(self): if self.ds is None: self.ds = fake_random_ds(64) self.slc = SlicePlot(self.ds, 0, ("gas", "density"))
class TestHideAxesColorbar(unittest.TestCase): ds = None def setUp(self): if self.ds is None: self.ds = fake_random_ds(64) self.slc = SlicePlot(self.ds, 0, ("gas", "density")) self.tmpdir = tempfile.mkdtemp() self.curdir = os.getcwd() os.chdir(self.tmpdir) def tearDown(self): os.chdir(self.curdir) shutil.rmtree(self.tmpdir) del self.ds del self.slc def test_hide_show_axes(self): self.slc.hide_axes() self.slc.save() self.slc.show_axes() self.slc.save() def test_hide_show_colorbar(self): self.slc.hide_colorbar() self.slc.save() self.slc.show_colorbar() self.slc.save() def test_hide_axes_colorbar(self): self.slc.hide_colorbar() self.slc.hide_axes() self.slc.save()