def guess_dipole_moment(b, r=2.0, strength=DEFAULT_STRENGTH, cap_angle=40, cap_ntheta=121, cap_nphi=121, plot=False): """guess dipole moment from a B field""" viscid.logger.warning("guess_dipole_moment doesn't seem to do better than " "1.6 degrees, you may want to use cotr instead.") cap = seed.SphericalCap(r=r, angle=cap_angle, ntheta=cap_ntheta, nphi=cap_nphi) b_cap = interp_trilin(b, cap) # FIXME: this doesn't get closer than 1.6 deg @ (theta, mu) = (0, 7.5) # so maybe the index is incorrect somehow? idx = np.argmax(viscid.magnitude(b_cap).data) pole = cap.points()[:, idx] # FIXME: it should be achievabe to get strength from the magimum magnitude, # up to the direction pole = strength * pole / np.linalg.norm(pole) # # not sure where 0.133 comes from, this is probably not correct # pole *= 0.133 * np.dot(pole, b_cap.data.reshape(-1, 3)[idx, :]) * r**3 if plot: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt vlt.plot(viscid.magnitude(b_cap)) vlt.plot(viscid.magnitude(b_cap), style='contour', levels=10, colors='k', colorbar=False, ax=plt.gca()) vlt.show() return pole
def main(): f = viscid.load_file("~/dev/work/tmedium/*.3d.[-1].xdmf") grid = f.get_grid() gslc = "x=-26f:12.5f, y=-15f:15f, z=-15f:15f" # gslc = "x=-12.5f:26f, y=-15f:15f, z=-15f:15f" b_cc = f['b_cc'][gslc] b_cc.name = "b_cc" b_fc = f['b_fc'][gslc] b_fc.name = "b_fc" e_cc = f['e_cc'][gslc] e_cc.name = "e_cc" e_ec = f['e_ec'][gslc] e_ec.name = "e_ec" pp = f['pp'][gslc] pp.name = 'pp' pargs = dict(logscale=True, earth=True) # mpl.clf() # ax1 = mpl.subplot(211) # mpl.plot(f['pp']['y=0f'], **pargs) # # mpl.plot(viscid.magnitude(f['b_cc']['y=0f']), **pargs) # # mpl.show() # mpl.subplot(212, sharex=ax1, sharey=ax1) # mpl.plot(viscid.magnitude(viscid.fc2cc(f['b_fc'])['y=0f']), **pargs) # mpl.show() basename = './tmediumR.3d.{0:06d}'.format(int(grid.time)) viscid.save_fields(basename + '.h5', [b_cc, b_fc, e_cc, e_ec, pp]) f2 = viscid.load_file(basename + ".xdmf") pargs = dict(logscale=True, earth=True) mpl.clf() ax1 = mpl.subplot(211) mpl.plot(f2['pp']['y=0f'], style='contour', levels=5, colorbar=None, colors='k', **pargs) mpl.plot(viscid.magnitude(f2['b_cc']['y=0f']), **pargs) mpl.subplot(212, sharex=ax1, sharey=ax1) mpl.plot(viscid.magnitude(viscid.fc2cc(f2['b_fc'])['y=0f']), **pargs) mpl.show() os.remove(basename + '.h5') os.remove(basename + '.xdmf') return 0
def main(): f = viscid.load_file("~/dev/work/tmedium/*.3d.[-1].xdmf") grid = f.get_grid() gslc = "x=-26f:12.5f, y=-15f:15f, z=-15f:15f" # gslc = "x=-12.5f:26f, y=-15f:15f, z=-15f:15f" b_cc = f['b_cc'][gslc] b_cc.name = "b_cc" b_fc = f['b_fc'][gslc] b_fc.name = "b_fc" e_cc = f['e_cc'][gslc] e_cc.name = "e_cc" e_ec = f['e_ec'][gslc] e_ec.name = "e_ec" pp = f['pp'][gslc] pp.name = 'pp' pargs = dict(logscale=True, earth=True) # vlt.clf() # ax1 = vlt.subplot(211) # vlt.plot(f['pp']['y=0f'], **pargs) # # vlt.plot(viscid.magnitude(f['b_cc']['y=0f']), **pargs) # # vlt.show() # vlt.subplot(212, sharex=ax1, sharey=ax1) # vlt.plot(viscid.magnitude(viscid.fc2cc(f['b_fc'])['y=0f']), **pargs) # vlt.show() basename = './tmediumR.3d.{0:06d}'.format(int(grid.time)) viscid.save_fields(basename + '.h5', [b_cc, b_fc, e_cc, e_ec, pp]) f2 = viscid.load_file(basename + ".xdmf") pargs = dict(logscale=True, earth=True) vlt.clf() ax1 = vlt.subplot(211) vlt.plot(f2['pp']['y=0f'], style='contour', levels=5, colorbar=None, colors='k', **pargs) vlt.plot(viscid.magnitude(f2['b_cc']['y=0f']), **pargs) vlt.subplot(212, sharex=ax1, sharey=ax1) vlt.plot(viscid.magnitude(viscid.fc2cc(f2['b_fc'])['y=0f']), **pargs) vlt.show() os.remove(basename + '.h5') os.remove(basename + '.xdmf') return 0
def compare_vectors(orig_fld, cmp_fld, catol=1e-8, rtol=2e-6, trim_slc='x=2:-2, y=2:-2, z=2:-2', make_plots=False): # mag_shape = list(orig_fld.sshape) + [1] mag = viscid.magnitude(orig_fld) # .data.reshape(mag_shape) reldiff = (cmp_fld - orig_fld) / mag reldiff = reldiff[trim_slc] reldiff.name = cmp_fld.name + " - " + orig_fld.name reldiff.pretty_name = cmp_fld.pretty_name + " - " + orig_fld.pretty_name comp_beyond_limit = [False] * 3 for i, d in enumerate('xyz'): abs_max_rel_diff = np.nanmax(np.abs(reldiff[d])) max_crd_diff = np.max(orig_fld.get_crd(d) - cmp_fld.get_crd(d)) print("{0}{1}, max absolute relative diff: {2:.3e} ({1} crds: {3:.1e})" "".format(cmp_fld.name, d, abs_max_rel_diff, max_crd_diff)) if abs_max_rel_diff > rtol or abs(max_crd_diff) > catol: comp_beyond_limit[i] = True # plot differences? if make_plots: plt.clf() ax1 = plt.subplot(311) vlt.plot(orig_fld[d]['y=0j'], symmetric=True, earth=True) plt.subplot(312, sharex=ax1, sharey=ax1) vlt.plot(cmp_fld[d]['y=0j'], symmetric=True, earth=True) plt.subplot(313, sharex=ax1, sharey=ax1) vlt.plot(reldiff[d]['y=0j'], symmetric=True, earth=True) vlt.show()
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_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_test_2d(f, main__file__, show=False): vlt.clf() slc = "x=-20j:12j, y=0j" plot_kwargs = dict(title=True, earth=True) vlt.subplot(141) vlt.plot(f['pp'], slc, logscale=True, **plot_kwargs) vlt.plot(np.abs(f['psi']), style='contour', logscale=True, levels=30, linewidths=0.8, colors='grey', linestyles='solid', colorbar=None, x=(-20, 12)) vlt.subplot(142) vlt.plot(viscid.magnitude(f['bcc']), slc, logscale=True, **plot_kwargs) vlt.plot2d_quiver(f['v'][slc], step=5, color='y', pivot='mid', width=0.03, scale=600) vlt.subplot(143) vlt.plot(f['jy'], slc, clim=[-0.005, 0.005], **plot_kwargs) vlt.streamplot(f['v'][slc], linewidth=0.3) vlt.subplot(144) vlt.plot(f['jy'], "x=7j:12j, y=0j, z=0j") plt.suptitle("2D File") vlt.auto_adjust_subplots(subplot_params=dict(top=0.9, wspace=1.3)) plt.gcf().set_size_inches(10, 4) vlt.savefig(next_plot_fname(main__file__)) if show: vlt.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 compare_vectors(cc_fld, ecfc_fld, to_cc_fn, catol=1e-8, rtol=2.2e-6, trim_slc=':', bnd=True, make_plots=False): trimmed = cc_fld[trim_slc] cc = to_cc_fn(ecfc_fld, bnd=bnd) reldiff = (cc - trimmed) / viscid.magnitude(trimmed) reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"] reldiff.name = cc.name + " - " + trimmed.name reldiff.pretty_name = cc.pretty_name + " - " + trimmed.pretty_name comp_beyond_limit = [False] * 3 for i, d in enumerate('xyz'): abs_max_rel_diff = np.nanmax(np.abs(reldiff[d])) # trim first and last when diffing crds since they're extrapolated # in the ecfc field, so we already know they won't match up do dx max_crd_diff = np.max((trimmed.get_crd(d) - cc.get_crd(d))[1:-1]) print("{0}{1}, max absolute relative diff: {2:.3e} ({1} crds: {3:.1e})" "".format(cc_fld.name, d, abs_max_rel_diff, max_crd_diff)) if abs_max_rel_diff > rtol or abs(max_crd_diff) > catol: comp_beyond_limit[i] = True # plot differences? if make_plots: ax1 = plt.subplot(311) vlt.plot(cc_fld[d]['y=0j'], symmetric=True, earth=True) plt.subplot(312, sharex=ax1, sharey=ax1) vlt.plot(cc[d]['y=0j'], symmetric=True, earth=True) plt.subplot(313, sharex=ax1, sharey=ax1) vlt.plot(reldiff[d]['y=0j'], symmetric=True, earth=True) vlt.show() if any(comp_beyond_limit): raise RuntimeError("Tolerance exceeded on ->CC accuracy")
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 default_fluid_callback(i, t, seeds=None, v_field=None, anc_fields=None, grid0=None, grid1=None, streamlines=None, series_fname=None, show=False, **kwargs): from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt _, ax0 = plt.subplots(1, 1) vlt.plot(viscid.magnitude(v_field).atmost_nd(2), ax=ax0) vlt.scatter_2d(seeds, ax=ax0) vlt.streamplot(v_field.atmost_nd(2)) vlt.plot_lines2d(streamlines, ax=ax0) plt.title('{0:8.3f}'.format(t)) if series_fname: plt.savefig('{0}_{1:06d}.png'.format(series_fname, i)) if show: vlt.show() else: plt.close()
def run_test_3d(f, main__file__, show=False): vlt.clf() slc = "x=-20f:12f, y=0f" plot_kwargs = dict(title=True, earth=True) vlt.subplot(141) vlt.plot(f['pp'], slc, logscale=True, **plot_kwargs) vlt.subplot(142) vlt.plot(viscid.magnitude(f['bcc']), slc, logscale=True, **plot_kwargs) vlt.plot2d_quiver(f['v'][slc], step=5, color='y', pivot='mid', width=0.03, scale=600) vlt.subplot(143) vlt.plot(f['jy'], slc, clim=(-0.005, 0.005), **plot_kwargs) vlt.streamplot(f['v'][slc], linewidth=0.3) vlt.subplot(144) vlt.plot(f['jy'], "x=7f:12f, y=0f, z=0f") plt.suptitle("3D File") vlt.auto_adjust_subplots(subplot_params=dict(top=0.9, wspace=1.3)) plt.gcf().set_size_inches(10, 4) vlt.savefig(next_plot_fname(main__file__)) if show: vlt.show()
def compare_vectors(cc_fld, ecfc_fld, to_cc_fn, catol=1e-8, rtol=2.2e-6, trim_slc='x=1:-1, y=1:-1, z=1:-1', make_plots=False): trimmed = cc_fld[trim_slc] cc = to_cc_fn(ecfc_fld) reldiff = (cc - trimmed) / viscid.magnitude(trimmed) reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"] reldiff.name = cc.name + " - " + trimmed.name reldiff.pretty_name = cc.pretty_name + " - " + trimmed.pretty_name comp_beyond_limit = [False] * 3 for i, d in enumerate('xyz'): abs_max_rel_diff = np.nanmax(np.abs(reldiff[d])) max_crd_diff = np.max(trimmed.get_crd(d) - cc.get_crd(d)) print("{0}{1}, max absolute relative diff: {2:.3e} ({1} crds: {3:.1e})" "".format(cc_fld.name, d, abs_max_rel_diff, max_crd_diff)) if abs_max_rel_diff > rtol or abs(max_crd_diff) > catol: comp_beyond_limit[i] = True # plot differences? if make_plots: ax1 = mpl.plt.subplot(311) mpl.plot(cc_fld[d]['y=0f'], symmetric=True, earth=True) mpl.plt.subplot(312, sharex=ax1, sharey=ax1) mpl.plot(cc[d]['y=0f'], symmetric=True, earth=True) mpl.plt.subplot(313, sharex=ax1, sharey=ax1) mpl.plot(reldiff[d]['y=0f'], symmetric=True, earth=True) mpl.show() if any(comp_beyond_limit): raise RuntimeError("Tolerance exceeded on ->CC accuracy")
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(-1, 1, 2), dtype=dtype) y = np.array(np.linspace(-2, 2, 30), dtype=dtype) z = np.array(np.linspace(-5, 5, 90), dtype=dtype) v = viscid.empty([x, y, z], nr_comps=3, name="V", center="cell", layout="interlaced") X, Y, Z = v.get_crds_cc(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 mag = viscid.magnitude(v) mag2 = np.sqrt(np.sum(v * v, axis=v.nr_comp)) another = np.transpose(mag) plt.subplot(151) mpl.plot(v["x"]) plt.subplot(152) mpl.plot(v["y"]) plt.subplot(153) mpl.plot(mag) plt.subplot(154) mpl.plot(mag2) plt.subplot(155) mpl.plot(another) if args.show: plt.show() return 0
def run_test(_fld, _seeds, plot2d=True, plot3d=True, title='', show=False, **kwargs): lines, topo = viscid.calc_streamlines(_fld, _seeds, **kwargs) topo_color = viscid.topology2color(topo) # downsample lines for plotting lines = [line[:, ::8] for line in lines] try: if not plot2d: raise ImportError from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() vlt.plot2d_lines(lines, scalars=topo_color, symdir='y', marker='^') if title: plt.title(title) plt.savefig(next_plot_fname(__file__, series='2d')) if show: plt.show() except ImportError: pass try: if not plot3d: raise ImportError from viscid.plot import vlab try: fig = _global_ns['figure'] vlab.clf() except KeyError: fig = vlab.figure(size=[1200, 800], offscreen=not show, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0)) _global_ns['figure'] = fig fld_mag = np.log(viscid.magnitude(_fld)) try: # note: mayavi.mlab.mesh can't take color tuples as scalars # so one can't use topo_color on a mesh surface. This # is a limitation of mayavi. To actually plot a specific # set of colors on a mesh, one must use a texture mesh = vlab.mesh_from_seeds(_seeds, scalars=topo, opacity=0.6) mesh.actor.property.backface_culling = True except RuntimeError: pass vlab.plot_lines(lines, scalars=fld_mag, tube_radius=0.01, cmap='viridis') if title: vlab.title(title) vlab.savefig(next_plot_fname(__file__, series='3d')) if show: vlab.show() except ImportError: pass
def run_test(_fld, _seeds, plot2d=True, plot3d=True, title="", show=False, **kwargs): lines, topo = viscid.calc_streamlines(_fld, _seeds, **kwargs) topo_color = viscid.topology2color(topo) # downsample lines for plotting lines = [line[:, ::8] for line in lines] try: if not plot2d: raise ImportError from viscid.plot import mpl mpl.plt.clf() mpl.plot2d_lines(lines, scalars=topo_color, symdir="y", marker="^") if title: mpl.plt.title(title) mpl.plt.savefig(next_plot_fname(__file__, series="2d")) if show: mpl.plt.show() except ImportError: pass try: if not plot3d: raise ImportError from viscid.plot import mvi try: fig = _global_ns["figure"] mvi.clf() except KeyError: fig = mvi.figure(size=[1200, 800], offscreen=not show) _global_ns["figure"] = fig fld_mag = np.log(viscid.magnitude(_fld)) try: # note: mayavi.mlab.mesh can't take color tuples as scalars # so one can't use topo_color on a mesh surface. This # is a limitation of mayavi. To actually plot a specific # set of colors on a mesh, one must use a texture mesh = mvi.mesh_from_seeds(_seeds, scalars=topo, opacity=0.6) mesh.actor.property.backface_culling = True except RuntimeError: pass mvi.plot_lines(lines, scalars=fld_mag, tube_radius=0.01, cmap="viridis") if title: mvi.title(title) mvi.savefig(next_plot_fname(__file__, series="3d")) if show: mvi.show() except ImportError: pass
def run_test(_fld, _seeds, plot2d=True, plot3d=True, title='', show=False, **kwargs): lines, topo = viscid.calc_streamlines(_fld, _seeds, **kwargs) topo_color = viscid.topology2color(topo) # downsample lines for plotting lines = [line[:, ::8] for line in lines] try: if not plot2d: raise ImportError from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() vlt.plot2d_lines(lines, scalars=topo_color, symdir='y', marker='^') if title: plt.title(title) plt.savefig(next_plot_fname(__file__, series='2d')) if show: plt.show() except ImportError: pass try: if not plot3d: raise ImportError vlab, _ = get_mvi_fig() fld_mag = np.log(viscid.magnitude(_fld)) try: # note: mayavi.mlab.mesh can't take color tuples as scalars # so one can't use topo_color on a mesh surface. This # is a limitation of mayavi. To actually plot a specific # set of colors on a mesh, one must use a texture mesh = vlab.mesh_from_seeds(_seeds, scalars=topo, opacity=0.6) mesh.actor.property.backface_culling = True except RuntimeError: pass vlab.plot_lines(lines, scalars=fld_mag, tube_radius=0.01, cmap='viridis') if title: vlab.title(title) vlab.savefig(next_plot_fname(__file__, series='3d')) if show: vlab.show() except ImportError: pass
def run_test(_fld, _seeds, plot2d=True, plot3d=True, show=False, **kwargs): lines, topo = viscid.calc_streamlines(_fld, _seeds, **kwargs) topo_fld = _seeds.wrap_field(topo) topo_color = viscid.topology2color(topo) # downsample lines for plotting lines = [line[:, ::8] for line in lines] try: if not plot2d: raise ImportError from viscid.plot import mpl mpl.plt.clf() mpl.plot2d_lines(lines, scalars=topo_color, symdir="y", marker="^") if show: mpl.plt.show() except ImportError: pass try: if not plot3d: raise ImportError from viscid.plot import mvi mvi.clf() fld_mag = np.log(viscid.magnitude(_fld)) try: # note: mayavi.mlab.mesh can't take color tuples as scalars # so one can't use topo_color on a mesh surface. This # is a limitation of mayavi. To actually plot a specific # set of colors on a mesh, one must use a texture vertices, scalars = _seeds.wrap_mesh(topo_fld.data) mesh = mvi.mlab.mesh(vertices[0], vertices[1], vertices[2], scalars=scalars, opacity=0.5) mesh.actor.property.backface_culling = True except RuntimeError: pass mvi.plot_lines(lines, scalars=fld_mag, tube_radius=0.005) if show: mvi.show() except ImportError: pass
def compare_vectors(cc_fld, ecfc_fld, to_cc_fn, catol=1e-8, rtol=2.2e-6, trim_slc=':', bnd=True, make_plots=False): trimmed = cc_fld[trim_slc] cc = to_cc_fn(ecfc_fld, bnd=bnd) reldiff = (cc - trimmed) / viscid.magnitude(trimmed) reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"] reldiff.name = cc.name + " - " + trimmed.name reldiff.pretty_name = cc.pretty_name + " - " + trimmed.pretty_name comp_beyond_limit = [False] * 3 for i, d in enumerate('xyz'): abs_max_rel_diff = np.nanmax(np.abs(reldiff[d])) # trim first and last when diffing crds since they're extrapolated # in the ecfc field, so we already know they won't match up do dx max_crd_diff = np.max((trimmed.get_crd(d) - cc.get_crd(d))[1:-1]) print("{0}{1}, max absolute relative diff: {2:.3e} ({1} crds: {3:.1e})" "".format(cc_fld.name, d, abs_max_rel_diff, max_crd_diff)) if abs_max_rel_diff > rtol or abs(max_crd_diff) > catol: comp_beyond_limit[i] = True # plot differences? if make_plots: ax1 = plt.subplot(311) vlt.plot(cc_fld[d]['y=0f'], symmetric=True, earth=True) plt.subplot(312, sharex=ax1, sharey=ax1) vlt.plot(cc[d]['y=0f'], symmetric=True, earth=True) plt.subplot(313, sharex=ax1, sharey=ax1) vlt.plot(reldiff[d]['y=0f'], symmetric=True, earth=True) vlt.show() if any(comp_beyond_limit): raise RuntimeError("Tolerance exceeded on ->CC accuracy")
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) dtype = 'float32' ######################################################################## # hard core test transpose (since this is used for mapfield transforms) x = np.array(np.linspace( 1, -1, 9), dtype=dtype) y = np.array(np.linspace(-1, 1, 9), dtype=dtype) z = np.array(np.linspace(-1, 1, 9), dtype=dtype) vI1 = viscid.empty([x, y, z], nr_comps=3, name='V', center='cell', layout='interlaced') vI2 = viscid.empty([z, y, x], nr_comps=3, name='V', center='cell', layout='interlaced', crd_names='zyx') vF1 = viscid.empty([x, y, z], nr_comps=3, name='V', center='cell', layout='flat') vF2 = viscid.empty([z, y, x], nr_comps=3, name='V', center='cell', layout='flat', crd_names='zyx') X1, Y1, Z1 = vI1.get_crds_cc(shaped=True) X2, Y2, Z2 = vI2.get_crds_cc(shaped=True) for v in (vI1, vF1): v['x'] = (0.5 * X1) + (0.0 * Y1) + (0.0 * Z1) v['y'] = (0.0 * X1) + (0.5 * Y1) + (0.5 * Z1) v['z'] = (0.0 * X1) + (0.5 * Y1) + (0.5 * Z1) for v in (vI2, vF2): v['z'] = (0.5 * X2) + (0.5 * Y2) + (0.0 * Z2) v['y'] = (0.5 * X2) + (0.5 * Y2) + (0.0 * Z2) v['x'] = (0.0 * X2) + (0.0 * Y2) + (0.5 * Z2) assert_different(vI1, vI2) # test some straight up transposes of both interlaced and flat fields assert_similar(vI1.spatial_transpose(), vI2) assert_similar(vI1.ST, vI2) assert_similar(vF1.spatial_transpose(), vF2) assert_similar(vI1.transpose(), vF2) assert_similar(vI1.T, vF2) assert_different(vI1.transpose(), vI2) assert_similar(vF1.transpose(), vI2) assert_different(vF1.transpose(), vF2) assert_similar(np.transpose(vI1), vF2) assert_similar(np.transpose(vF1), vI2) # now specify specific axes using all 3 interfaces assert_similar(vI1.spatial_transpose('x', 'z', 'y'), vI1) assert_similar(np.transpose(vI1, axes=[0, 2, 1, 3]), vI1) assert_similar(vI1.transpose(0, 2, 1, 3), vI1) assert_similar(vF1.spatial_transpose('x', 'z', 'y'), vF1) assert_similar(np.transpose(vF1, axes=(0, 1, 3, 2)), vF1) assert_similar(vF1.transpose(0, 1, 3, 2), vF1) # now test swapaxes since that uses assert_similar(vI1.swapaxes(1, 2), vI1) assert_similar(np.swapaxes(vI1, 1, 2), vI1) assert_similar(vI1.swap_crd_axes('y', 'z'), vI1) ############################## # test some other mathy stuff x = np.array(np.linspace(-1, 1, 2), dtype=dtype) y = np.array(np.linspace(-2, 2, 30), dtype=dtype) z = np.array(np.linspace(-5, 5, 90), dtype=dtype) v = viscid.empty([x, y, z], nr_comps=3, name='V', center='cell', layout='interlaced') X, Y, Z = v.get_crds_cc(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) mag = viscid.magnitude(v) mag2 = np.sqrt(np.sum(v * v, axis=v.nr_comp)) another = np.transpose(mag) plt.subplot(151) vlt.plot(v['x']) plt.subplot(152) vlt.plot(v['y']) plt.subplot(153) vlt.plot(mag) plt.subplot(154) vlt.plot(mag2) plt.subplot(155) vlt.plot(another) plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) dtype = 'float32' ######################################################################## # hard core test transpose (since this is used for mapfield transforms) x = np.array(np.linspace(1, -1, 9), dtype=dtype) y = np.array(np.linspace(-1, 1, 9), dtype=dtype) z = np.array(np.linspace(-1, 1, 9), dtype=dtype) vI1 = viscid.empty([x, y, z], nr_comps=3, name='V', center='cell', layout='interlaced') vI2 = viscid.empty([z, y, x], nr_comps=3, name='V', center='cell', layout='interlaced', crd_names='zyx') vF1 = viscid.empty([x, y, z], nr_comps=3, name='V', center='cell', layout='flat') vF2 = viscid.empty([z, y, x], nr_comps=3, name='V', center='cell', layout='flat', crd_names='zyx') X1, Y1, Z1 = vI1.get_crds_cc(shaped=True) X2, Y2, Z2 = vI2.get_crds_cc(shaped=True) for v in (vI1, vF1): v['x'] = (0.5 * X1) + (0.0 * Y1) + (0.0 * Z1) v['y'] = (0.0 * X1) + (0.5 * Y1) + (0.5 * Z1) v['z'] = (0.0 * X1) + (0.5 * Y1) + (0.5 * Z1) for v in (vI2, vF2): v['z'] = (0.5 * X2) + (0.5 * Y2) + (0.0 * Z2) v['y'] = (0.5 * X2) + (0.5 * Y2) + (0.0 * Z2) v['x'] = (0.0 * X2) + (0.0 * Y2) + (0.5 * Z2) assert_different(vI1, vI2) # test some straight up transposes of both interlaced and flat fields assert_similar(vI1.spatial_transpose(), vI2) assert_similar(vI1.ST, vI2) assert_similar(vF1.spatial_transpose(), vF2) assert_similar(vI1.transpose(), vF2) assert_similar(vI1.T, vF2) assert_different(vI1.transpose(), vI2) assert_similar(vF1.transpose(), vI2) assert_different(vF1.transpose(), vF2) assert_similar(np.transpose(vI1), vF2) assert_similar(np.transpose(vF1), vI2) # now specify specific axes using all 3 interfaces assert_similar(vI1.spatial_transpose('x', 'z', 'y'), vI1) assert_similar(np.transpose(vI1, axes=[0, 2, 1, 3]), vI1) assert_similar(vI1.transpose(0, 2, 1, 3), vI1) assert_similar(vF1.spatial_transpose('x', 'z', 'y'), vF1) assert_similar(np.transpose(vF1, axes=(0, 1, 3, 2)), vF1) assert_similar(vF1.transpose(0, 1, 3, 2), vF1) # now test swapaxes since that uses assert_similar(vI1.swapaxes(1, 2), vI1) assert_similar(np.swapaxes(vI1, 1, 2), vI1) assert_similar(vI1.swap_crd_axes('y', 'z'), vI1) ############################## # test some other mathy stuff x = np.array(np.linspace(-1, 1, 2), dtype=dtype) y = np.array(np.linspace(-2, 2, 30), dtype=dtype) z = np.array(np.linspace(-5, 5, 90), dtype=dtype) v = viscid.empty([x, y, z], nr_comps=3, name='V', center='cell', layout='interlaced') X, Y, Z = v.get_crds_cc(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) mag = viscid.magnitude(v) mag2 = np.sqrt(np.sum(v * v, axis=v.nr_comp)) another = np.transpose(mag) plt.subplot(151) vlt.plot(v['x']) plt.subplot(152) vlt.plot(v['y']) plt.subplot(153) vlt.plot(mag) plt.subplot(154) vlt.plot(mag2) plt.subplot(155) vlt.plot(another) plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = viscid.vutil.common_argparse(parser, default_verb=0) viscid.logger.setLevel(viscid.logging.DEBUG) args.show = False cotr = viscid.Cotr(dip_tilt=20.0, dip_gsm=15.0) # pylint: disable=not-callable b = viscid.make_dipole(m=cotr.get_dipole_moment(), n=(32, 32, 32)) seeds = viscid.Circle(n=5, r=1.5, pole=[0, 0, 1]) lines, topo = viscid.calc_streamlines(b, seeds, ibound=1.4, method='rk45') for i in range(2): # make sure this works for lines with 0, 1, 2, 3 vertices if i == 1: lines[1] = lines[2][:, :0] lines[2] = lines[2][:, :1] lines[3] = lines[3][:, :2] lines[4] = lines[4][:, :3] viscid.logger.debug('---') viscid.logger.debug('{0}'.format(len(lines))) for line in lines: viscid.logger.debug('line shape: {0}'.format(line.shape)) viscid.logger.debug('---') do_test(lines, scalars=None, txt='given None', show=args.show) do_test(lines, scalars='#ff0000', txt='given a single 24bit rgb hex color', show=args.show) do_test(lines, scalars='#ff000066', txt='given a single 32bit rgba hex color', show=args.show) do_test(lines, scalars='#f00', txt='given a single 12bit rgb hex color', show=args.show) do_test(lines, scalars='#f006', txt='given a single 16bit rgba hex color', show=args.show) do_test(lines, scalars=['#ff0000', '#cc0000', '#aa0000', '#880000', '#660000'], txt='given a list of Nlines 24bit rgb hex colors', show=args.show) do_test(lines, scalars=['#ff000066', '#cc000066', '#aa000066', '#88000066', '#66000066'], txt='given a list of Nlines 32bit rgba hex colors', show=args.show) do_test(lines, scalars=['#f00', '#c00', '#a00', '#800', '#600'], txt='given a list of Nlines 12bit rgb hex colors', show=args.show) do_test(lines, scalars=['#f00a', '#c009', '#a008', '#8007', '#6006'], txt='given a list of Nlines 16bit rgba hex colors', show=args.show) do_test(lines, scalars=[0.8, 0.0, 0.2], txt='given a single rgb [0..1] color', show=args.show) do_test(lines, scalars=[0.8, 0.0, 0.2, 0.8], txt='given a single rgba [0..1] color', show=args.show) do_test(lines, scalars=[(0.8, 0.0, 0.2), (0.7, 0.0, 0.3), (0.6, 0.0, 0.4), (0.5, 0.0, 0.5), (0.4, 0.0, 0.6)], txt='given a list of Nlines rgb [0..1] tuples', show=args.show) do_test(lines, scalars=[(0.8, 0.0, 0.2, 1.0), (0.7, 0.0, 0.3, 0.9), (0.6, 0.0, 0.4, 0.8), (0.5, 0.0, 0.5, 0.7), (0.4, 0.0, 0.6, 0.6)], txt='given a list of Nlines rgba [0..1] tuples', show=args.show) do_test(lines, scalars=[250, 0, 250], txt='given a single rgb [0..255] color', show=args.show) do_test(lines, scalars=[250, 0, 250, 190], txt='given a single rgba [0..255] color', show=args.show) do_test(lines, scalars=[(204, 0, 51), (179, 0, 77), (153, 0, 102), (127, 0, 127), (0.4, 0, 102)], txt='given a list of Nlines rgb [0..255] tuples', show=args.show) do_test(lines, scalars=[(204, 0, 51, 255), (179, 0, 77, 230), (153, 0, 102, 204), (127, 0, 127, 179), (102, 0, 102, 153)], txt='given a list of Nlines rgba [0..255] tuples', show=args.show) do_test(lines, scalars=['#ff000088', 'blue', 'lavenderblush', 'c', '#4f4'], txt='given a mix of color hex/html color names', show=args.show) do_test(lines, scalars=topo, txt='scalars == topo value', show=args.show) do_test(lines, scalars=viscid.topology2color(topo), txt='scalars == topo2color value', show=args.show) do_test(lines, scalars=np.log(viscid.magnitude(b)), txt='given bmag', show=args.show) # prevent weird xorg bad-instructions on tear down if 'figure' in _global_ns and _global_ns['figure'] is not None: from viscid.plot import vlab vlab.mlab.close(_global_ns['figure']) return 0
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) b = viscid.make_dipole(l=(-5, -5, -5), h=(5, 5, 5), n=(255, 255, 127), 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" _ = plt.figure(figsize=(9, 4.2)) ax1 = vlt.subplot(231) vlt.plot(b2['z=0f'], logscale=True) vlt.plot(b2['z=0f'], logscale=True, style='contour', levels=10, colors='grey') # vlt.plot2d_quiver(viscid.normalize(b['z=0f']), step=16, pivot='mid') ax2 = vlt.subplot(234) vlt.plot(b2['y=0f'], logscale=True) vlt.plot(b2['y=0f'], logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(b['y=0f'], preferred='numpy'), step=16, pivot='mid') vlt.subplot(232, sharex=ax1, sharey=ax1) vlt.plot(1e-4 + viscid.magnitude(grad_b2['z=0f']), logscale=True) vlt.plot(1e-4 + viscid.magnitude(grad_b2['z=0f']), logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(grad_b2['z=0f']), step=16, pivot='mid') vlt.subplot(235, sharex=ax2, sharey=ax2) vlt.plot(1e-4 + viscid.magnitude(grad_b2['y=0f']), logscale=True) vlt.plot(1e-4 + viscid.magnitude(grad_b2['y=0f']), logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(grad_b2['y=0f']), step=16, pivot='mid') vlt.subplot(233, sharex=ax1, sharey=ax1) vlt.plot(viscid.magnitude(conv['z=0f']), logscale=True) vlt.plot(viscid.magnitude(conv['z=0f']), logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(conv['z=0f']), step=16, pivot='mid') vlt.subplot(236, sharex=ax2, sharey=ax2) vlt.plot(viscid.magnitude(conv['y=0f']), logscale=True) vlt.plot(viscid.magnitude(conv['y=0f']), logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(conv['y=0f']), step=16, pivot='mid') vlt.auto_adjust_subplots() plt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() return 0
def main(): mhd_type = "C" make_plots = 1 test_fc = 1 test_ec = 1 test_div = 1 test_interp = 1 test_streamline = 1 mhd_type = mhd_type.upper() if mhd_type.startswith("C"): if mhd_type in ("C", ): f = viscid.load_file("$WORK/tmedium/*.3d.[-1].xdmf") elif mhd_type in ("C2", "C3"): f = viscid.load_file("$WORK/tmedium2/*.3d.[-1].xdmf") else: raise ValueError() catol = 1e-8 rtol = 5e-6 elif mhd_type in ("F", "FORTRAN"): f = viscid.load_file("$WORK/tmedium3/*.3df.[-1]") catol = 1e-8 rtol = 7e-2 else: raise ValueError() ISLICE = slice(None) # ISLICE = 'y=0f:0.15f' # ################# # # test out fc2cc if test_fc: b = f['b'][ISLICE] b1 = f['b1'][ISLICE] compare_vectors(b, b1, viscid.fc2cc, catol=catol, rtol=rtol, make_plots=make_plots) ################# # test out ec2cc if test_ec: e_cc = f['e_cc'][ISLICE] e_ec = f['e_ec'][ISLICE] if mhd_type not in ("F", "FORTRAN"): compare_vectors(e_cc, e_ec, viscid.ec2cc, catol=catol, rtol=rtol, make_plots=make_plots) ################# # test out divfc # Note: Relative error on Div B is meaningless b/c the coordinates # are not the same up to order (dx/4) I think. You can see this # since (fcdiv - divb_trimmed) is both noisy and stripy if test_div: bnd = 0 if mhd_type not in ("F", "FORTRAN"): b1 = f['b1'][ISLICE] divb = f['divB'][ISLICE] if bnd: trimmed = divb else: trimmed = divb['x=1:-1, y=1:-1, z=1:-1'] b1mag = viscid.magnitude(viscid.fc2cc(b1, bnd=bnd)) divb1 = viscid.div_fc(b1, bnd=bnd) viscid.set_in_region(trimmed, trimmed, alpha=0.0, beta=0.0, out=trimmed, mask=viscid.make_spherical_mask(trimmed, rmax=5.0)) viscid.set_in_region(divb1, divb1, alpha=0.0, beta=0.0, out=divb1, mask=viscid.make_spherical_mask(divb1, rmax=5.0)) reldiff = (divb1 - trimmed) / b1mag reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"] reldiff.name = divb1.name + " - " + trimmed.name reldiff.pretty_name = divb1.pretty_name + " - " + trimmed.pretty_name abs_max_rel_diff = np.nanmax(np.abs(reldiff)) max_crd_diff = [0.0] * 3 for i, d in enumerate('xyz'): max_crd_diff[i] = np.max(trimmed.get_crd(d) - divb1.get_crd(d)) print("divB max absolute relative diff: {0:.3e} " "(crds: X: {1[0]:.3e}, Y: {1[1]:.3e}, Z: {1[2]:.3e})" "".format(abs_max_rel_diff, max_crd_diff)) # plot differences? if make_plots: ax1 = plt.subplot(311) vlt.plot(divb['y=0f'], symmetric=True, earth=True) plt.subplot(312, sharex=ax1, sharey=ax1) vlt.plot(divb1['y=0f'], symmetric=True, earth=True) plt.subplot(313, sharex=ax1, sharey=ax1) vlt.plot(reldiff['y=0f'], symmetric=True, earth=True) vlt.show() # Since the coordinates will be different by order dx^2 (i think), # there is no way to compare the divB from simulation with the # one we get here. However, they should be the same up to a few %, and # down to noise level with stripes of enhanced noise. These stripes # are the errors in the coordinate values (since the output only # gives us weird nc = averaged cc locations) # # if abs_max_rel_diff > rtol or np.any(np.abs(max_crd_diff) > catol): # raise RuntimeError("Tolerance exceeded on divB calculation") if test_streamline: b_cc = f['b_cc']['x=-40f:12f, y=-15f:15f, z=-15f:15f'] b_fc = f['b_fc']['x=-40f:12f, y=-15f:15f, z=-15f:15f'] cotr = viscid.cotr.Cotr() r_mask = 3.0 # set b_cc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_cc) viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask) # set b_fc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_fc) viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask) seeds = viscid.Volume([-10, 0, -5], [10, 0, 5], (16, 1, 3)) sl_kwargs = dict(ibound=1.0, method=viscid.EULER1A) lines_cc, topo_cc = viscid.calc_streamlines(b_cc, seeds, **sl_kwargs) lines_fc, topo_fc = viscid.calc_streamlines(b_fc, seeds, **sl_kwargs) if make_plots: plt.figure(figsize=(10, 6)) ax0 = plt.subplot(211) topo_cc_colors = viscid.topology2color(topo_cc) vlt.plot(f['pp']['y=0f'], logscale=True, earth=True, cmap='plasma') vlt.plot2d_lines(lines_cc, topo_cc_colors, symdir='y') ax0 = plt.subplot(212, sharex=ax0, sharey=ax0) topo_fc_colors = viscid.topology2color(topo_fc) vlt.plot(f['pp']['y=0f'], logscale=True, earth=True, cmap='plasma') vlt.plot2d_lines(lines_fc, topo_fc_colors, symdir='y') plt.xlim(-20, 10) plt.ylim(-10, 10) vlt.auto_adjust_subplots() vlt.show() if test_interp: # test interpolation with E . B / B b_cc = f['b_cc'] b_fc = f['b_fc'] e_cc = f['e_cc'] e_ec = f['e_ec'] cotr = viscid.cotr.Cotr() r_mask = 3.0 # set b_cc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_cc) viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask) # set b_fc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_fc) viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask) # zero out e_cc inside some sphere viscid.set_in_region(e_cc, e_cc, alpha=0.0, beta=0.0, out=e_cc, mask=viscid.make_spherical_mask(e_cc, rmax=r_mask)) # zero out e_ec inside some sphere viscid.set_in_region(e_ec, e_ec, alpha=0.0, beta=0.0, out=e_ec, mask=viscid.make_spherical_mask(e_ec, rmax=r_mask)) tmp = viscid.empty([ np.linspace(-10, 10, 64), np.linspace(-10, 10, 64), np.linspace(-10, 10, 64) ], center="Cell") b_cc_interp = viscid.interp_linear(b_cc, tmp) b_fc_interp = viscid.interp_linear(b_fc, tmp) e_cc_interp = viscid.interp_linear(e_cc, tmp) e_ec_interp = viscid.interp_linear(e_ec, tmp) epar_cc = viscid.dot(e_cc_interp, b_cc_interp) / viscid.magnitude(b_cc_interp) epar_ecfc = viscid.dot(e_ec_interp, b_fc_interp) / viscid.magnitude(b_fc_interp) if make_plots: # plt.figure() # ax0 = plt.subplot(121) # vlt.plot(b_cc['x']['y=0f'], clim=(-40, 40)) # plt.subplot(122, sharex=ax0, sharey=ax0) # vlt.plot(b_fc['x']['y=0f'], clim=(-40, 40)) # vlt.show() plt.figure(figsize=(14, 5)) ax0 = plt.subplot(131) vlt.plot(epar_cc['y=0f'], symmetric=True, cbarlabel="Epar CC") plt.subplot(132, sharex=ax0, sharey=ax0) vlt.plot(epar_ecfc['y=0f'], symmetric=True, cbarlabel="Epar ECFC") plt.subplot(133, sharex=ax0, sharey=ax0) vlt.plot(((epar_cc - epar_ecfc) / epar_cc)['y=0f'], clim=(-10, 10), cbarlabel="Rel Diff") vlt.auto_adjust_subplots() vlt.show() return 0
def main(): mhd_type = "C" make_plots = 1 test_fc = 1 test_ec = 1 test_div = 1 test_interp = 1 test_streamline = 1 mhd_type = mhd_type.upper() if mhd_type.startswith("C"): if mhd_type in ("C",): f = viscid.load_file("$WORK/tmedium/*.3d.[-1].xdmf") elif mhd_type in ("C2", "C3"): f = viscid.load_file("$WORK/tmedium2/*.3d.[-1].xdmf") else: raise ValueError() catol = 1e-8 rtol = 5e-6 elif mhd_type in ("F", "FORTRAN"): f = viscid.load_file("$WORK/tmedium3/*.3df.[-1]") catol = 1e-8 rtol = 7e-2 else: raise ValueError() ISLICE = slice(None) # ISLICE = 'y=0j:0.15j' # ################# # # test out fc2cc if test_fc: b = f['b'][ISLICE] b1 = f['b1'][ISLICE] compare_vectors(b, b1, viscid.fc2cc, catol=catol, rtol=rtol, make_plots=make_plots) ################# # test out ec2cc if test_ec: e_cc = f['e_cc'][ISLICE] e_ec = f['e_ec'][ISLICE] if mhd_type not in ("F", "FORTRAN"): compare_vectors(e_cc, e_ec, viscid.ec2cc, catol=catol, rtol=rtol, make_plots=make_plots) ################# # test out divfc # Note: Relative error on Div B is meaningless b/c the coordinates # are not the same up to order (dx/4) I think. You can see this # since (fcdiv - divb_trimmed) is both noisy and stripy if test_div: bnd = 0 if mhd_type not in ("F", "FORTRAN"): b1 = f['b1'][ISLICE] divb = f['divB'][ISLICE] if bnd: trimmed = divb else: trimmed = divb['x=1:-1, y=1:-1, z=1:-1'] b1mag = viscid.magnitude(viscid.fc2cc(b1, bnd=bnd)) divb1 = viscid.div_fc(b1, bnd=bnd) viscid.set_in_region(trimmed, trimmed, alpha=0.0, beta=0.0, out=trimmed, mask=viscid.make_spherical_mask(trimmed, rmax=5.0)) viscid.set_in_region(divb1, divb1, alpha=0.0, beta=0.0, out=divb1, mask=viscid.make_spherical_mask(divb1, rmax=5.0)) reldiff = (divb1 - trimmed) / b1mag reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"] reldiff.name = divb1.name + " - " + trimmed.name reldiff.pretty_name = divb1.pretty_name + " - " + trimmed.pretty_name abs_max_rel_diff = np.nanmax(np.abs(reldiff)) max_crd_diff = [0.0] * 3 for i, d in enumerate('xyz'): max_crd_diff[i] = np.max(trimmed.get_crd(d) - divb1.get_crd(d)) print("divB max absolute relative diff: {0:.3e} " "(crds: X: {1[0]:.3e}, Y: {1[1]:.3e}, Z: {1[2]:.3e})" "".format(abs_max_rel_diff, max_crd_diff)) # plot differences? if make_plots: ax1 = plt.subplot(311) vlt.plot(divb['y=0j'], symmetric=True, earth=True) plt.subplot(312, sharex=ax1, sharey=ax1) vlt.plot(divb1['y=0j'], symmetric=True, earth=True) plt.subplot(313, sharex=ax1, sharey=ax1) vlt.plot(reldiff['y=0j'], symmetric=True, earth=True) vlt.show() # Since the coordinates will be different by order dx^2 (i think), # there is no way to compare the divB from simulation with the # one we get here. However, they should be the same up to a few %, and # down to noise level with stripes of enhanced noise. These stripes # are the errors in the coordinate values (since the output only # gives us weird nc = averaged cc locations) # # if abs_max_rel_diff > rtol or np.any(np.abs(max_crd_diff) > catol): # raise RuntimeError("Tolerance exceeded on divB calculation") if test_streamline: b_cc = f['b_cc']['x=-40j:12j, y=-15j:15j, z=-15j:15j'] b_fc = f['b_fc']['x=-40j:12j, y=-15j:15j, z=-15j:15j'] cotr = viscid.cotr.Cotr() r_mask = 3.0 # set b_cc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_cc) viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask) # set b_fc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_fc) viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask) seeds = viscid.Volume([-10, 0, -5], [10, 0, 5], (16, 1, 3)) sl_kwargs = dict(ibound=1.0, method=viscid.EULER1A) lines_cc, topo_cc = viscid.calc_streamlines(b_cc, seeds, **sl_kwargs) lines_fc, topo_fc = viscid.calc_streamlines(b_fc, seeds, **sl_kwargs) if make_plots: plt.figure(figsize=(10, 6)) ax0 = plt.subplot(211) topo_cc_colors = viscid.topology2color(topo_cc) vlt.plot(f['pp']['y=0j'], logscale=True, earth=True, cmap='plasma') vlt.plot2d_lines(lines_cc, topo_cc_colors, symdir='y') ax0 = plt.subplot(212, sharex=ax0, sharey=ax0) topo_fc_colors = viscid.topology2color(topo_fc) vlt.plot(f['pp']['y=0j'], logscale=True, earth=True, cmap='plasma') vlt.plot2d_lines(lines_fc, topo_fc_colors, symdir='y') plt.xlim(-20, 10) plt.ylim(-10, 10) vlt.auto_adjust_subplots() vlt.show() if test_interp: # test interpolation with E . B / B b_cc = f['b_cc'] b_fc = f['b_fc'] e_cc = f['e_cc'] e_ec = f['e_ec'] cotr = viscid.cotr.Cotr() r_mask = 3.0 # set b_cc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_cc) viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask) # set b_fc to dipole inside some sphere isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask) moment = cotr.get_dipole_moment(crd_system=b_fc) viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask) # zero out e_cc inside some sphere viscid.set_in_region(e_cc, e_cc, alpha=0.0, beta=0.0, out=e_cc, mask=viscid.make_spherical_mask(e_cc, rmax=r_mask)) # zero out e_ec inside some sphere viscid.set_in_region(e_ec, e_ec, alpha=0.0, beta=0.0, out=e_ec, mask=viscid.make_spherical_mask(e_ec, rmax=r_mask)) tmp = viscid.empty([np.linspace(-10, 10, 64), np.linspace(-10, 10, 64), np.linspace(-10, 10, 64)], center="Cell") b_cc_interp = viscid.interp_linear(b_cc, tmp) b_fc_interp = viscid.interp_linear(b_fc, tmp) e_cc_interp = viscid.interp_linear(e_cc, tmp) e_ec_interp = viscid.interp_linear(e_ec, tmp) epar_cc = viscid.dot(e_cc_interp, b_cc_interp) / viscid.magnitude(b_cc_interp) epar_ecfc = viscid.dot(e_ec_interp, b_fc_interp) / viscid.magnitude(b_fc_interp) if make_plots: # plt.figure() # ax0 = plt.subplot(121) # vlt.plot(b_cc['x']['y=0j'], clim=(-40, 40)) # plt.subplot(122, sharex=ax0, sharey=ax0) # vlt.plot(b_fc['x']['y=0j'], clim=(-40, 40)) # vlt.show() plt.figure(figsize=(14, 5)) ax0 = plt.subplot(131) vlt.plot(epar_cc['y=0j'], symmetric=True, cbarlabel="Epar CC") plt.subplot(132, sharex=ax0, sharey=ax0) vlt.plot(epar_ecfc['y=0j'], symmetric=True, cbarlabel="Epar ECFC") plt.subplot(133, sharex=ax0, sharey=ax0) vlt.plot(((epar_cc - epar_ecfc) / epar_cc)['y=0j'], clim=(-10, 10), cbarlabel="Rel Diff") vlt.auto_adjust_subplots() vlt.show() return 0
def main(): mhd_type = "C" make_plots = 1 test_fc = 1 test_ec = 1 test_div = 1 mhd_type = mhd_type.upper() if mhd_type.startswith("C"): if mhd_type in ("C",): f = viscid.load_file("$WORK/tmedium/*.3d.[-1].xdmf") elif mhd_type in ("C2", "C3"): f = viscid.load_file("$WORK/tmedium2/*.3d.[-1].xdmf") else: raise ValueError() catol = 1e-8 rtol = 2.2e-6 elif mhd_type in ("F", "FORTRAN"): f = viscid.load_file("$WORK/tmedium3/*.3df.[-1]") catol = 1e-8 rtol = 7e-2 else: raise ValueError() ISLICE = slice(None) # ISLICE = 'y=0f:0.15f' # ################# # # test out fc2cc if test_fc: b = f['b'][ISLICE] b1 = f['b1'][ISLICE] compare_vectors(b, b1, viscid.fc2cc, catol=catol, rtol=rtol, make_plots=make_plots) ################# # test out ec2cc if test_ec: e_cc = f['e_cc'][ISLICE] e_ec = f['e_ec'][ISLICE] if mhd_type not in ("F", "FORTRAN"): compare_vectors(e_cc, e_ec, viscid.ec2cc, catol=catol, rtol=rtol, make_plots=make_plots) ################# # test out divfc # Note: Relative error on Div B is meaningless b/c the coordinates # are not the same up to order (dx/4) I think. You can see this # since (fcdiv - divb_trimmed) is both noisy and stripy if test_div: bnd = 0 if mhd_type not in ("F", "FORTRAN"): b1 = f['b1'][ISLICE] divb = f['divB'][ISLICE] if bnd: trimmed = divb else: trimmed = divb['x=1:-1, y=1:-1, z=1:-1'] b1mag = viscid.magnitude(viscid.fc2cc(b1, bnd=bnd)) divb1 = viscid.div_fc(b1, bnd=bnd) viscid.set_in_region(trimmed, trimmed, alpha=0.0, beta=0.0, out=trimmed, mask=viscid.make_spherical_mask(trimmed, rmax=5.0)) viscid.set_in_region(divb1, divb1, alpha=0.0, beta=0.0, out=divb1, mask=viscid.make_spherical_mask(divb1, rmax=5.0)) reldiff = (divb1 - trimmed) / b1mag reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"] reldiff.name = divb1.name + " - " + trimmed.name reldiff.pretty_name = divb1.pretty_name + " - " + trimmed.pretty_name abs_max_rel_diff = np.nanmax(np.abs(reldiff)) max_crd_diff = [0.0] * 3 for i, d in enumerate('xyz'): max_crd_diff[i] = np.max(trimmed.get_crd(d) - divb1.get_crd(d)) print("divB max absolute relative diff: {0:.3e} " "(crds: X: {1[0]:.3e}, Y: {1[1]:.3e}, Z: {1[2]:.3e})" "".format(abs_max_rel_diff, max_crd_diff)) # plot differences? if make_plots: ax1 = mpl.plt.subplot(311) mpl.plot(divb['y=0f'], symmetric=True, earth=True) mpl.plt.subplot(312, sharex=ax1, sharey=ax1) mpl.plot(divb1['y=0f'], symmetric=True, earth=True) mpl.plt.subplot(313, sharex=ax1, sharey=ax1) mpl.plot(reldiff['y=0f'], symmetric=True, earth=True) mpl.show() # Since the coordinates will be different by order dx^2 (i think), # there is no way to compare the divB from simulation with the # one we get here. However, they should be the same up to a few %, and # down to noise level with stripes of enhanced noise. These stripes # are the errors in the coordinate values (since the output only # gives us weird nc = averaged cc locations) # # if abs_max_rel_diff > rtol or np.any(np.abs(max_crd_diff) > catol): # raise RuntimeError("Tolerance exceeded on divB calculation") return 0
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) b = viscid.make_dipole(l=(-5, -5, -5), h=(5, 5, 5), n=(255, 255, 127), 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" _ = plt.figure(figsize=(9, 4.2)) ax1 = vlt.subplot(231) vlt.plot(b2['z=0j'], logscale=True) vlt.plot(b2['z=0j'], logscale=True, style='contour', levels=10, colors='grey') # vlt.plot2d_quiver(viscid.normalize(b['z=0j']), step=16, pivot='mid') ax2 = vlt.subplot(234) vlt.plot(b2['y=0j'], logscale=True) vlt.plot(b2['y=0j'], logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(b['y=0j'], preferred='numpy'), step=16, pivot='mid') vlt.subplot(232, sharex=ax1, sharey=ax1) vlt.plot(1e-4 + viscid.magnitude(grad_b2['z=0j']), logscale=True) vlt.plot(1e-4 + viscid.magnitude(grad_b2['z=0j']), logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(grad_b2['z=0j']), step=16, pivot='mid') vlt.subplot(235, sharex=ax2, sharey=ax2) vlt.plot(1e-4 + viscid.magnitude(grad_b2['y=0j']), logscale=True) vlt.plot(1e-4 + viscid.magnitude(grad_b2['y=0j']), logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(grad_b2['y=0j']), step=16, pivot='mid') vlt.subplot(233, sharex=ax1, sharey=ax1) vlt.plot(viscid.magnitude(conv['z=0j']), logscale=True) vlt.plot(viscid.magnitude(conv['z=0j']), logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(conv['z=0j']), step=16, pivot='mid') vlt.subplot(236, sharex=ax2, sharey=ax2) vlt.plot(viscid.magnitude(conv['y=0j']), logscale=True) vlt.plot(viscid.magnitude(conv['y=0j']), logscale=True, style='contour', levels=10, colors='grey') vlt.plot2d_quiver(viscid.normalize(conv['y=0j']), step=16, pivot='mid') vlt.auto_adjust_subplots() plt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() return 0