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) _, axes = plt.subplots(4, 1, squeeze=False) vlt.plot(fld_s, "y=20j", ax=axes[0, 0], show=False, plot_opts="lin_0") vlt.plot(fld_s, "x=0j:20j,y=0j:5j", ax=axes[1, 0], earth=True, show=False, plot_opts="x_-10_0,y_0_7") vlt.plot(fld_s, "y=0j", ax=axes[2, 0], show=False, plot_opts="lin_-1_1") vlt.plot(fld_s, "z=0j,x=-20j:0j", ax=axes[3, 0], earth=True, show=False, plot_opts="lin_-5_5") plt.suptitle("2d cell centered") vlt.auto_adjust_subplots() plt.savefig(next_plot_fname(__file__)) if show: vlt.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_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_div_test(fld, exact, show=False, ignore_inexact=False): t0 = time() result_numexpr = viscid.div(fld, preferred="numexpr", only=True) t1 = time() logger.info("numexpr magnitude runtime: %g", t1 - t0) result_diff = viscid.diff(result_numexpr, exact[1:-1, 1:-1, 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) if show: mpl.mplshow()
def main(): parser = argparse.ArgumentParser(description="Test divergence") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) dtype = 'float64' # use 512 512 256 to inspect memory related things x = np.array(np.linspace(-0.5, 0.5, 256), dtype=dtype) y = np.array(np.linspace(-0.5, 0.5, 256), dtype=dtype) z = np.array(np.linspace(-0.5, 0.5, 64), dtype=dtype) v = viscid.empty([x, y, z], name="V", nr_comps=3, center="cell", layout="interlaced") exact_cc = viscid.empty([x, y, z], name="exact_cc", center='cell') Xcc, Ycc, Zcc = exact_cc.get_crds_cc(shaped=True) #pylint: disable=W0612 v['x'] = ne.evaluate("(sin(Xcc))") # + Zcc v['y'] = ne.evaluate("(cos(Ycc))") # + Xcc# + Zcc v['z'] = ne.evaluate("-((sin(Zcc)))") # + Xcc# + Ycc exact_cc[:, :, :] = ne.evaluate("cos(Xcc) - sin(Ycc) - cos(Zcc)") logger.info("node centered tests") v_nc = v.as_centered('node') exact_nc = viscid.empty_like(v_nc['x']) X, Y, Z = exact_nc.get_crds_nc(shaped=True) #pylint: disable=W0612 exact_nc[:, :, :] = ne.evaluate("cos(X) - sin(Y) - cos(Z)") # FIXME: why is the error so much larger here? run_div_test(v_nc, exact_nc, show=args.show, ignore_inexact=True) logger.info("cell centered tests") v_cc = v_nc.as_centered('cell') run_div_test(v_cc, exact_cc, show=args.show)
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) _, axes = plt.subplots(nrows, ncols, sharex=True, sharey=True, squeeze=False) for ind, p in enumerate(planes): vlt.plot(vx, p, ax=axes[0, ind], show=False) vlt.plot(vy, p, ax=axes[1, ind], show=False) vlt.plot(vz, p, ax=axes[2, ind], show=False) vlt.plot(mag_ne, p, ax=axes[3, ind], show=False) plt.suptitle(title) vlt.auto_adjust_subplots(subplot_params=dict(top=0.9, right=0.9)) plt.gcf().set_size_inches(6, 7) plt.savefig(next_plot_fname(__file__)) if show: vlt.mplshow()
def run_mag_test(fld, show=False): vx, vy, vz = fld.component_views() #pylint: disable=W0612 vx, vy, vz = fld.component_fields() t0 = time() mag_ne = viscid.magnitude(fld, preferred="numexpr", only=True) t1 = time() logger.info("numexpr mag runtime: %g", t1 - t0) t0 = time() 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) if show: mpl.mplshow()
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) _, axes = plt.subplots(4, 1, squeeze=False) vlt.plot(fld_s, "z=0,x=:30", ax=axes[0, 0], earth=True, plot_opts="lin_0") vlt.plot(fld_s, "z=0.75j,x=-4:-1,y=-3j:3j", ax=axes[1, 0], earth=True) vlt.plot(fld_s, "x=-0.5j:,y=-3j:3j,z=0j", ax=axes[2, 0], earth=True) vlt.plot(fld_s, "x=0.0j,y=-5.0j:5.0j", ax=axes[3, 0], earth=True, plot_opts="log,g") plt.suptitle("3d node centered") vlt.auto_adjust_subplots() plt.savefig(next_plot_fname(__file__)) if show: vlt.mplshow()
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)) vlt.plot(fld_s, "z=0,x=:30", earth=True, plot_opts="lin_0") plt.subplot2grid((nrows, ncols), (1, 0)) vlt.plot(fld_s, "z=0.75f,x=-4:-1,y=-3f:3f", earth=True) plt.subplot2grid((nrows, ncols), (2, 0)) vlt.plot(fld_s, "x=-0.5f:,y=-3f:3f,z=0f", earth=True) plt.subplot2grid((nrows, ncols), (3, 0)) vlt.plot(fld_s, "x=0.0f,y=-5.0f:5.0f", earth=True, plot_opts="log,g") plt.suptitle("3d node centered") vlt.auto_adjust_subplots() plt.savefig(next_plot_fname(__file__)) if show: vlt.mplshow()
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) dtype = 'float32' x = np.array(np.linspace(-5, 5, 512), dtype=dtype) y = np.array(np.linspace(-5, 5, 256), dtype=dtype) z = np.array(np.linspace(-5, 5, 256), dtype=dtype) v = viscid.empty([x, y, z], name="V", nr_comps=3, center='node', layout='interlaced') X, Y, Z = v.get_crds_nc(shaped=True) v['x'] = (0.5 * X**2) + ( Y ) + (0.0 * Z ) v['y'] = (0.0 * X ) + (0.5 * Y**2) + (0.0 * Z ) v['z'] = (0.0 * X ) + (0.0 * Y ) + (0.5 * Z**2) logger.info("Testing node centered magnitudes") run_mag_test(v, title="node centered", show=args.show) logger.info("Testing cell centered magnitudes") v = v.as_centered('cell') run_mag_test(v, title="cell centered", show=args.show) # print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024**2) # print("ne: ", timereps(10, Div1ne, [vx, vy, vz])) # print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024**2) # print("inline: ", timereps(10, Div1inline, [vx, vy, vz])) # print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024**2) return 0
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.warning("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=0j", "z=0j"] nrows = 2 ncols = len(planes) _, axes = plt.subplots(nrows, ncols, squeeze=False) for i, p in enumerate(planes): vlt.plot(result_numexpr, p, ax=axes[0, i], show=False) vlt.plot(result_diff, p, ax=axes[1, i], show=False) plt.suptitle(title) vlt.auto_adjust_subplots(subplot_params=dict(top=0.9)) plt.savefig(next_plot_fname(__file__)) if show: vlt.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=__doc__) parser.add_argument("--prof", action="store_true") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) dtype = 'float64' # use 512 512 256 to inspect memory related things x = np.array(np.linspace(-0.5, 0.5, 256), dtype=dtype) y = np.array(np.linspace(-0.5, 0.5, 256), dtype=dtype) z = np.array(np.linspace(-0.5, 0.5, 64), dtype=dtype) v = viscid.empty([x, y, z], name="V", nr_comps=3, center="cell", layout="interlaced") exact_cc = viscid.empty([x, y, z], name="exact_cc", center='cell') Xcc, Ycc, Zcc = exact_cc.get_crds_cc(shaped=True) # pylint: disable=W0612 if HAS_NUMEXPR: v['x'] = ne.evaluate("(sin(Xcc))") # + Zcc v['y'] = ne.evaluate("(cos(Ycc))") # + Xcc# + Zcc v['z'] = ne.evaluate("-((sin(Zcc)))") # + Xcc# + Ycc exact_cc[:, :, :] = ne.evaluate("cos(Xcc) - sin(Ycc) - cos(Zcc)") else: v['x'] = (np.sin(Xcc)) # + Zcc v['y'] = (np.cos(Ycc)) # + Xcc# + Zcc v['z'] = -((np.sin(Zcc))) # + Xcc# + Ycc exact_cc[:, :, :] = np.cos(Xcc) - np.sin(Ycc) - np.cos(Zcc) if args.prof: print("Without boundaries") viscid.timeit(viscid.div, v, bnd=False, timeit_repeat=10, timeit_print_stats=True) print("With boundaries") viscid.timeit(viscid.div, v, bnd=True, timeit_repeat=10, timeit_print_stats=True) logger.info("node centered tests") v_nc = v.as_centered('node') exact_nc = viscid.empty_like(v_nc['x']) X, Y, Z = exact_nc.get_crds_nc(shaped=True) # pylint: disable=W0612 if HAS_NUMEXPR: exact_nc[:, :, :] = ne.evaluate("cos(X) - sin(Y) - cos(Z)") else: exact_nc[:, :, :] = np.cos(X) - np.sin(Y) - np.cos(Z) # FIXME: why is the error so much larger here? run_div_test(v_nc, exact_nc, title='Node Centered', show=args.show, ignore_inexact=True) logger.info("cell centered tests") v_cc = v_nc.as_centered('cell') run_div_test(v_cc, exact_cc, title="Cell Centered", show=args.show) return 0
def make_grid1_cax(ax, position='right', orientation='horizontal', aspect=20.0, fraction=0.05, pad=0.05, shrink=1.0): # validate position && orientation if orientation == 'vertical': if position not in ('left', 'right'): raise ValueError("bad position '{0}'".format(position)) elif orientation == 'horizontal': if position not in ('bottom', 'top'): raise ValueError("bad position '{0}'".format(position)) else: raise ValueError("bad orientation '{0}'".format(orientation)) cax = None try: # prepare axes size given orientation and axes type if isinstance(ax, mprojections.polar.PolarAxes): kls_x, kls_y = _PolarAxesX, _PolarAxesY elif type(ax) in (mprojections.axes.Axes, mprojections.axes.Subplot): # note this checks type, not isinstance because all axes derive # from axes.Axes, and that's not what we're checking here kls_x, kls_y = _AxesX, _AxesY else: raise _UnexpectedProjection(str(type(ax))) size_x = kls_x(ax, aspect=1.0 / aspect) size_y = kls_y(ax, aspect=1.0 / aspect) # scale the long side by shrink if orientation == 'vertical': size_y = axes_size.Fraction(1.0 / shrink, size_y) width = axes_size.Fraction(fraction, size_x) pad_size = axes_size.Fraction(pad, size_x) else: size_x = axes_size.Fraction(1.0 / shrink, size_x) width = axes_size.Fraction(fraction, size_y) pad_size = axes_size.Fraction(pad, size_y) divider = axes_divider.AxesDivider(ax, xref=size_x, yref=size_y) locator = divider.new_locator(nx=0, ny=0) ax.set_axes_locator(locator) cax = divider.append_axes(position, size=width, pad=pad_size, axes_class=matplotlib.axes.Axes) except _UnexpectedProjection as e: logger.info("Viscid can't verify that grid1 axes will " "work to colorbar a {0} axis; falling back to " "default.".format(e.ax_type)) return cax
def main(): parser = argparse.ArgumentParser(description="Load some data files") parser.add_argument('files', nargs="*", help='input files') args = vutil.common_argparse(parser) # print("args", args) # logger.error(args) # logger.warn(args) logger.info("args: {0}".format(args)) # logger.debug(args) print() files = readers.load_files(args.files) readers.__filebucket__.print_tree() print() for f in files: f.print_tree(depth=-1)
def main(): parser = argparse.ArgumentParser(description="Test calc") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) dtype = 'float32' x = np.array(np.linspace(-5, 5, 512), dtype=dtype) y = np.array(np.linspace(-5, 5, 256), dtype=dtype) z = np.array(np.linspace(-5, 5, 256), dtype=dtype) v = viscid.empty([x, y, z], name="V", nr_comps=3, center='node', layout='interlaced') X, Y, Z = v.get_crds_nc(shaped=True) v['x'] = 0.5 * X**2 + Y + 0.0 * Z v['y'] = 0.0 * X + 0.5 * Y**2 + 0.0 * Z v['z'] = 0.0 * X + 0.0 * Y + 0.5 * Z**2 logger.info("Testing node centered magnitudes") run_mag_test(v, show=args.show) logger.info("Testing cell centered magnitudes") v = v.as_centered('cell') run_mag_test(v, show=args.show)
def _get_imp(self, preferred, only=False): if not isinstance(preferred, (list, tuple)): if preferred is None: preferred = list(self._imps.keys()) else: preferred = [preferred] for name in preferred: if name in self._imps: return self._imps[name] msg = "{0} :: {1}".format(self.opname, preferred) if only: raise verror.BackendNotFound(msg) logger.info("No preferred backends available: " + msg) for name in self.default_backends: if name in self._imps: return self._imps[name] if len(self._imps) == 0: raise verror.BackendNotFound("No backends available") return list(self._imps.values())[0]
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)) vlt.plot(fld_s, "y=20f", show=False, plot_opts="lin_0") plt.subplot2grid((nrows, ncols), (1, 0)) vlt.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)) vlt.plot(fld_s, "y=0f", show=False, plot_opts="lin_-1_1") plt.subplot2grid((nrows, ncols), (3, 0)) vlt.plot(fld_s, "z=0f,x=-20f:0f", earth=True, show=False, plot_opts="lin_-5_5") plt.suptitle("2d cell centered") vlt.auto_adjust_subplots() plt.savefig(next_plot_fname(__file__)) if show: vlt.mplshow()
def main(): parser = argparse.ArgumentParser(description="Streamline a PSC file") parser.add_argument("-t", default="2000", help="which time to plot (finds closest)") parser.add_argument('infile', nargs=1, help='input file') args = vutil.common_argparse(parser) # f = readers.load_file("pfd.020000.xdmf") # ... or ... # using this way of loading files, one probably wants just to give # pfd.xdmf to the command line f = readers.load_file(args.infile[0]) f.activate_time(args.t) jz = f["jz"] # recreate hx as a field of 0 to keep streamlines from moving in # that direction hx = field.zeros_like(jz, name="hx") h1 = field.scalar_fields_to_vector([hx, f["hy"], f["hz"]], name="H", _force_layout="Interlaced", forget_source=True) e = field.scalar_fields_to_vector([f["ex"], f["ey"], f["ez"]], name="E", _force_layout="Interlaced", forget_source=True) # plot magnetic fields, just a sanity check # ax1 = plt.subplot(211) # mpl.plot(f["hy"], flip_plot=True) # ax2 = plt.subplot(212, sharex=ax1, sharey=ax1) # mpl.plot(f["hz"], flip_plot=True) # mpl.mplshow() # make a line of 30 seeds straight along the z axis (x, y, z ordered) seeds1 = seed.Line((0.0, 0.0, 2.0), (1022.0, 0.0, 0.0), 60) # set outer boundary limits for streamlines ds = 0.005 # spatial step along the stream line curve obound0 = np.array([1, -128, -1000], dtype=h1.dtype) obound1 = np.array([1023, 128, 1000], dtype=h1.dtype) # calc the streamlines lines1, topo1 = streamline.streamlines(h1, seeds1, ds0=ds, maxit=200000, obound0=obound0, obound1=obound1, ibound=0.0) # run with -v to see this logger.info("Topology flags: {0}".format(topo1)) # rotate plot puts the z axis along the horizontal flip_plot = True mpl.plot(jz, flip_plot=flip_plot, plot_opts="lin_-.05_.05") # mpl.plot_streamlines2d(lines1, "x", flip_plot=flip_plot, color='k') plt.xlim([0, 1024]) plt.ylim([-128, 128]) plt.show() # interpolate e onto each point of the first field line of lines1 e1 = cycalc.interp_trilin(e, seed.Point(lines1[0])) print(e1.shape, lines1[0].shape) plt.clf() plt.plot(np.linspace(0, ds * e1.shape[0], e1.shape[0]), e1[:, 0]) plt.xlabel("length along field line") plt.ylabel("Ex") plt.show() return 0
def _follow_fluid_step(i, dt, grid, root_seeds, plot_function, stream_opts, speed_scale): direction = int(dt / np.abs(dt)) if direction >= 0: sl_direction = streamline.DIR_FORWARD else: sl_direction = streamline.DIR_BACKWARD logger.info("working on timestep {0} {1}".format(i, grid.time)) v = grid["v"] logger.debug("finished reading V field") logger.debug("calculating new streamline positions") flow_lines = calc_streamlines(v, root_seeds, output=viscid.OUTPUT_STREAMLINES, stream_dir=sl_direction, **stream_opts)[0] logger.debug("done with that, now i'm plotting...") plot_function(i, grid, v, flow_lines, root_seeds) ############################################################ # now recalculate the seed positions for the next timestep logger.debug("finding new seed positions...") root_pts = root_seeds.genr_points() valid_pt_inds = [] for i in range(root_pts.shape[1]): valid_pt = True # get the index of the root point in teh 2d flow line array # dist = flow_lines[i] - root_pts[:, [i]] # root_ind = np.argmin(np.sum(dist**2, axis=0)) # print("!!!", root_pts[:, i], "==", flow_lines[i][:, root_ind]) # interpolate velocity onto teh flow line, and get speed too v_interp = cycalc.interp_trilin(v, seed.Point(flow_lines[i])) speed = np.sqrt(np.sum(v_interp * v_interp, axis=1)) # this is a super slopy way to integrate velocity # keep marching along the flow line until we get to the next timestep t = 0.0 ind = 0 if direction < 0: flow_lines[i] = flow_lines[i][:, ::-1] speed = speed[::-1] while t < np.abs(dt): ind += 1 if ind >= len(speed): # set valid_pt to True if you want to keep that point for # future time steps, but most likely if we're here, the seed # has gone out of our region of interest ind = len(speed) - 1 valid_pt = False logger.info("OOPS: ran out of streamline, increase " "max_length when tracing flow lines if this " "is unexpected") break t += stream_opts["ds0"] / (speed_scale * speed[ind]) root_pts[:, i] = flow_lines[i][:, ind] if valid_pt: valid_pt_inds.append(i) # remove seeds that have flown out of our region of interest # (aka, beyond the flow line we drew) root_pts = root_pts[:, valid_pt_inds] logger.debug("ok, done with all that :)") return root_pts
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 vpyplot as vlt logger.info("Plotting timestep: %d, %g", tind, grid.time) if plot_vars is None: raise ValueError("No plot_vars given to `_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 "plot_opts" not 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: vlt.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 = vlt.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 _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