def run_test_iof(f, main__file__, show=False): vlt.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=True, cbar_kwargs=dict(pad=0.15) # pad the colorbar away from the plot ) ax1 = vlt.subplot(121, projection='polar') vlt.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 = vlt.subplot(122, projection='polar') plot_args['gridec'] = False vlt.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) vlt.auto_adjust_subplots(subplot_params=dict()) plt.gcf().set_size_inches(8, 4) plt.savefig(next_plot_fname(main__file__)) if show: vlt.mplshow()
def do_test(lines, scalars, show=False, txt=""): viscid.logger.info('--> ' + txt) title = txt + '\n' + "\n".join( textwrap.wrap("scalars = {0}".format(scalars), width=50)) try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt vlt.clf() vlt.plot_lines(lines, scalars=scalars) plt.title(title) vlt.savefig(next_plot_fname(__file__, series='q2')) if show: vlt.show() except ImportError: pass try: from mayavi import mlab vlab, _ = get_mvi_fig() vlab.clf() vlab.plot_lines3d(lines, scalars=scalars) vlab.fancy_axes() mlab.text(0.05, 0.05, title) vlab.savefig(next_plot_fname(__file__, series='q3')) if show: vlab.show(stop=True) except ImportError: pass
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f = viscid.load_file(os.path.join(sample_dir, 'vpic_sample', 'global.vpc')) # some slices that are good to check vlt.clf() vlt.plot(f['bx']['x=:32.01j']) plt.close() vlt.clf() vlt.plot(f['bx']['x=:33.0j']) plt.close() _, axes = vlt.subplots(2, 2, figsize=(8, 4)) for i, ti in enumerate([0, -1]): f.activate_time(ti) vlt.plot(f['n_e']['y=0j'], symmetric=False, ax=axes[0, i]) vlt.plot(f['bx']['y=0j'], symmetric=True, ax=axes[1, i]) axes[0, i].set_title(f.get_grid().time) vlt.auto_adjust_subplots() plt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() plt.close() return 0
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 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 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 main(): f = viscid.load_file("~/dev/work/tmedium/*.3d.[-1].xdmf") grid = f.get_grid() gslc = "x=-26j:12.5j, y=-15j:15j, z=-15j:15j" # gslc = "x=-12.5j:26j, y=-15j:15j, z=-15j:15j" 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=0j'], **pargs) # # vlt.plot(viscid.magnitude(f['b_cc']['y=0j']), **pargs) # # vlt.show() # vlt.subplot(212, sharex=ax1, sharey=ax1) # vlt.plot(viscid.magnitude(viscid.fc2cc(f['b_fc'])['y=0j']), **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=0j'], style='contour', levels=5, colorbar=None, colors='k', **pargs) vlt.plot(viscid.magnitude(f2['b_cc']['y=0j']), **pargs) vlt.subplot(212, sharex=ax1, sharey=ax1) vlt.plot(viscid.magnitude(viscid.fc2cc(f2['b_fc'])['y=0j']), **pargs) vlt.show() os.remove(basename + '.h5') os.remove(basename + '.xdmf') return 0
def do_test(lines, scalars, show=False, txt=""): viscid.logger.info('--> ' + txt) title = txt + '\n' + "\n".join(textwrap.wrap("scalars = {0}".format(scalars), width=50)) try: from matplotlib import pyplot as plt from viscid.plot import vpyplot as vlt vlt.clf() vlt.plot_lines(lines, scalars=scalars) plt.title(title) vlt.savefig(next_plot_fname(__file__, series='q2')) if show: vlt.show() except ImportError: pass try: from mayavi import mlab 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 vlab.clf() vlab.plot_lines3d(lines, scalars=scalars) vlab.fancy_axes() mlab.text(0.05, 0.05, title) vlab.savefig(next_plot_fname(__file__, series='q3')) if show: vlab.show(stop=True) except ImportError: pass
def do_test(lines, scalars, show=False, txt=""): viscid.logger.info('--> ' + txt) title = txt + '\n' + "\n".join(textwrap.wrap("scalars = {0}".format(scalars), width=50)) try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt vlt.clf() vlt.plot_lines(lines, scalars=scalars) plt.title(title) vlt.savefig(next_plot_fname(__file__, series='q2')) if show: vlt.show() except ImportError: pass try: from mayavi import mlab 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 vlab.clf() vlab.plot_lines3d(lines, scalars=scalars) vlab.fancy_axes() mlab.text(0.05, 0.05, title) vlab.savefig(next_plot_fname(__file__, series='q3')) if show: vlab.show(stop=True) except ImportError: pass
def run_test_timeseries(f, main__file__, show=False): vlt.clf() ntimes = f.nr_times() t = [None] * ntimes pressure = np.zeros((ntimes, ), dtype='f4') for i, grid in enumerate(f.iter_times()): t[i] = grid.time_as_datetime() pressure[i] = grid['pp']['x=10.0f, y=0.0f, z=0.0f'] plt.plot(t, pressure) plt.ylabel('Pressure') dateFmt = mdates.DateFormatter('%H:%M:%S') plt.gca().xaxis.set_major_formatter(dateFmt) plt.gcf().autofmt_xdate() plt.gca().grid(True) plt.gcf().set_size_inches(8, 4) plt.savefig(next_plot_fname(main__file__)) if show: vlt.mplshow()
def run_test_timeseries(f, main__file__, show=False): vlt.clf() ntimes = f.nr_times() t = [None] * ntimes pressure = np.zeros((ntimes,), dtype='f4') for i, grid in enumerate(f.iter_times()): t[i] = grid.time_as_datetime() pressure[i] = grid['pp']['x=10.0j, y=0.0j, z=0.0j'] plt.plot(t, pressure) plt.ylabel('Pressure') dateFmt = mdates.DateFormatter('%H:%M:%S') plt.gca().xaxis.set_major_formatter(dateFmt) plt.gcf().autofmt_xdate() plt.gca().grid(True) plt.gcf().set_size_inches(8, 4) plt.savefig(next_plot_fname(main__file__)) if show: vlt.mplshow()
def run_test_3d(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.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("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 _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--notwo", dest='notwo', action="store_true") parser.add_argument("--nothree", dest='nothree', action="store_true") parser.add_argument("--show", "--plot", action="store_true") args = viscid.vutil.common_argparse(parser, default_verb=0) plot2d = not args.notwo plot3d = not args.nothree # plot2d = True # plot3d = True # args.show = True img = np.load(os.path.join(sample_dir, "logo.npy")) x = np.linspace(-1, 1, img.shape[0]) y = np.linspace(-1, 1, img.shape[1]) z = np.linspace(-1, 1, img.shape[2]) logo = viscid.arrays2field([x, y, z], img) if 1: viscid.logger.info('Testing Line...') seeds = viscid.Line([-1, -1, 0], [1, 1, 2], n=5) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Plane...') seeds = viscid.Plane([0.0, 0.0, 0.0], [1, 1, 1], [1, 0, 0], 2, 2, nl=160, nm=170, NL_are_vectors=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Volume...') seeds = viscid.Volume([-0.8, -0.8, -0.8], [0.8, 0.8, 0.8], n=[64, 64, 3]) # note: can't make a 2d plot of the volume w/o a slice run_test(logo, seeds, plot2d=False, plot3d=plot3d, add_title="3d", show=args.show) if 1: viscid.logger.info('Testing Volume (with ignorable dim)...') seeds = viscid.Volume([-0.8, -0.8, 0.0], [0.8, 0.8, 0.0], n=[64, 64, 1]) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="2d", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (phi, theta)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (theta, phi)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (phi, theta)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (theta, phi)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Patch...') seeds = viscid.SphericalPatch(p0=[0, 0, 0], p1=[0, -0, -1], max_alpha=30.0, max_beta=59.9, nalpha=65, nbeta=80, r=0.5, roll=45.0) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing RectilinearMeshPoints...') f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[-1].xdmf')) slc = 'x=-40f:12f, y=-10f:10f, z=-10f:10f' b = f['b'][slc] z = b.get_crd('z') sheet_iz = np.argmin(b['x']**2, axis=2) sheet_pts = b['z=0:1'].get_points() sheet_pts[2, :] = z[sheet_iz].reshape(-1) isphere_mask = np.sum(sheet_pts[:2, :]**2, axis=0) < 5**2 day_mask = sheet_pts[0:1, :] > -1.0 sheet_pts[2, :] = np.choose(isphere_mask, [sheet_pts[2, :], 0]) sheet_pts[2, :] = np.choose(day_mask, [sheet_pts[2, :], 0]) nx, ny, _ = b.sshape sheet_seed = viscid.RectilinearMeshPoints(sheet_pts.reshape(3, nx, ny)) vx_sheet = viscid.interp_nearest(f['vx'], sheet_seed) try: if not plot2d: raise ImportError from matplotlib import pyplot as plt from viscid.plot import vpyplot as vlt vlt.clf() vlt.plot(vx_sheet, symmetric=True) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: vlt.show() except ImportError: pass try: if not plot3d: raise ImportError from viscid.plot import vlab vlab.clf() mesh = vlab.mesh_from_seeds(sheet_seed, scalars=vx_sheet, clim=(-400, 400)) vlab.plot_earth_3d(crd_system=b) vlab.view(azimuth=+90.0 + 45.0, elevation=90.0 - 25.0, distance=30.0, focalpoint=(-10.0, +1.0, +1.0)) vlab.title("RectilinearMeshPoints") vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show() except ImportError: pass # 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(): global offscreen_vlab parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--notwo", dest='notwo', action="store_true") parser.add_argument("--nothree", dest='nothree', action="store_true") parser.add_argument("--show", "--plot", action="store_true") args = viscid.vutil.common_argparse(parser, default_verb=0) plot2d = not args.notwo plot3d = not args.nothree # plot2d = True # plot3d = True # args.show = True offscreen_vlab = not args.show img = np.load(os.path.join(sample_dir, "logo.npy")) x = np.linspace(-1, 1, img.shape[0]) y = np.linspace(-1, 1, img.shape[1]) z = np.linspace(-1, 1, img.shape[2]) logo = viscid.arrays2field([x, y, z], img) if 1: viscid.logger.info('Testing Point with custom local coordinates...') pts = np.vstack([[-1, -0.5, 0, 0.5, 1], [-1, -0.5, 0, 0.5, 1], [ 0, 0.5, 1, 1.5, 2]]) local_crds = viscid.asarray_datetime64([0, 60, 120, 180, 240], conservative=True) seeds = viscid.Point(pts, local_crds=local_crds) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Line...') seeds = viscid.Line([-1, -1, 0], [1, 1, 2], n=5) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Plane...') seeds = viscid.Plane([0.0, 0.0, 0.0], [1, 1, 1], [1, 0, 0], 2, 2, nl=160, nm=170, NL_are_vectors=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Volume...') seeds = viscid.Volume([-0.8, -0.8, -0.8], [0.8, 0.8, 0.8], n=[64, 64, 3]) # note: can't make a 2d plot of the volume w/o a slice run_test(logo, seeds, plot2d=False, plot3d=plot3d, add_title="3d", show=args.show) if 1: viscid.logger.info('Testing Volume (with ignorable dim)...') seeds = viscid.Volume([-0.8, -0.8, 0.0], [0.8, 0.8, 0.0], n=[64, 64, 1]) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="2d", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (phi, theta)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (theta, phi)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (phi, theta)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (theta, phi)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Patch...') seeds = viscid.SphericalPatch(p0=[0, 0, 0], p1=[0, -0, -1], max_alpha=30.0, max_beta=59.9, nalpha=65, nbeta=80, r=0.5, roll=45.0) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: # this spline test is very custom viscid.logger.info('Testing Spline...') try: import scipy.interpolate as interpolate except ImportError: msg = "XFail: ImportError (is scipy installed?)" if plot2d: try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() plt.annotate(msg, xy=(0.3, 0.4), xycoords='axes fraction') plt.savefig(next_plot_fname(__file__, series='2d')) plt.savefig(next_plot_fname(__file__, series='2d')) plt.savefig(next_plot_fname(__file__, series='3d')) if args.show: plt.show() except ImportError: pass else: knots = np.array([[ 0.2, 0.5, 0.0], [-0.2, 0.5, 0.2], [-0.2, 0.0, 0.4], [ 0.2, 0.0, 0.2], [ 0.2, -0.5, 0.0], [-0.2, -0.5, 0.2]]).T seed_name = "Spline" fld = logo seeds = viscid.Spline(knots) seed_pts = seeds.get_points() interp_fld = viscid.interp_trilin(fld, seeds) if plot2d: try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() vlt.plot(interp_fld) plt.title(seed_name) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: plt.show() plt.clf() from matplotlib import rcParams _ms = rcParams['lines.markersize'] plt.gca().scatter(knots[0, :], knots[1, :], s=(2 * _ms)**2, marker='^', color='y') plt.gca().scatter(seed_pts[0, :], seed_pts[1, :], s=(1.5 * _ms)**2, marker='o', color='k') vlt.plot2d_line(seed_pts, scalars=interp_fld.flat_data, symdir='z') plt.title(seed_name) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: plt.show() except ImportError: pass if plot3d: try: vlab, _ = get_mvi_fig() vlab.points3d(knots[0], knots[1], knots[2], color=(1.0, 1.0, 0), scale_mode='none', scale_factor=0.04) p = vlab.points3d(seed_pts[0], seed_pts[1], seed_pts[2], color=(0, 0, 0), scale_mode='none', scale_factor=0.03) vlab.plot_line(seed_pts, scalars=interp_fld.flat_data, tube_radius=0.01) vlab.axes(p) vlab.title(seed_name) vlab.mlab.roll(-90.0) vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show(stop=True) except ImportError: pass if 1: viscid.logger.info('Testing RectilinearMeshPoints...') f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[-1].xdmf')) slc = 'x=-40j:12j, y=-10j:10j, z=-10j:10j' b = f['b'][slc] z = b.get_crd('z') sheet_iz = np.argmin(b['x']**2, axis=2) sheet_pts = b['z=0:1'].get_points() sheet_pts[2, :] = z[sheet_iz].reshape(-1) isphere_mask = np.sum(sheet_pts[:2, :]**2, axis=0) < 5**2 day_mask = sheet_pts[0:1, :] > -1.0 sheet_pts[2, :] = np.choose(isphere_mask, [sheet_pts[2, :], 0]) sheet_pts[2, :] = np.choose(day_mask, [sheet_pts[2, :], 0]) nx, ny, _ = b.sshape sheet_seed = viscid.RectilinearMeshPoints(sheet_pts.reshape(3, nx, ny)) vx_sheet = viscid.interp_nearest(f['vx'], sheet_seed) try: if not plot2d: raise ImportError from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt vlt.clf() vlt.plot(vx_sheet, symmetric=True) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: vlt.show() except ImportError: pass try: if not plot3d: raise ImportError vlab, _ = get_mvi_fig() mesh = vlab.mesh_from_seeds(sheet_seed, scalars=vx_sheet, clim=(-400, 400)) vlab.plot_earth_3d(crd_system=b) vlab.view(azimuth=+90.0 + 45.0, elevation=90.0 - 25.0, distance=30.0, focalpoint=(-10.0, +1.0, +1.0)) vlab.title("RectilinearMeshPoints") vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show(stop=True) except ImportError: pass # 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 _get_sep_pts_bisect(fld, seed, trace_opts=None, min_depth=3, max_depth=7, plot=False, perimeter_check=perimeter_check_bitwise_or, make_3d=True, start_uneven=False, _base_quadrent="", _uneven_mask=0, _first_recurse=True): if len(_base_quadrent) == max_depth: return [_base_quadrent] # causes pylint to complain if trace_opts is None: trace_opts = dict() nx, ny = seed.uv_shape (xlim, ylim) = seed.uv_extent if _first_recurse and start_uneven: _uneven_mask = UNEVEN_MASK if _first_recurse and plot: from viscid.plot import vlab from viscid.plot import vpyplot as vlt vlt.clf() _, all_topo = viscid.calc_streamlines(fld, seed, **trace_opts) vlt.plot(np.bitwise_and(all_topo, 15), show=False) verts, arr = seed.wrap_mesh(all_topo.data) vlab.mesh(verts[0], verts[1], verts[2], scalars=arr, opacity=0.75) # quadrents and lines are indexed as follows... # directions are counter clackwise around the quadrent with # lower index (which matters for lines which are shared among # more than one quadrent, aka, lines 1,2,6,7). Notice that even # numbered lines are horizontal, like the interstate system :) # -<--10-----<-8--- # | ^ ^ # 11 2 9 3 7 # \/ | | # --<-2-----<-6---- # | ^ ^ # 3 0 1 1 5 # \/ | | # ----0->-----4->-- # find low(left), mid(center), and high(right) crds in x and y low_quad = "{0}{1:x}".format(_base_quadrent, 0 | _uneven_mask) high_quad = "{0}{1:x}".format(_base_quadrent, 3 | _uneven_mask) xl, xm, yl, ym = _quadrent_limits(low_quad, xlim, ylim) _, xh, _, yh = _quadrent_limits(high_quad, xlim, ylim) segsx, segsy = [None] * 12, [None] * 12 topo = [None] * 12 nxm, nym = nx // 2, ny // 2 # make all the line segments segsx[0], segsy[0] = np.linspace(xl, xm, nxm), np.linspace(yl, yl, nxm) segsx[1], segsy[1] = np.linspace(xm, xm, nym), np.linspace(yl, ym, nym) segsx[2], segsy[2] = np.linspace(xm, xl, nxm), np.linspace(ym, ym, nxm) segsx[3], segsy[3] = np.linspace(xl, xl, nym), np.linspace(ym, yl, nym) segsx[4], segsy[4] = np.linspace(xm, xh, nxm), np.linspace(yl, yl, nxm) segsx[5], segsy[5] = np.linspace(xh, xh, nym), np.linspace(yl, ym, nym) segsx[6], segsy[6] = np.linspace(xh, xm, nxm), np.linspace(ym, ym, nxm) segsx[7], segsy[7] = np.linspace(xh, xh, nym), np.linspace(ym, yh, nym) segsx[8], segsy[8] = np.linspace(xh, xm, nxm), np.linspace(yh, yh, nxm) segsx[9], segsy[9] = np.linspace(xm, xm, nym), np.linspace(ym, yh, nym) segsx[10], segsy[10] = np.linspace(xm, xl, nxm), np.linspace(yh, yh, nxm) segsx[11], segsy[11] = np.linspace(xl, xl, nym), np.linspace(yh, ym, nym) allx = np.concatenate(segsx) ally = np.concatenate(segsy) # print("plot::", _base_quadrent, '|', _uneven_mask, '|', len(allx), len(ally)) pts3d = seed.to_3d(seed.uv_to_local(np.array([allx, ally]))) _, all_topo = viscid.calc_streamlines(fld, pts3d, **trace_opts) topo[0] = all_topo[:len(segsx[0])] cnt = len(topo[0]) for i, segx in zip(count(1), segsx[1:]): topo[i] = all_topo[cnt:cnt + len(segx)] # print("??", i, cnt, cnt + len(segx), np.bitwise_and.reduce(topo[i])) cnt += len(topo[i]) # assemble the lines into the four quadrents quad_topo = [None] * 4 # all arrays snip off the last element since those are # duplicated by the next line... reversed arrays do the # snipping with -1:0:-1 quad_topo[0] = np.concatenate( [topo[0][:-1], topo[1][:-1], topo[2][:-1], topo[3][:-1]]) quad_topo[1] = np.concatenate( [topo[4][:-1], topo[5][:-1], topo[6][:-1], topo[1][-1:0:-1]]) quad_topo[2] = np.concatenate( [topo[2][-1:0:-1], topo[9][:-1], topo[10][:-1], topo[11][:-1]]) quad_topo[3] = np.concatenate( [topo[6][-1:0:-1], topo[7][:-1], topo[8][:-1], topo[9][-1:0:-1]]) # now that the quad arrays are populated, decide which quadrents # still contain the separator (could be > 1) required_uneven_subquads = False ret = [] for i in range(4): if perimeter_check(quad_topo[i]): next_quad = "{0}{1:x}".format(_base_quadrent, i | _uneven_mask) subquads = _get_sep_pts_bisect(fld, seed, trace_opts=trace_opts, min_depth=min_depth, max_depth=max_depth, plot=plot, _base_quadrent=next_quad, _uneven_mask=0, _first_recurse=False) ret += subquads if len(ret) == 0: perimeter = np.concatenate([ topo[0][::-1], topo[4][::-1], topo[5][::-1], topo[7][::-1], topo[8][::-1], topo[10][::-1], topo[11][::-1], topo[3][::-1] ]) if _uneven_mask: if len(_base_quadrent) > min_depth: print("sep trace issue, but min depth reached: {0} > {1}" "".format(len(_base_quadrent), min_depth)) ret = [_base_quadrent] else: print("sep trace issue, the separator ended prematurely") elif perimeter_check(perimeter): ret = _get_sep_pts_bisect(fld, seed, trace_opts=trace_opts, min_depth=min_depth, max_depth=max_depth, plot=plot, _base_quadrent=_base_quadrent, _uneven_mask=UNEVEN_MASK, _first_recurse=False) required_uneven_subquads = True if plot and not required_uneven_subquads: from viscid.plot import vlab from matplotlib import pyplot as plt from viscid.plot import vpyplot as vlt _pts3d = seed.to_3d(seed.uv_to_local(np.array([allx, ally]))) vlab.points3d(_pts3d[0], _pts3d[1], _pts3d[2], all_topo.data.reshape(-1), scale_mode='none', scale_factor=0.02) plt.scatter(allx, ally, color=np.bitwise_and(all_topo, 15), vmin=0, vmax=15, marker='o', edgecolor='y', s=40) if _first_recurse: # turn quadrent strings into locations xc = np.empty(len(ret)) yc = np.empty(len(ret)) for i, r in enumerate(ret): xc[i], yc[i] = _quadrent_center(r, xlim, ylim) pts_uv = np.array([xc, yc]) if plot: from viscid.plot import vlab from matplotlib import pyplot as plt from viscid.plot import vpyplot as vlt plt.plot(pts_uv[0], pts_uv[1], "y*", ms=20, markeredgecolor='k', markeredgewidth=1.0) vlt.show(block=False) vlab.show(stop=True) # return seed.to_3d(seed.uv_to_local(pts_uv)) # if pts_uv.size == 0: # return None if make_3d: return seed.uv_to_3d(pts_uv) else: return pts_uv else: return ret
def topology_bitor_clusters(fld, min_depth=1, max_depth=10, multiple=True, plot=False, sep_val=streamline.TOPOLOGY_MS_SEPARATOR, mask_limit=0b1111, periodic="00", pt_bnds=()): """Find separator as intersection of all global topologies Neighbors are bitwise ORed until at least one value matches `sep_val` which is presumably (Close | Open N | Open S | SW). This happens between min_depth and max_depth times, where the resolution of each iteration is reduced by a factor of two, ie, worst case 2**(max_depth). Args: fld (Field): Topology (bitmask) as a field min_depth (int): Iterate at least this many times max_depth (int): Iterate at most this many times multiple (bool): passed to :py:func:`viscid.cluster` sep_val (int): Value of bitmask that indicates a separator plot (bool): Make a 2D plot of Fld and the sep candidates mask_limit (int): if > 0, then bitmask fld with mask_limit, i.e., fld = fld & mask_limit (bitwise and) periodic (sequence): indicate whether that direction is periodic, and if so, whether the coordinate arrays are overlapped or not. Values can be True, False, or '+'. '+' indicates that x[0] and x[-1] are not colocated, so assume they're dx apart where dx = x[-1] - x[-2]. pt_bnd (sequence): Boundaries that come to a point, i.e., all values along that boundary are neighbors such as the poles of a sphere. Specified like "0-" for lower boundary of dimension 0 or "1+" for the upper boundary of dimension 1. Returns: ndarray: 2xN for N clusters of separator points in the same coordinates as `fld` """ pd = [False if pi == "0" else bool(pi) for pi in periodic] fld = fld.slice_reduce(":") if mask_limit: fld = np.bitwise_and(fld, mask_limit) a = fld.data x, y = fld.get_crds() for i in range(max_depth): if pd[0]: a[(0, -1), :] |= a[(-1, 0), :] if pd[1]: a[:, (0, -1)] |= a[:, (-1, 0)] a = ( a[:-1, :-1] | a[:-1, 1:] | # pylint: disable=bad-whitespace a[1:, :-1] | a[1:, 1:]) # pylint: disable=bad-whitespace x = 0.5 * (x[1:] + x[:-1]) y = 0.5 * (y[1:] + y[:-1]) # bitwise_or an entire bounary if all points are neighbors, like # at the poles of a sphere for bnd in pt_bnds: slc = [slice(None), slice(None)] slc[int(bnd[0])] = -1 if bnd[1] == "+" else 0 a[slc] = np.bitwise_or.reduce(a[slc]) indx, indy = np.where(a == sep_val) if i + 1 >= min_depth and len(indx): break pts = viscid.cluster(indx, indy, x, y, multiple=multiple, periodic=periodic) if plot: from matplotlib import pyplot as plt from viscid.plot import vpyplot as vlt vlt.clf() ax0 = vlt.subplot(121) vlt.plot(fld, title=True) vlt.subplot(122, sharex=ax0, sharey=ax0) or_fld = viscid.arrays2field((x, y), a, name="OR") vlt.plot(or_fld, title=True) _x, _y = or_fld.get_crds() plt.plot(_x[indx], _y[indy], 'ko') plt.plot(pts[0], pts[1], 'y^') plt.show() return pts
def _get_sep_pts_bisect(fld, seed, trace_opts=None, min_depth=3, max_depth=7, plot=False, perimeter_check=perimeter_check_bitwise_or, make_3d=True, start_uneven=False, _base_quadrent="", _uneven_mask=0, _first_recurse=True): if len(_base_quadrent) == max_depth: return [_base_quadrent] # causes pylint to complain if trace_opts is None: trace_opts = dict() nx, ny = seed.uv_shape (xlim, ylim) = seed.uv_extent if _first_recurse and start_uneven: _uneven_mask = UNEVEN_MASK if _first_recurse and plot: from viscid.plot import vlab from viscid.plot import vpyplot as vlt vlt.clf() _, all_topo = viscid.calc_streamlines(fld, seed, **trace_opts) vlt.plot(np.bitwise_and(all_topo, 15), show=False) verts, arr = seed.wrap_mesh(all_topo.data) vlab.mesh(verts[0], verts[1], verts[2], scalars=arr, opacity=0.75) # quadrents and lines are indexed as follows... # directions are counter clackwise around the quadrent with # lower index (which matters for lines which are shared among # more than one quadrent, aka, lines 1,2,6,7). Notice that even # numbered lines are horizontal, like the interstate system :) # -<--10-----<-8--- # | ^ ^ # 11 2 9 3 7 # \/ | | # --<-2-----<-6---- # | ^ ^ # 3 0 1 1 5 # \/ | | # ----0->-----4->-- # find low(left), mid(center), and high(right) crds in x and y low_quad = "{0}{1:x}".format(_base_quadrent, 0 | _uneven_mask) high_quad = "{0}{1:x}".format(_base_quadrent, 3 | _uneven_mask) xl, xm, yl, ym = _quadrent_limits(low_quad, xlim, ylim) _, xh, _, yh = _quadrent_limits(high_quad, xlim, ylim) segsx, segsy = [None] * 12, [None] * 12 topo = [None] * 12 nxm, nym = nx //2, ny // 2 # make all the line segments segsx[0], segsy[0] = np.linspace(xl, xm, nxm), np.linspace(yl, yl, nxm) segsx[1], segsy[1] = np.linspace(xm, xm, nym), np.linspace(yl, ym, nym) segsx[2], segsy[2] = np.linspace(xm, xl, nxm), np.linspace(ym, ym, nxm) segsx[3], segsy[3] = np.linspace(xl, xl, nym), np.linspace(ym, yl, nym) segsx[4], segsy[4] = np.linspace(xm, xh, nxm), np.linspace(yl, yl, nxm) segsx[5], segsy[5] = np.linspace(xh, xh, nym), np.linspace(yl, ym, nym) segsx[6], segsy[6] = np.linspace(xh, xm, nxm), np.linspace(ym, ym, nxm) segsx[7], segsy[7] = np.linspace(xh, xh, nym), np.linspace(ym, yh, nym) segsx[8], segsy[8] = np.linspace(xh, xm, nxm), np.linspace(yh, yh, nxm) segsx[9], segsy[9] = np.linspace(xm, xm, nym), np.linspace(ym, yh, nym) segsx[10], segsy[10] = np.linspace(xm, xl, nxm), np.linspace(yh, yh, nxm) segsx[11], segsy[11] = np.linspace(xl, xl, nym), np.linspace(yh, ym, nym) allx = np.concatenate(segsx) ally = np.concatenate(segsy) # print("plot::", _base_quadrent, '|', _uneven_mask, '|', len(allx), len(ally)) pts3d = seed.to_3d(seed.uv_to_local(np.array([allx, ally]))) _, all_topo = viscid.calc_streamlines(fld, pts3d, **trace_opts) topo[0] = all_topo[:len(segsx[0])] cnt = len(topo[0]) for i, segx in zip(count(1), segsx[1:]): topo[i] = all_topo[cnt:cnt + len(segx)] # print("??", i, cnt, cnt + len(segx), np.bitwise_and.reduce(topo[i])) cnt += len(topo[i]) # assemble the lines into the four quadrents quad_topo = [None] * 4 # all arrays snip off the last element since those are # duplicated by the next line... reversed arrays do the # snipping with -1:0:-1 quad_topo[0] = np.concatenate([topo[0][:-1], topo[1][:-1], topo[2][:-1], topo[3][:-1]]) quad_topo[1] = np.concatenate([topo[4][:-1], topo[5][:-1], topo[6][:-1], topo[1][-1:0:-1]]) quad_topo[2] = np.concatenate([topo[2][-1:0:-1], topo[9][:-1], topo[10][:-1], topo[11][:-1]]) quad_topo[3] = np.concatenate([topo[6][-1:0:-1], topo[7][:-1], topo[8][:-1], topo[9][-1:0:-1]]) # now that the quad arrays are populated, decide which quadrents # still contain the separator (could be > 1) required_uneven_subquads = False ret = [] for i in range(4): if perimeter_check(quad_topo[i]): next_quad = "{0}{1:x}".format(_base_quadrent, i | _uneven_mask) subquads = _get_sep_pts_bisect(fld, seed, trace_opts=trace_opts, min_depth=min_depth, max_depth=max_depth, plot=plot, _base_quadrent=next_quad, _uneven_mask=0, _first_recurse=False) ret += subquads if len(ret) == 0: perimeter = np.concatenate([topo[0][::-1], topo[4][::-1], topo[5][::-1], topo[7][::-1], topo[8][::-1], topo[10][::-1], topo[11][::-1], topo[3][::-1]]) if _uneven_mask: if len(_base_quadrent) > min_depth: print("sep trace issue, but min depth reached: {0} > {1}" "".format(len(_base_quadrent), min_depth)) ret = [_base_quadrent] else: print("sep trace issue, the separator ended prematurely") elif perimeter_check(perimeter): ret = _get_sep_pts_bisect(fld, seed, trace_opts=trace_opts, min_depth=min_depth, max_depth=max_depth, plot=plot, _base_quadrent=_base_quadrent, _uneven_mask=UNEVEN_MASK, _first_recurse=False) required_uneven_subquads = True if plot and not required_uneven_subquads: from viscid.plot import vlab from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt _pts3d = seed.to_3d(seed.uv_to_local(np.array([allx, ally]))) vlab.points3d(_pts3d[0], _pts3d[1], _pts3d[2], all_topo.data.reshape(-1), scale_mode='none', scale_factor=0.02) plt.scatter(allx, ally, color=np.bitwise_and(all_topo, 15), vmin=0, vmax=15, marker='o', edgecolor='y', s=40) if _first_recurse: # turn quadrent strings into locations xc = np.empty(len(ret)) yc = np.empty(len(ret)) for i, r in enumerate(ret): xc[i], yc[i] = _quadrent_center(r, xlim, ylim) pts_uv = np.array([xc, yc]) if plot: from viscid.plot import vlab from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.plot(pts_uv[0], pts_uv[1], "y*", ms=20, markeredgecolor='k', markeredgewidth=1.0) vlt.show(block=False) vlab.show(stop=True) # return seed.to_3d(seed.uv_to_local(pts_uv)) # if pts_uv.size == 0: # return None if make_3d: return seed.uv_to_3d(pts_uv) else: return pts_uv else: return ret
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--notwo", dest='notwo', action="store_true") parser.add_argument("--nothree", dest='nothree', action="store_true") parser.add_argument("--show", "--plot", action="store_true") args = viscid.vutil.common_argparse(parser, default_verb=0) plot2d = not args.notwo plot3d = not args.nothree # plot2d = True # plot3d = True # args.show = True img = np.load(os.path.join(sample_dir, "logo.npy")) x = np.linspace(-1, 1, img.shape[0]) y = np.linspace(-1, 1, img.shape[1]) z = np.linspace(-1, 1, img.shape[2]) logo = viscid.arrays2field([x, y, z], img) if 1: viscid.logger.info('Testing Point with custom local coordinates...') pts = np.vstack([[-1, -0.5, 0, 0.5, 1], [-1, -0.5, 0, 0.5, 1], [ 0, 0.5, 1, 1.5, 2]]) local_crds = viscid.asarray_datetime64([0, 60, 120, 180, 240], conservative=True) seeds = viscid.Point(pts, local_crds=local_crds) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Line...') seeds = viscid.Line([-1, -1, 0], [1, 1, 2], n=5) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Plane...') seeds = viscid.Plane([0.0, 0.0, 0.0], [1, 1, 1], [1, 0, 0], 2, 2, nl=160, nm=170, NL_are_vectors=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: viscid.logger.info('Testing Volume...') seeds = viscid.Volume([-0.8, -0.8, -0.8], [0.8, 0.8, 0.8], n=[64, 64, 3]) # note: can't make a 2d plot of the volume w/o a slice run_test(logo, seeds, plot2d=False, plot3d=plot3d, add_title="3d", show=args.show) if 1: viscid.logger.info('Testing Volume (with ignorable dim)...') seeds = viscid.Volume([-0.8, -0.8, 0.0], [0.8, 0.8, 0.0], n=[64, 64, 1]) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="2d", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (phi, theta)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", show=args.show) if 1: viscid.logger.info('Testing Spherical Sphere (theta, phi)...') seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (phi, theta)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=False) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Cap (theta, phi)...') seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80, pole=[-1, -1, -1], theta_phi=True) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP", view_kwargs=dict(azimuth=180, elevation=180), show=args.show) if 1: viscid.logger.info('Testing Spherical Patch...') seeds = viscid.SphericalPatch(p0=[0, 0, 0], p1=[0, -0, -1], max_alpha=30.0, max_beta=59.9, nalpha=65, nbeta=80, r=0.5, roll=45.0) run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show) if 1: # this spline test is very custom viscid.logger.info('Testing Spline...') try: import scipy.interpolate as interpolate except ImportError: msg = "XFail: ImportError (is scipy installed?)" if plot2d: try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() plt.annotate(msg, xy=(0.3, 0.4), xycoords='axes fraction') plt.savefig(next_plot_fname(__file__, series='2d')) plt.savefig(next_plot_fname(__file__, series='2d')) plt.savefig(next_plot_fname(__file__, series='3d')) if args.show: plt.show() except ImportError: pass else: knots = np.array([[ 0.2, 0.5, 0.0], [-0.2, 0.5, 0.2], [-0.2, 0.0, 0.4], [ 0.2, 0.0, 0.2], [ 0.2, -0.5, 0.0], [-0.2, -0.5, 0.2]]).T seed_name = "Spline" fld = logo seeds = viscid.Spline(knots) seed_pts = seeds.get_points() interp_fld = viscid.interp_trilin(fld, seeds) if plot2d: try: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt plt.clf() vlt.plot(interp_fld) plt.title(seed_name) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: plt.show() plt.clf() from matplotlib import rcParams _ms = rcParams['lines.markersize'] plt.gca().scatter(knots[0, :], knots[1, :], s=(2 * _ms)**2, marker='^', color='y') plt.gca().scatter(seed_pts[0, :], seed_pts[1, :], s=(1.5 * _ms)**2, marker='o', color='k') vlt.plot2d_line(seed_pts, scalars=interp_fld.flat_data, symdir='z') plt.title(seed_name) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: plt.show() except ImportError: pass if plot3d: try: from viscid.plot import vlab _ = get_mvi_fig(offscreen=not args.show) vlab.points3d(knots[0], knots[1], knots[2], color=(1.0, 1.0, 0), scale_mode='none', scale_factor=0.04) p = vlab.points3d(seed_pts[0], seed_pts[1], seed_pts[2], color=(0, 0, 0), scale_mode='none', scale_factor=0.03) vlab.plot_line(seed_pts, scalars=interp_fld.flat_data, tube_radius=0.01) vlab.axes(p) vlab.title(seed_name) vlab.mlab.roll(-90.0) vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show(stop=True) except ImportError: pass if 1: viscid.logger.info('Testing RectilinearMeshPoints...') f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[-1].xdmf')) slc = 'x=-40j:12j, y=-10j:10j, z=-10j:10j' b = f['b'][slc] z = b.get_crd('z') sheet_iz = np.argmin(b['x']**2, axis=2) sheet_pts = b['z=0:1'].get_points() sheet_pts[2, :] = z[sheet_iz].reshape(-1) isphere_mask = np.sum(sheet_pts[:2, :]**2, axis=0) < 5**2 day_mask = sheet_pts[0:1, :] > -1.0 sheet_pts[2, :] = np.choose(isphere_mask, [sheet_pts[2, :], 0]) sheet_pts[2, :] = np.choose(day_mask, [sheet_pts[2, :], 0]) nx, ny, _ = b.sshape sheet_seed = viscid.RectilinearMeshPoints(sheet_pts.reshape(3, nx, ny)) vx_sheet = viscid.interp_nearest(f['vx'], sheet_seed) try: if not plot2d: raise ImportError from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt vlt.clf() vlt.plot(vx_sheet, symmetric=True) plt.savefig(next_plot_fname(__file__, series='2d')) if args.show: vlt.show() except ImportError: pass try: if not plot3d: raise ImportError from viscid.plot import vlab _ = get_mvi_fig(offscreen=not args.show) mesh = vlab.mesh_from_seeds(sheet_seed, scalars=vx_sheet, clim=(-400, 400)) vlab.plot_earth_3d(crd_system=b) vlab.view(azimuth=+90.0 + 45.0, elevation=90.0 - 25.0, distance=30.0, focalpoint=(-10.0, +1.0, +1.0)) vlab.title("RectilinearMeshPoints") vlab.savefig(next_plot_fname(__file__, series='3d')) if args.show: vlab.show(stop=True) except ImportError: pass # 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 topology_bitor_clusters(fld, min_depth=1, max_depth=10, multiple=True, plot=False, sep_val=streamline.TOPOLOGY_MS_SEPARATOR, mask_limit=0b1111, periodic="00", pt_bnds=()): """Find separator as intersection of all global topologies Neighbors are bitwise ORed until at least one value matches `sep_val` which is presumably (Close | Open N | Open S | SW). This happens between min_depth and max_depth times, where the resolution of each iteration is reduced by a factor of two, ie, worst case 2**(max_depth). Args: fld (Field): Topology (bitmask) as a field min_depth (int): Iterate at least this many times max_depth (int): Iterate at most this many times multiple (bool): passed to :py:func:`viscid.cluster` sep_val (int): Value of bitmask that indicates a separator plot (bool): Make a 2D plot of Fld and the sep candidates mask_limit (int): if > 0, then bitmask fld with mask_limit, i.e., fld = fld & mask_limit (bitwise and) periodic (sequence): indicate whether that direction is periodic, and if so, whether the coordinate arrays are overlapped or not. Values can be True, False, or '+'. '+' indicates that x[0] and x[-1] are not colocated, so assume they're dx apart where dx = x[-1] - x[-2]. pt_bnd (sequence): Boundaries that come to a point, i.e., all values along that boundary are neighbors such as the poles of a sphere. Specified like "0-" for lower boundary of dimension 0 or "1+" for the upper boundary of dimension 1. Returns: ndarray: 2xN for N clusters of separator points in the same coordinates as `fld` """ pd = [False if pi == "0" else bool(pi) for pi in periodic] fld = fld.slice_reduce(":") if mask_limit: fld = np.bitwise_and(fld, mask_limit) a = fld.data x, y = fld.get_crds() for i in range(max_depth): if pd[0]: a[(0, -1), :] |= a[(-1, 0), :] if pd[1]: a[:, (0, -1)] |= a[:, (-1, 0)] a = (a[ :-1, :-1] | a[ :-1, 1: ] | # pylint: disable=bad-whitespace a[1: , :-1] | a[1: , 1: ]) # pylint: disable=bad-whitespace x = 0.5 * (x[1:] + x[:-1]) y = 0.5 * (y[1:] + y[:-1]) # bitwise_or an entire bounary if all points are neighbors, like # at the poles of a sphere for bnd in pt_bnds: slc = (slice(None), slice(None)) slc[int(bnd[0])] = -1 if bnd[1] == "+" else 0 a[slc] = np.bitwise_or.reduce(a[slc]) indx, indy = np.where(a == sep_val) if i + 1 >= min_depth and len(indx): break pts = viscid.find_clusters(indx, indy, x, y, multiple=multiple, periodic=periodic) if plot: from viscid.plot import vpyplot as vlt from matplotlib import pyplot as plt vlt.clf() ax0 = vlt.subplot(121) vlt.plot(fld, title=True) vlt.subplot(122, sharex=ax0, sharey=ax0) or_fld = viscid.arrays2field((x, y), a, name="OR") vlt.plot(or_fld, title=True) _x, _y = or_fld.get_crds() plt.plot(_x[indx], _y[indy], 'ko') plt.plot(pts[0], pts[1], 'y^') plt.show() return pts