def run_mpl_testB(show=False): logger.info("3D node centered tests") x = np.array(np.linspace(-10, 10, 100), dtype=dtype) y = np.array(np.linspace(-10, 10, 120), dtype=dtype) z = np.array(np.linspace(-10, 10, 140), dtype=dtype) fld_s = viscid.empty([x, y, z], center='node') X, Y, Z = fld_s.get_crds_nc(shaped=True) # pylint: disable=W0612 fld_s[:, :, :] = np.sin(X) + np.cos(Y) - np.cos(Z) # print("shape: ", fld_s.data.shape) nrows = 4 ncols = 1 plt.subplot2grid((nrows, ncols), (0, 0)) mpl.plot(fld_s, "z=0,x=:30", earth=True, plot_opts="lin_0") plt.subplot2grid((nrows, ncols), (1, 0)) mpl.plot(fld_s, "z=0.75f,x=-4:-1,y=-3f:3f", earth=True) plt.subplot2grid((nrows, ncols), (2, 0)) mpl.plot(fld_s, "x=-0.5f:,y=-3f:3f,z=0f", earth=True) plt.subplot2grid((nrows, ncols), (3, 0)) mpl.plot(fld_s, "x=0.0f,y=-5.0f:5.0f", earth=True, plot_opts="log,g") mpl.plt.suptitle("3d node centered") mpl.auto_adjust_subplots() mpl.plt.savefig(next_plot_fname(__file__)) if show: mpl.mplshow()
def run_test_2d(f, main__file__, show=False): mpl.clf() slc = "x=-20f:12f, y=0f" plot_kwargs = dict(title=True, earth=True) mpl.subplot(141) mpl.plot(f['pp'], slc, logscale=True, **plot_kwargs) mpl.plot(np.abs(f['psi']), style='contour', logscale=True, levels=30, linewidths=0.8, colors='grey', linestyles='solid', cbar=None, x=(-20, 12)) mpl.subplot(142) mpl.plot(viscid.magnitude(f['bcc']), slc, logscale=True, **plot_kwargs) mpl.plot2d_quiver(f['v'][slc], step=5, color='y', pivot='mid', width=0.03, scale=600) mpl.subplot(143) mpl.plot(f['jy'], slc, clim=[-0.005, 0.005], **plot_kwargs) mpl.streamplot(f['v'][slc], linewidth=0.3) mpl.subplot(144) mpl.plot(f['jy'], "x=7f:12f, y=0f, z=0f") mpl.plt.suptitle("2D File") mpl.auto_adjust_subplots(subplot_params=dict(top=0.9, wspace=1.3)) mpl.plt.gcf().set_size_inches(10, 4) mpl.savefig(next_plot_fname(main__file__)) if show: mpl.show()
def run_test_iof(f, main__file__, show=False): mpl.clf() fac_tot = 1e9 * f["fac_tot"] plot_args = dict(projection="polar", lin=[-300, 300], bounding_lat=35.0, drawcoastlines=True, # for basemap only title="Total FAC\n", gridec='gray', label_lat=True, label_mlt=True, colorbar=dict(pad=0.1) # pad the colorbar away from the plot ) ax1 = mpl.subplot(121, projection='polar') mpl.plot(fac_tot, ax=ax1, hemisphere='north', **plot_args) ax1.annotate('(a)', xy=(0, 0), textcoords="axes fraction", xytext=(-0.1, 1.0), fontsize=18) ax2 = mpl.subplot(122, projection='polar') plot_args['gridec'] = False mpl.plot(fac_tot, ax=ax2, hemisphere="south", style="contourf", levels=50, extend="both", **plot_args) ax2.annotate('(b)', xy=(0, 0), textcoords="axes fraction", xytext=(-0.1, 1.0), fontsize=18) mpl.auto_adjust_subplots(subplot_params=dict()) mpl.plt.gcf().set_size_inches(8, 4) mpl.plt.savefig(next_plot_fname(main__file__)) if show: mpl.mplshow()
def run_mag_test(fld, title="", show=False): vx, vy, vz = fld.component_views() # pylint: disable=W0612 vx, vy, vz = fld.component_fields() try: t0 = time() mag_ne = viscid.magnitude(fld, preferred="numexpr", only=False) t1 = time() logger.info("numexpr mag runtime: %g", t1 - t0) except viscid.verror.BackendNotFound: xfail("Numexpr is not installed") planes = ["z=0", "y=0"] nrows = 4 ncols = len(planes) ax = plt.subplot2grid((nrows, ncols), (0, 0)) ax.axis("equal") for ind, p in enumerate(planes): plt.subplot2grid((nrows, ncols), (0, ind), sharex=ax, sharey=ax) mpl.plot(vx, p, show=False) plt.subplot2grid((nrows, ncols), (1, ind), sharex=ax, sharey=ax) mpl.plot(vy, p, show=False) plt.subplot2grid((nrows, ncols), (2, ind), sharex=ax, sharey=ax) mpl.plot(vz, p, show=False) plt.subplot2grid((nrows, ncols), (3, ind), sharex=ax, sharey=ax) mpl.plot(mag_ne, p, show=False) mpl.plt.suptitle(title) mpl.auto_adjust_subplots(subplot_params=dict(top=0.9)) mpl.plt.gcf().set_size_inches(6, 7) mpl.plt.savefig(next_plot_fname(__file__)) if show: mpl.mplshow()
def run_mpl_testA(show=False): logger.info("2D cell centered tests") x = np.array(np.linspace(-10, 10, 100), dtype=dtype) y = np.array(np.linspace(-10, 10, 120), dtype=dtype) z = np.array(np.linspace(-1, 1, 2), dtype=dtype) fld_s = viscid.empty([x, y, z], center='cell') Xcc, Ycc, Zcc = fld_s.get_crds_cc(shaped=True) # pylint: disable=unused-variable fld_s[:, :, :] = np.sin(Xcc) + np.cos(Ycc) nrows = 4 ncols = 1 plt.subplot2grid((nrows, ncols), (0, 0)) mpl.plot(fld_s, "y=20f", show=False, plot_opts="lin_0") plt.subplot2grid((nrows, ncols), (1, 0)) mpl.plot(fld_s, "x=0f:20f,y=0f:5f", earth=True, show=False, plot_opts="x_-10_0,y_0_7") plt.subplot2grid((nrows, ncols), (2, 0)) mpl.plot(fld_s, "y=0f", show=False, plot_opts="lin_-1_1") plt.subplot2grid((nrows, ncols), (3, 0)) mpl.plot(fld_s, "z=0f,x=-20f:0f", earth=True, show=False, plot_opts="lin_-5_5") mpl.plt.suptitle("2d cell centered") mpl.auto_adjust_subplots() mpl.plt.savefig(next_plot_fname(__file__)) if show: mpl.mplshow()
def run_div_test(fld, exact, title='', show=False, ignore_inexact=False): t0 = time() result_numexpr = viscid.div(fld, preferred="numexpr", only=False) t1 = time() logger.info("numexpr magnitude runtime: %g", t1 - t0) result_diff = viscid.diff(result_numexpr, exact)['x=1:-1, y=1:-1, z=1:-1'] if not ignore_inexact and not (result_diff.data < 5e-5).all(): logger.warn("numexpr result is far from the exact result") logger.info("min/max(abs(numexpr - exact)): %g / %g", np.min(result_diff.data), np.max(result_diff.data)) planes = ["y=0f", "z=0f"] nrows = 2 ncols = len(planes) ax = plt.subplot2grid((nrows, ncols), (0, 0)) ax.axis("equal") for i, p in enumerate(planes): plt.subplot2grid((nrows, ncols), (0, i), sharex=ax, sharey=ax) mpl.plot(result_numexpr, p, show=False) plt.subplot2grid((nrows, ncols), (1, i), sharex=ax, sharey=ax) mpl.plot(result_diff, p, show=False) mpl.plt.suptitle(title) mpl.auto_adjust_subplots(subplot_params=dict(top=0.9)) mpl.plt.savefig(next_plot_fname(__file__)) if show: mpl.mplshow()
def main(): parser = argparse.ArgumentParser(description="Test divergence") parser.add_argument("--show", "--plot", action="store_true") args = viscid.vutil.common_argparse(parser) # args.show = True t = viscid.linspace_datetime64("2006-06-10 12:30:00.0", "2006-06-10 12:33:00.0", 16) tL = viscid.as_datetime64("2006-06-10 12:31:00.0") tR = viscid.as_datetime64("2006-06-10 12:32:00.0") y = np.linspace(2 * np.pi, 4 * np.pi, 12) ### plots with a datetime64 axis f0 = viscid.ones([t, y], crd_names="ty", center="node") T, Y = f0.get_crds(shaped=True) f0.data += np.arange(T.size).reshape(T.shape) f0.data += np.cos(Y) fig = mpl.plt.figure(figsize=(10, 5)) # 1D plot mpl.subplot(121) mpl.plot(f0[tL:tR]["y=0"], marker="^") mpl.plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist()) # 2D plot mpl.subplot(122) mpl.plot(f0, x=(t[0], t[-1])) mpl.plt.suptitle("datetime64") mpl.auto_adjust_subplots(subplot_params=dict(top=0.9)) mpl.plt.savefig(next_plot_fname(__file__)) if args.show: mpl.show() mpl.plt.close(fig) ### plots with a timedelta64 axis tL = tL - t[0] tR = tR - t[0] t = t - t[0] f0 = viscid.ones([t, y], crd_names="ty", center="node") T, Y = f0.get_crds(shaped=True) f0.data += np.arange(T.size).reshape(T.shape) f0.data += np.cos(Y) fig = mpl.plt.figure(figsize=(10, 5)) # 1D plot mpl.subplot(121) mpl.plot(f0[tL:tR]["y=0"], marker="^") mpl.plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist()) # 2D plot mpl.subplot(122) mpl.plot(f0, x=(t[0], t[-1]), y=(y[0], y[-1])) mpl.plt.suptitle("timedelta64") mpl.auto_adjust_subplots(subplot_params=dict(top=0.9)) mpl.plt.savefig(next_plot_fname(__file__)) if args.show: mpl.show() mpl.plt.close(fig) return 0
def run_test_3d(f, main__file__, show=False): mpl.clf() slc = "x=-20f:12f, y=0f" plot_kwargs = dict(title=True, earth=True) mpl.subplot(141) mpl.plot(f['pp'], slc, logscale=True, **plot_kwargs) mpl.subplot(142) mpl.plot(viscid.magnitude(f['bcc']), slc, logscale=True, **plot_kwargs) mpl.plot2d_quiver(f['v'][slc], step=5, color='y', pivot='mid', width=0.03, scale=600) mpl.subplot(143) mpl.plot(f['jy'], slc, clim=(-0.005, 0.005), **plot_kwargs) mpl.streamplot(f['v'][slc], linewidth=0.3) mpl.subplot(144) mpl.plot(f['jy'], "x=7f:12f, y=0f, z=0f") mpl.plt.suptitle("3D File") mpl.auto_adjust_subplots(subplot_params=dict(top=0.9, wspace=1.3)) mpl.plt.gcf().set_size_inches(10, 4) mpl.savefig(next_plot_fname(main__file__)) if show: mpl.show()
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) ####### test binary files f_bin = viscid.load_file(sample_dir + '/ath_sample.*.bin') for i, grid in enumerate(f_bin.iter_times(":")): plt.subplot2grid((2, 2), (0, i)) mpl.plot(grid['bx']) plt.subplot2grid((2, 2), (1, i)) mpl.plot(grid['by']) mpl.plt.suptitle("athena bin (binary) files") mpl.auto_adjust_subplots(subplot_params=dict(top=0.9)) mpl.plt.savefig(next_plot_fname(__file__)) if args.show: mpl.show() plt.clf() ####### test ascii files f_tab = viscid.load_file(sample_dir + '/ath_sample.*.tab') for i, grid in enumerate(f_tab.iter_times(":")): plt.subplot2grid((2, 2), (0, i)) mpl.plot(grid['bx']) plt.subplot2grid((2, 2), (1, i)) mpl.plot(grid['by']) mpl.plt.suptitle("athena tab (ascii) files") mpl.auto_adjust_subplots(subplot_params=dict(top=0.9)) mpl.plt.savefig(next_plot_fname(__file__)) if args.show: mpl.show() plt.clf()
def _do_multiplot(tind, grid, plot_vars=None, global_popts=None, kwopts=None, share_axes=False, show=False, subplot_params=None, first_run_result=None, first_run=False, **kwargs): import matplotlib.pyplot as plt from viscid.plot import mpl logger.info("Plotting timestep: %d, %g", tind, grid.time) if plot_vars is None: raise ValueError("No plot_vars given to vlab._do_multiplot :(") if kwargs: logger.info("Unused kwargs: {0}".format(kwargs)) if kwopts is None: kwopts = {} transpose = kwopts.get("transpose", False) plot_size = kwopts.get("plot_size", None) dpi = kwopts.get("dpi", None) out_prefix = kwopts.get("out_prefix", None) out_format = kwopts.get("out_format", "png") selection = kwopts.get("selection", None) timeformat = kwopts.get("timeformat", ".02f") tighten = kwopts.get("tighten", False) # wicked hacky # subplot_params = kwopts.get("subplot_params", _subplot_params) # nrows = len(plot_vars) nrows = len([pv[0] for pv in plot_vars if not pv[0].startswith('^')]) ncols = 1 if transpose: nrows, ncols = ncols, nrows if nrows == 0: logger.warn("I have no variables to plot") return fig = plt.gcf() if plot_size is not None: fig.set_size_inches(*plot_size, forward=True) if dpi is not None: fig.set_dpi(dpi) shareax = None this_row = -1 for i, fld_meta in enumerate(plot_vars): if not fld_meta[0].startswith('^'): this_row += 1 same_axis = False else: same_axis = True fld_name_meta = fld_meta[0].lstrip('^') fld_name_split = fld_name_meta.split(',') if '=' in fld_name_split[0]: # if fld_name is actually an equation, assume # there's no slice, and commas are part of the # equation fld_name = ",".join(fld_name_split) fld_slc = "" else: fld_name = fld_name_split[0] fld_slc = ",".join(fld_name_split[1:]) if selection is not None: # fld_slc += ",{0}".format(selection) if fld_slc != "": fld_slc = ",".join([fld_slc, selection]) else: fld_slc = selection if fld_slc.strip() == "": fld_slc = None # print("fld_time:", fld.time) if this_row < 0: raise ValueError("first plot can't begin with a +") row = this_row col = 0 if transpose: row, col = col, row if not same_axis: ax = plt.subplot2grid((nrows, ncols), (row, col), sharex=shareax, sharey=shareax) if i == 0 and share_axes: shareax = ax if not "plot_opts" in fld_meta[1]: fld_meta[1]["plot_opts"] = global_popts elif global_popts is not None: fld_meta[1]["plot_opts"] = "{0},{1}".format( fld_meta[1]["plot_opts"], global_popts) with grid.get_field(fld_name, slc=fld_slc) as fld: mpl.plot(fld, masknan=True, **fld_meta[1]) # print("fld cache", grid[fld_meta[0]]._cache) if timeformat and timeformat.lower() != "none": plt.suptitle(grid.format_time(timeformat)) # for adjusting subplots / tight_layout and applying the various # hacks to keep plots from dancing around in movies if not subplot_params and first_run_result: subplot_params = first_run_result if tighten: tighten = dict(rect=[0, 0.03, 1, 0.90]) ret = mpl.auto_adjust_subplots(tight_layout=tighten, subplot_params=subplot_params) if not first_run: ret = None if out_prefix: plt.savefig("{0}_{1:06d}.{2}".format(out_prefix, tind + 1, out_format)) if show: plt.show() plt.clf() return ret
def main(): parser = argparse.ArgumentParser(description="Test grad") parser.add_argument("--prof", action="store_true") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) b = viscid.make_dipole(l=(-5, -5, -5), h=(5, 5, 5), n=(256, 256, 128), m=(0, 0, -1)) b2 = np.sum(b * b, axis=b.nr_comp) if args.prof: print("Without boundaries") viscid.timeit(viscid.grad, b2, bnd=False, timeit_repeat=10, timeit_print_stats=True) print("With boundaries") viscid.timeit(viscid.grad, b2, bnd=True, timeit_repeat=10, timeit_print_stats=True) grad_b2 = viscid.grad(b2) grad_b2.pretty_name = r"$\nabla$ B$^2$" conv = viscid.convective_deriv(b) conv.pretty_name = r"(B $\cdot \nabla$) B" _ = mpl.plt.figure(figsize=(9, 4.2)) ax1 = mpl.subplot(231) mpl.plot(b2['z=0f'], logscale=True) mpl.plot(b2['z=0f'], logscale=True, style='contour', levels=10, colors='grey') # mpl.plot2d_quiver(viscid.normalize(b['z=0f']), step=16, pivot='mid') ax2 = mpl.subplot(234) mpl.plot(b2['y=0f'], logscale=True) mpl.plot(b2['y=0f'], logscale=True, style='contour', levels=10, colors='grey') mpl.plot2d_quiver(viscid.normalize(b['y=0f'], preferred='numpy'), step=16, pivot='mid') mpl.subplot(232, sharex=ax1, sharey=ax1) mpl.plot(1e-4 + viscid.magnitude(grad_b2['z=0f']), logscale=True) mpl.plot(1e-4 + viscid.magnitude(grad_b2['z=0f']), logscale=True, style='contour', levels=10, colors='grey') mpl.plot2d_quiver(viscid.normalize(grad_b2['z=0f']), step=16, pivot='mid') mpl.subplot(235, sharex=ax2, sharey=ax2) mpl.plot(1e-4 + viscid.magnitude(grad_b2['y=0f']), logscale=True) mpl.plot(1e-4 + viscid.magnitude(grad_b2['y=0f']), logscale=True, style='contour', levels=10, colors='grey') mpl.plot2d_quiver(viscid.normalize(grad_b2['y=0f']), step=16, pivot='mid') mpl.subplot(233, sharex=ax1, sharey=ax1) mpl.plot(viscid.magnitude(conv['z=0f']), logscale=True) mpl.plot(viscid.magnitude(conv['z=0f']), logscale=True, style='contour', levels=10, colors='grey') mpl.plot2d_quiver(viscid.normalize(conv['z=0f']), step=16, pivot='mid') mpl.subplot(236, sharex=ax2, sharey=ax2) mpl.plot(viscid.magnitude(conv['y=0f']), logscale=True) mpl.plot(viscid.magnitude(conv['y=0f']), logscale=True, style='contour', levels=10, colors='grey') mpl.plot2d_quiver(viscid.normalize(conv['y=0f']), step=16, pivot='mid') mpl.auto_adjust_subplots() mpl.plt.savefig(next_plot_fname(__file__)) if args.show: mpl.show()