def _main(): crd_system = 'gse' print( viscid.get_dipole_moment_ang(dip_tilt=45.0, dip_gsm=0.0, crd_system=crd_system)) print( viscid.get_dipole_moment_ang(dip_tilt=0.0, dip_gsm=45.0, crd_system=crd_system)) print( viscid.get_dipole_moment_ang(dip_tilt=45.0, dip_gsm=45.0, crd_system=crd_system)) print("---") ptsNP = np.array([[+2, -2, +2], [+2, -1, +2], [+2, 1, +2], [+2, 2, +2]]).T ptsSP = np.array([[+2, -2, -2], [+2, -1, -2], [+2, 1, -2], [+2, 2, -2]]).T ptsNN = np.array([[-2, -2, +2], [-2, -1, +2], [-2, 1, +2], [-2, 2, +2]]).T ptsSN = np.array([[-2, -2, -2], [-2, -1, -2], [-2, 1, -2], [-2, 2, -2]]).T mapped_ptsNP = dipole_map(ptsNP) mapped_ptsNN = dipole_map(ptsNN) mapped_ptsSP = dipole_map(ptsSP) mapped_ptsSN = dipole_map(ptsSN) try: from viscid.plot import vlab colors1 = np.array([(0.6, 0.2, 0.2), (0.2, 0.2, 0.6), (0.6, 0.6, 0.2), (0.2, 0.6, 0.6)]) colors2 = colors1 * 0.5 vlab.points3d(ptsNP, scale_factor=0.4, color=tuple(colors1[0])) vlab.points3d(ptsNN, scale_factor=0.4, color=tuple(colors1[1])) vlab.points3d(ptsSP, scale_factor=0.4, color=tuple(colors1[2])) vlab.points3d(ptsSN, scale_factor=0.4, color=tuple(colors1[3])) vlab.points3d(mapped_ptsNP, scale_factor=0.4, color=tuple(colors2[0])) vlab.points3d(mapped_ptsNN, scale_factor=0.4, color=tuple(colors2[1])) vlab.points3d(mapped_ptsSP, scale_factor=0.4, color=tuple(colors2[2])) vlab.points3d(mapped_ptsSN, scale_factor=0.4, color=tuple(colors2[3])) b = make_dipole() vlab.plot_lines( viscid.calc_streamlines(b, mapped_ptsNP, ibound=0.5)[0]) vlab.plot_lines( viscid.calc_streamlines(b, mapped_ptsNN, ibound=0.5)[0]) vlab.show() except ImportError: print("Mayavi not installed, no 3D plots", file=sys.stderr)
def _main(): crd_system = 'gse' print(viscid.get_dipole_moment_ang(dip_tilt=45.0, dip_gsm=0.0, crd_system=crd_system)) print(viscid.get_dipole_moment_ang(dip_tilt=0.0, dip_gsm=45.0, crd_system=crd_system)) print(viscid.get_dipole_moment_ang(dip_tilt=45.0, dip_gsm=45.0, crd_system=crd_system)) print("---") ptsNP = np.array([[+2, -2, +2], [+2, -1, +2], [+2, 1, +2], [+2, 2, +2]]).T ptsSP = np.array([[+2, -2, -2], [+2, -1, -2], [+2, 1, -2], [+2, 2, -2]]).T ptsNN = np.array([[-2, -2, +2], [-2, -1, +2], [-2, 1, +2], [-2, 2, +2]]).T ptsSN = np.array([[-2, -2, -2], [-2, -1, -2], [-2, 1, -2], [-2, 2, -2]]).T mapped_ptsNP = dipole_map(ptsNP) mapped_ptsNN = dipole_map(ptsNN) mapped_ptsSP = dipole_map(ptsSP) mapped_ptsSN = dipole_map(ptsSN) try: from viscid.plot import vlab colors1 = np.array([(0.6, 0.2, 0.2), (0.2, 0.2, 0.6), (0.6, 0.6, 0.2), (0.2, 0.6, 0.6)]) colors2 = colors1 * 0.5 vlab.points3d(ptsNP, scale_factor=0.4, color=tuple(colors1[0])) vlab.points3d(ptsNN, scale_factor=0.4, color=tuple(colors1[1])) vlab.points3d(ptsSP, scale_factor=0.4, color=tuple(colors1[2])) vlab.points3d(ptsSN, scale_factor=0.4, color=tuple(colors1[3])) vlab.points3d(mapped_ptsNP, scale_factor=0.4, color=tuple(colors2[0])) vlab.points3d(mapped_ptsNN, scale_factor=0.4, color=tuple(colors2[1])) vlab.points3d(mapped_ptsSP, scale_factor=0.4, color=tuple(colors2[2])) vlab.points3d(mapped_ptsSN, scale_factor=0.4, color=tuple(colors2[3])) b = make_dipole() vlab.plot_lines(viscid.calc_streamlines(b, mapped_ptsNP, ibound=0.5)[0]) vlab.plot_lines(viscid.calc_streamlines(b, mapped_ptsNN, ibound=0.5)[0]) vlab.show() except ImportError: print("Mayavi not installed, no 3D plots", file=sys.stderr)
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) ####### test 5-moment uniform grids gk_uniform = viscid.load_file(os.path.join(sample_dir, 'sample_gkeyll_uniform_q_*.h5')) plt.figure(figsize=(9, 3)) for i, grid in enumerate(gk_uniform.iter_times(":")): plt.subplot2grid((1, 2), (0, i)) vlt.plot(grid['rho_i'], logscale=True, style='contourf', levels=128) seeds = viscid.Line((-1.2, 0, 0), (1.4, 0, 0), 8) b_lines, _ = viscid.calc_streamlines(grid['b'], seeds, method='euler1', max_length=20.0) vlt.plot2d_lines(b_lines, scalars='#000000', symdir='z', linewidth=1.0) plt.title(grid.format_time('.02f')) vlt.auto_adjust_subplots() plt.suptitle("Uniform Gkeyll Dataset") plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() plt.clf() return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) ####### test 5-moment uniform grids gk_uniform = viscid.load_file(os.path.join(sample_dir, 'sample_gkeyll_uniform_q_*.h5')) _, axes = plt.subplots(1, 2, figsize=(9, 3)) for i, grid in enumerate(gk_uniform.iter_times(":")): vlt.plot(grid['rho_i'], logscale=True, style='contourf', levels=128, ax=axes[i]) seeds = viscid.Line((-1.2, 0, 0), (1.4, 0, 0), 8) b_lines, _ = viscid.calc_streamlines(grid['b'], seeds, method='euler1', max_length=20.0) vlt.plot2d_lines(b_lines, scalars='#000000', symdir='z', linewidth=1.0) plt.title(grid.format_time('.02f')) vlt.auto_adjust_subplots() plt.suptitle("Uniform Gkeyll Dataset") plt.savefig(next_plot_fname(__file__)) if args.show: plt.show() plt.clf() return 0
def get_sep_pts_bitor(fld, seed, trace_opts=None, make_3d=True, **kwargs): """bitor topologies to find separator points in uv map from seed Args: fld (VectorField): Magnetic Field seed (viscid.seed.SeedGen): Any Seed generator with a 2d local representation trace_opts (dict): kwargs for calc_streamlines make_3d (bool): convert result from uv to 3d space **kwargs: passed to :py:func:`topology_bitor_clusters` Returns: 3xN ndarray of N separator points in uv space or 3d space depending on the `make_3d` kwarg """ trace_opts = _prep_trace_opt_defaults(trace_opts) topo = viscid.calc_streamlines(fld, seed, **trace_opts)[1] try: pt_bnds = seed.pt_bnds except AttributeError: pt_bnds = () try: periodic = seed.periodic except AttributeError: periodic = "00" kwargs.setdefault("pt_bnds", pt_bnds) kwargs.setdefault("periodic", periodic) pts = topology_bitor_clusters(topo, **kwargs) if make_3d: pts = seed.uv_to_3d(pts) return pts
def get_sep_pts_bitor(fld, seed, trace_opts=None, make_3d=True, **kwargs): """bitor topologies to find separator points in uv map from seed Args: fld (VectorField): Magnetic Field seed (viscid.seed.SeedGen): Any Seed generator with a 2d local representation trace_opts (dict): kwargs for calc_streamlines make_3d (bool): convert result from uv to 3d space **kwargs: passed to :py:func:`topology_bitor_clusters` Returns: 3xN ndarray of N separator points in uv space or 3d space depending on the `make_3d` kwarg """ trace_opts = _prep_trace_opt_defaults(trace_opts) topo = viscid.calc_streamlines(fld, seed, **trace_opts)[1] try: pt_bnds = seed.pt_bnds except AttributeError: pt_bnds = () try: periodic = seed.periodic except AttributeError: periodic = "00" kwargs.setdefault('pt_bnds', pt_bnds) kwargs.setdefault('periodic', periodic) pts = topology_bitor_clusters(topo, **kwargs) if make_3d: pts = seed.uv_to_3d(pts) return pts
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 check(): """Runtime check compiled modules""" import os import sys import numpy as np import viscid ret = 0 check_version() print() ##################################################### # run streamline calculation (checks cython modules) try: cotr = viscid.Cotr(dip_tilt=15.0, dip_gsm=21.0) # pylint: disable=not-callable m = cotr.get_dipole_moment(crd_system='gse') seeds = viscid.seed.Sphere((0.0, 0.0, 0.0), 2.0, pole=-m, ntheta=25, nphi=25, thetalim=(5, 90), philim=(5, 360), phi_endpoint=False) B = viscid.make_dipole(m=m, crd_system='gse', n=(32, 32, 32), l=(-25, -25, -25), h=(25, 25, 25), dtype='f8') lines, _ = viscid.calc_streamlines(B, seeds, ibound=1.0) for line in lines: if np.any(np.isnan(line)): raise ValueError("NaN in line") print("Cython module ran successfully") except Exception as e: print("Cython module has runtime errors.") print(str(e)) ret |= (1 << 0) print() #################################### # load a jrrle file (checks fortran) try: f3d = viscid.load_file( os.path.join(viscid.sample_dir, 'sample_jrrle.3df.*')) _ = np.array(f3d['pp'].data) print("Fortran module ran successfully") except Exception as e: print("Fortran module has runtime errors.") print(str(e)) ret |= (1 << 1) print() return ret
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 main(): parser = argparse.ArgumentParser(description="Test quasi potential") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) b, e = make_arcade(8.0, N=[64, 64, 64]) epar = viscid.project(e, b) epar.pretty_name = "E parallel" ############### # Calculate Xi seeds = viscid.Volume(xl=[-10, 0.0, -10], xh=[10, 0.0, 10], n=[64, 1, 64]) b_lines, _ = viscid.calc_streamlines(b, seeds) xi_dat = viscid.integrate_along_lines(b_lines, e, reduction='dot') xi = seeds.wrap_field(xi_dat, name='xi', pretty_name=r"$\Xi$") ################################ # Make 2D Matplotlib plot of Xi mpl.plot(xi, x=(-10, 10), y=(-10, 10), style='contourf', levels=256, lin=(2e-4, 1.5718)) mpl.plot(xi, x=(-10, 10), y=(-10, 10), style='contour', colors='grey', levels=[0.5, 1.0]) mpl.savefig(next_plot_fname(__file__)) if args.show: mpl.show() ############################################################ # Make 3D mayavi plot of Xi and the 'brightest' field lines # as well as some other field lines for context try: from viscid.plot import mvi except ImportError: xfail("Mayavi not installed") mvi.figure(size=[1200, 800], offscreen=not args.show) inds = np.argsort(xi_dat)[-64:] inds = np.concatenate([inds, np.arange(len(xi_dat))[::71]]) s = mvi.plot_lines(b_lines[inds], scalars=epar, cmap='viridis') mvi.mesh_from_seeds(seeds, scalars=xi, cmap='inferno') mvi.colorbar(s, orientation='horizontal', title=epar.pretty_name) # mvi.streamline(b, scalars=e, seedtype='sphere', seed_resolution=4, # integration_direction='both') oa = mvi.orientation_axes() oa.marker.set_viewport(0.75, 0.75, 1.0, 1.0) mvi.view(roll=0, azimuth=90, elevation=25, distance=30.0, focalpoint=[0, 2, 0]) mvi.savefig(next_plot_fname(__file__)) if args.show: mvi.show()
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 check(): """Runtime check compiled modules""" import os import sys import numpy as np import viscid ret = 0 check_version() print() ##################################################### # run streamline calculation (checks cython modules) try: cotr = viscid.Cotr(dip_tilt=15.0, dip_gsm=21.0) # pylint: disable=not-callable m = cotr.get_dipole_moment(crd_system='gse') seeds = viscid.seed.Sphere((0.0, 0.0, 0.0), 2.0, pole=-m, ntheta=25, nphi=25, thetalim=(5, 90), philim=(5, 360), phi_endpoint=False) B = viscid.make_dipole(m=m, crd_system='gse', n=(32, 32, 32), l=(-25, -25, -25), h=(25, 25, 25), dtype='f8') lines, _ = viscid.calc_streamlines(B, seeds, ibound=1.0) for line in lines: if np.any(np.isnan(line)): raise ValueError("NaN in line") print("Cython module ran successfully") except Exception as e: print("Cython module has runtime errors.") print(str(e)) ret |= (1 << 0) print() #################################### # load a jrrle file (checks fortran) try: f3d = viscid.load_file(os.path.join(viscid.sample_dir, 'sample_jrrle.3df.*')) _ = np.array(f3d['pp'].data) print("Fortran module ran successfully") except Exception as e: print("Fortran module has runtime errors.") print(str(e)) ret |= (1 << 1) print() return ret
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 main(): parser = argparse.ArgumentParser(description="Test calc") parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) f3d = viscid.load_file(_viscid_root + '/../sample/sample.3df.[0].xdmf') f_iono = viscid.load_file(_viscid_root + "/../sample/*.iof.[0].xdmf") b = f3d["b"] pp = f3d["pp"] # plot a scalar cut plane of pressure pp_src = mvi.field2source(pp, center='node') scp = mlab.pipeline.scalar_cut_plane(pp_src, plane_orientation='z_axes', transparent=True, opacity=0.5, view_controls=False) scp.implicit_plane.normal = [0, 0, -1] scp.implicit_plane.origin = [0, 0, 0] # i don't know why this log10 doesn't seem to work scp.module_manager.scalar_lut_manager.lut.scale = 'log10' scp.module_manager.scalar_lut_manager.lut_mode = 'Reds' scp.module_manager.scalar_lut_manager.reverse_lut = True scp.module_manager.scalar_lut_manager.show_scalar_bar = True # calculate B field lines && topology in viscid and plot them seeds = viscid.SphericalPatch([0, 0, 0], [2, 0, 1], 30, 15, r=5.0, nalpha=5, nbeta=5) b_lines, topo = viscid.calc_streamlines(b, seeds, ibound=3.5, obound0=[-25, -20, -20], obound1=[15, 20, 20]) mvi.plot_lines(b_lines, scalars=viscid.topology2color(topo)) # Use Mayavi (VTK) to calculate field lines using an interactive seed b_src = mvi.field2source(b, center='node') bsl2 = mlab.pipeline.streamline(b_src, seedtype='sphere', integration_direction='both', seed_resolution=4) bsl2.stream_tracer.maximum_propagation = 20. bsl2.seed.widget.center = [-11, 0, 0] bsl2.seed.widget.radius = 1.0 bsl2.streamline_type = 'tube' bsl2.tube_filter.radius = 0.03 bsl2.stop() # this stop/start was a hack to get something to work? bsl2.start() bsl2.seed.widget.enabled = True # Plot the ionosphere too fac_tot = 1e9 * f_iono['fac_tot'] crd_system = 'gse' m = mvi.plot_ionosphere(fac_tot, crd_system=crd_system, bounding_lat=30.0, vmin=-300, vmax=300, opacity=0.75) m.module_manager.scalar_lut_manager.lut_mode = 'RdBu' m.module_manager.scalar_lut_manager.reverse_lut = True mvi.plot_blue_marble(r=1.0, orientation=(0, 21.5, -45.0)) # now shade the night side with a transparent black hemisphere mvi.plot_earth_3d(radius=1.01, crd_system="gse", night_only=True, opacity=0.5) mlab.axes(pp_src, nb_labels=5) mlab.orientation_axes() mvi.resize([1200, 800]) mlab.view(azimuth=40, elevation=70, distance=35.0, focalpoint=[-3, 0, 0]) # # Save Figure # print("saving png") # mvi.mlab.savefig('mayavi_msphere_sample.png') # print("saving x3d") # # x3d files can be turned into COLLADA files with meshlab, and # # COLLADA (.dae) files can be opened in OS X's preview # # # # IMPORTANT: for some reason, using bounding_lat in mvi.plot_ionosphere # # causes a segfault when saving x3d files # # # mvi.mlab.savefig('mayavi_msphere_sample.x3d') # print("done") if args.show: mlab.show()
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") parser.add_argument("--interact", "-i", action="store_true") args = vutil.common_argparse(parser) f3d = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[0].xdmf')) f_iono = viscid.load_file(os.path.join(sample_dir, "sample_xdmf.iof.[0].xdmf")) b = f3d["b"] v = f3d["v"] pp = f3d["pp"] e = f3d["e_cc"] vlab.figure(size=(1280, 800), offscreen=not args.show) ########################################################## # make b a dipole inside 3.1Re and set e = 0 inside 4.0Re cotr = viscid.Cotr(time='1990-03-21T14:48', dip_tilt=0.0) # pylint: disable=not-callable moment = cotr.get_dipole_moment(crd_system=b) isphere_mask = viscid.make_spherical_mask(b, rmax=3.1) viscid.fill_dipole(b, m=moment, mask=isphere_mask) e_mask = viscid.make_spherical_mask(b, rmax=4.0) viscid.set_in_region(e, 0.0, alpha=0.0, mask=e_mask, out=e) ###################################### # plot a scalar cut plane of pressure pp_src = vlab.field2source(pp, center='node') scp = vlab.scalar_cut_plane(pp_src, plane_orientation='z_axes', opacity=0.5, transparent=True, view_controls=False, cmap="inferno", logscale=True) scp.implicit_plane.normal = [0, 0, -1] scp.implicit_plane.origin = [0, 0, 0] scp.enable_contours = True scp.contour.filled_contours = True scp.contour.number_of_contours = 64 cbar = vlab.colorbar(scp, title=pp.name, orientation='vertical') cbar.scalar_bar_representation.position = (0.01, 0.13) cbar.scalar_bar_representation.position2 = (0.08, 0.76) ###################################### # plot a vector cut plane of the flow vcp = vlab.vector_cut_plane(v, scalars=pp_src, plane_orientation='z_axes', view_controls=False, mode='arrow', cmap='Greens_r') vcp.implicit_plane.normal = [0, 0, -1] vcp.implicit_plane.origin = [0, 0, 0] ############################## # plot very faint isosurfaces vx_src = vlab.field2source(v['x'], center='node') iso = vlab.iso_surface(vx_src, contours=[0.0], opacity=0.008, cmap='Pastel1') ############################################################## # calculate B field lines && topology in Viscid and plot them seedsA = viscid.SphericalPatch([0, 0, 0], [2, 0, 1], 30, 15, r=5.0, nalpha=5, nbeta=5) seedsB = viscid.SphericalPatch([0, 0, 0], [1.9, 0, -20], 30, 15, r=5.0, nalpha=1, nbeta=5) seeds = np.concatenate([seedsA, seedsB], axis=1) b_lines, topo = viscid.calc_streamlines(b, seeds, ibound=3.5, obound0=[-25, -20, -20], obound1=[15, 20, 20], wrap=True) vlab.plot_lines(b_lines, scalars=viscid.topology2color(topo)) ###################################################################### # plot a random circle at geosynchronus orbit with scalars colored # by the Matplotlib viridis color map, just because we can; this is # a useful toy for debugging circle = viscid.Circle(p0=[0, 0, 0], r=6.618, n=128, endpoint=True) scalar = np.sin(circle.as_local_coordinates().get_crd('phi')) surf = vlab.plot_line(circle.get_points(), scalars=scalar, clim=0.8, cmap="Spectral_r") ###################################################################### # Use Mayavi (VTK) to calculate field lines using an interactive seed # These field lines are colored by E parallel epar = viscid.project(e, b) epar.name = "Epar" bsl2 = vlab.streamline(b, epar, seedtype='plane', seed_resolution=4, integration_direction='both', clim=(-0.05, 0.05)) # now tweak the VTK streamlines bsl2.stream_tracer.maximum_propagation = 20. bsl2.seed.widget.origin = [-11, -5.0, -2.0] bsl2.seed.widget.point1 = [-11, 5.0, -2.0] bsl2.seed.widget.point2 = [-11.0, -5.0, 2.0] bsl2.streamline_type = 'tube' bsl2.tube_filter.radius = 0.03 bsl2.stop() # this stop/start was a hack to get something to update bsl2.start() bsl2.seed.widget.enabled = False cbar = vlab.colorbar(bsl2, title=epar.name, label_fmt='%.3f', orientation='horizontal') cbar.scalar_bar_representation.position = (0.15, 0.01) cbar.scalar_bar_representation.position2 = (0.72, 0.10) ############################################################### # Make a contour at the open-closed boundary in the ionosphere seeds_iono = viscid.Sphere(r=1.063, pole=-moment, ntheta=256, nphi=256, thetalim=(0, 180), philim=(0, 360), crd_system=b) _, topo_iono = viscid.calc_streamlines(b, seeds_iono, ibound=1.0, nr_procs='all', output=viscid.OUTPUT_TOPOLOGY) topo_iono = np.log2(topo_iono) m = vlab.mesh_from_seeds(seeds_iono, scalars=topo_iono, opacity=1.0, clim=(0, 3), color=(0.992, 0.445, 0.0)) m.enable_contours = True m.actor.property.line_width = 4.0 m.contour.number_of_contours = 4 #################################################################### # Plot the ionosphere, note that the sample data has the ionosphere # at a different time, so the open-closed boundary found above # will not be consistant with the field aligned currents fac_tot = 1e9 * f_iono['fac_tot'] m = vlab.plot_ionosphere(fac_tot, bounding_lat=30.0, vmin=-300, vmax=300, opacity=0.75, rotate=cotr, crd_system=b) m.actor.property.backface_culling = True ######################################################################## # Add some markers for earth, i.e., real earth, and dayside / nightside # representation vlab.plot_blue_marble(r=1.0, lines=False, ntheta=64, nphi=128, rotate=cotr, crd_system=b) # now shade the night side with a transparent black hemisphere vlab.plot_earth_3d(radius=1.01, night_only=True, opacity=0.5, crd_system=b) #################### # Finishing Touches # vlab.axes(pp_src, nb_labels=5) oa = vlab.orientation_axes() oa.marker.set_viewport(0.75, 0.75, 1.0, 1.0) # note that resize won't work if the current figure has the # off_screen_rendering flag set # vlab.resize([1200, 800]) vlab.view(azimuth=45, elevation=70, distance=35.0, focalpoint=[-2, 0, 0]) ############## # Save Figure # print("saving png") # vlab.savefig('mayavi_msphere_sample.png') # print("saving x3d") # # x3d files can be turned into COLLADA files with meshlab, and # # COLLADA (.dae) files can be opened in OS X's preview # # # # IMPORTANT: for some reason, using bounding_lat in vlab.plot_ionosphere # # causes a segfault when saving x3d files # # # vlab.savefig('mayavi_msphere_sample.x3d') # print("done") vlab.savefig(next_plot_fname(__file__)) ########################### # Interact Programatically if args.interact: vlab.interact() ####################### # Interact Graphically if args.show: vlab.show() try: vlab.mlab.close() except AttributeError: pass 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 _follow_fluid_step(i, dt, grid, root_seeds, plot_function, stream_opts, speed_scale): direction = int(dt / np.abs(dt)) if direction >= 0: sl_direction = streamline.DIR_FORWARD else: sl_direction = streamline.DIR_BACKWARD logger.info("working on timestep {0} {1}".format(i, grid.time)) v = grid["v"] logger.debug("finished reading V field") logger.debug("calculating new streamline positions") flow_lines = calc_streamlines(v, root_seeds, output=viscid.OUTPUT_STREAMLINES, stream_dir=sl_direction, **stream_opts)[0] logger.debug("done with that, now i'm plotting...") plot_function(i, grid, v, flow_lines, root_seeds) ############################################################ # now recalculate the seed positions for the next timestep logger.debug("finding new seed positions...") root_pts = root_seeds.genr_points() valid_pt_inds = [] for i in range(root_pts.shape[1]): valid_pt = True # get the index of the root point in teh 2d flow line array # dist = flow_lines[i] - root_pts[:, [i]] # root_ind = np.argmin(np.sum(dist**2, axis=0)) # print("!!!", root_pts[:, i], "==", flow_lines[i][:, root_ind]) # interpolate velocity onto teh flow line, and get speed too v_interp = cycalc.interp_trilin(v, seed.Point(flow_lines[i])) speed = np.sqrt(np.sum(v_interp * v_interp, axis=1)) # this is a super slopy way to integrate velocity # keep marching along the flow line until we get to the next timestep t = 0.0 ind = 0 if direction < 0: flow_lines[i] = flow_lines[i][:, ::-1] speed = speed[::-1] while t < np.abs(dt): ind += 1 if ind >= len(speed): # set valid_pt to True if you want to keep that point for # future time steps, but most likely if we're here, the seed # has gone out of our region of interest ind = len(speed) - 1 valid_pt = False logger.info("OOPS: ran out of streamline, increase " "max_length when tracing flow lines if this " "is unexpected") break t += stream_opts["ds0"] / (speed_scale * speed[ind]) root_pts[:, i] = flow_lines[i][:, ind] if valid_pt: valid_pt_inds.append(i) # remove seeds that have flown out of our region of interest # (aka, beyond the flow line we drew) root_pts = root_pts[:, valid_pt_inds] logger.debug("ok, done with all that :)") return root_pts
def _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 follow_fluid(dset, initial_seeds, time_slice=slice(None), curator=None, callback=default_fluid_callback, speed_scale=1.0, dt=None, tstart=None, tstop=None, duration=None, dt_interp=None, v_key='v', anc_keys=(), fld_slc=Ellipsis, stream_opts={}, callback_kwargs={}): """Trace fluid elements Note: you want speed_scale if say V is in km/s and x/y/z is in Re ;) Parameters: vfile: a vFile object that we can call iter_times on time_slice: string, slice notation, like 1200:2400:1 initial_seeds: any SeedGen object plot_function: function that is called each time step, arguments should be exactly: (i [int], grid, v [Vector Field], v_lines [result of streamline trace], root_seeds [SeedGen]) stream_opts: must have ds0 and max_length, maxit will be automatically calculated Returns: root points after following the fluid """ curator = SeedCurator() if curator is None else curator grids = [grid for grid in dset.iter_times(time_slice)] times = [g.time for g in grids] slc_range = dset.tslc_range(time_slice) time_slice_dir = np.sign(times[-1] - times[0]).astype('f') slice_min_dt = 1.0 if len(times) <= 1 else np.min(np.abs(np.diff(times))) # figure out direction (forward / backward) if tstart is not None and tstop is not None: tdir = np.sign(tstop - tstart).astype('f') elif (dt is not None and dt < 0) or (duration is not None and duration < 0): tdir = -1.0 else: tdir = 1.0 if time_slice_dir == 0.0 else time_slice_dir # enforce that grids and times arrays are reordered to match tdir if (tdir > 0 and time_slice_dir < 0) or (tdir < 0 and time_slice_dir > 0): grids = grids[::-1] times = times[::-1] slc_range = slc_range[::-1] time_slice_dir *= -1 # set tstart and tstop if they're not already given if tstart is None: tstart = slc_range[0] if tstop is None: if duration is not None: tstop = tstart + tdir * np.abs(duration) else: tstop = slc_range[1] # set dt if they're not given dt = np.abs(dt) if dt is not None else slice_min_dt dt_interp = np.abs(dt_interp) if dt_interp is not None else dt # ------ main loop fld_keys = [v_key] + list(anc_keys) times = np.array(times) t = tstart if np.any(np.sign(np.diff(times)) != tdir): raise RuntimeError("times is not monotonic") i = 0 seeds = initial_seeds.get_points() while tdir * (t - tstop) <= 0.0: idx0 = max(np.sum(tdir * (times - t) < 0.0) - 1, 0) idx1 = min(idx0 + 1, len(grids) - 1) time0, grid0 = times[idx0], grids[idx0] time1, grid1 = times[idx1], grids[idx1] frac_interp = 0.0 if time0 == time1 else (t - time0) / (time1 - time0) # get / calculate fields for each key at the current time if grid0 is grid1: flds = [grid0[key] for key in fld_keys] else: a = frac_interp b = 1.0 - frac_interp flds = [viscid.axpby(a, grid0[k][fld_slc], b, grid1[k][fld_slc]) for k in fld_keys] anc_fields = OrderedDict([(k, v) for k, v in zip(anc_keys, flds[1:])]) t_next_interp = t + tdir * dt_interp while tdir * (t - t_next_interp) < 0 and tdir * (t - tstop) <= 0.0: if 'method' not in stream_opts: stream_opts['method'] = 'rk45' vpaths = viscid.calc_streamlines(tdir * speed_scale * flds[0], seeds, max_t=dt, output=viscid.OUTPUT_STREAMLINES, stream_dir=viscid.DIR_FORWARD, **stream_opts)[0] callback(i, t, seeds=seeds, v_field=flds[0], anc_fields=anc_fields, grid0=grid0, grid1=grid1, streamlines=vpaths, **callback_kwargs) i += 1 # prepare seeds for next iteration for iseed in range(seeds.shape[1]): seeds[:, iseed] = vpaths[iseed][:, -1] seeds = curator.update(flds[0], seeds, time=t) t += tdir * dt
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 mvi from viscid.plot import mpl mpl.clf() _, all_topo = viscid.calc_streamlines(fld, seed, **trace_opts) mpl.plot(np.bitwise_and(all_topo, 15), show=False) verts, arr = seed.wrap_mesh(all_topo.data) mvi.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 mvi from viscid.plot import mpl _pts3d = seed.to_3d(seed.uv_to_local(np.array([allx, ally]))) mvi.points3d(_pts3d[0], _pts3d[1], _pts3d[2], all_topo.data.reshape(-1), scale_mode="none", scale_factor=0.02) mpl.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 mvi from viscid.plot import mpl mpl.plt.plot(pts_uv[0], pts_uv[1], "y*", ms=20, markeredgecolor="k", markeredgewidth=1.0) mpl.show(block=False) mvi.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("--show", "--plot", action="store_true") parser.add_argument("--interact", "-i", action="store_true") args = vutil.common_argparse(parser) f3d = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[0].xdmf')) f_iono = viscid.load_file( os.path.join(sample_dir, "sample_xdmf.iof.[0].xdmf")) b = f3d["b"] v = f3d["v"] pp = f3d["pp"] e = f3d["e_cc"] vlab.mlab.options.offscreen = not args.show vlab.figure(size=(1280, 800)) ########################################################## # make b a dipole inside 3.1Re and set e = 0 inside 4.0Re cotr = viscid.Cotr(time='1990-03-21T14:48', dip_tilt=0.0) # pylint: disable=not-callable moment = cotr.get_dipole_moment(crd_system=b) isphere_mask = viscid.make_spherical_mask(b, rmax=3.1) viscid.fill_dipole(b, m=moment, mask=isphere_mask) e_mask = viscid.make_spherical_mask(b, rmax=4.0) viscid.set_in_region(e, 0.0, alpha=0.0, mask=e_mask, out=e) ###################################### # plot a scalar cut plane of pressure pp_src = vlab.field2source(pp, center='node') scp = vlab.scalar_cut_plane(pp_src, plane_orientation='z_axes', opacity=0.5, transparent=True, view_controls=False, cmap="inferno", logscale=True) scp.implicit_plane.normal = [0, 0, -1] scp.implicit_plane.origin = [0, 0, 0] scp.enable_contours = True scp.contour.filled_contours = True scp.contour.number_of_contours = 64 cbar = vlab.colorbar(scp, title=pp.name, orientation='vertical') cbar.scalar_bar_representation.position = (0.01, 0.13) cbar.scalar_bar_representation.position2 = (0.08, 0.76) ###################################### # plot a vector cut plane of the flow vcp = vlab.vector_cut_plane(v, scalars=pp_src, plane_orientation='z_axes', view_controls=False, mode='arrow', cmap='Greens_r') vcp.implicit_plane.normal = [0, 0, -1] vcp.implicit_plane.origin = [0, 0, 0] ############################## # plot very faint isosurfaces vx_src = vlab.field2source(v['x'], center='node') iso = vlab.iso_surface(vx_src, contours=[0.0], opacity=0.008, cmap='Pastel1') ############################################################## # calculate B field lines && topology in Viscid and plot them seedsA = viscid.SphericalPatch([0, 0, 0], [2, 0, 1], 30, 15, r=5.0, nalpha=5, nbeta=5) seedsB = viscid.SphericalPatch([0, 0, 0], [1.9, 0, -20], 30, 15, r=5.0, nalpha=1, nbeta=5) seeds = np.concatenate([seedsA, seedsB], axis=1) b_lines, topo = viscid.calc_streamlines(b, seeds, ibound=3.5, obound0=[-25, -20, -20], obound1=[15, 20, 20], wrap=True) vlab.plot_lines(b_lines, scalars=viscid.topology2color(topo)) ###################################################################### # plot a random circle at geosynchronus orbit with scalars colored # by the Matplotlib viridis color map, just because we can; this is # a useful toy for debugging circle = viscid.Circle(p0=[0, 0, 0], r=6.618, n=128, endpoint=True) scalar = np.sin(circle.as_local_coordinates().get_crd('phi')) surf = vlab.plot_line(circle.get_points(), scalars=scalar, clim=0.8, cmap="Spectral_r") ###################################################################### # Use Mayavi (VTK) to calculate field lines using an interactive seed # These field lines are colored by E parallel epar = viscid.project(e, b) epar.name = "Epar" bsl2 = vlab.streamline(b, epar, seedtype='plane', seed_resolution=4, integration_direction='both', clim=(-0.05, 0.05)) # now tweak the VTK streamlines bsl2.stream_tracer.maximum_propagation = 20. bsl2.seed.widget.origin = [-11, -5.0, -2.0] bsl2.seed.widget.point1 = [-11, 5.0, -2.0] bsl2.seed.widget.point2 = [-11.0, -5.0, 2.0] bsl2.streamline_type = 'tube' bsl2.tube_filter.radius = 0.03 bsl2.stop() # this stop/start was a hack to get something to update bsl2.start() bsl2.seed.widget.enabled = False cbar = vlab.colorbar(bsl2, title=epar.name, label_fmt='%.3f', orientation='horizontal') cbar.scalar_bar_representation.position = (0.15, 0.01) cbar.scalar_bar_representation.position2 = (0.72, 0.10) ############################################################### # Make a contour at the open-closed boundary in the ionosphere seeds_iono = viscid.Sphere(r=1.063, pole=-moment, ntheta=256, nphi=256, thetalim=(0, 180), philim=(0, 360), crd_system=b) _, topo_iono = viscid.calc_streamlines(b, seeds_iono, ibound=1.0, nr_procs='all', output=viscid.OUTPUT_TOPOLOGY) topo_iono = np.log2(topo_iono) m = vlab.mesh_from_seeds(seeds_iono, scalars=topo_iono, opacity=1.0, clim=(0, 3), color=(0.992, 0.445, 0.0)) m.enable_contours = True m.actor.property.line_width = 4.0 m.contour.number_of_contours = 4 #################################################################### # Plot the ionosphere, note that the sample data has the ionosphere # at a different time, so the open-closed boundary found above # will not be consistant with the field aligned currents fac_tot = 1e9 * f_iono['fac_tot'] m = vlab.plot_ionosphere(fac_tot, bounding_lat=30.0, vmin=-300, vmax=300, opacity=0.75, rotate=cotr, crd_system=b) m.actor.property.backface_culling = True ######################################################################## # Add some markers for earth, i.e., real earth, and dayside / nightside # representation vlab.plot_blue_marble(r=1.0, lines=False, ntheta=64, nphi=128, rotate=cotr, crd_system=b) # now shade the night side with a transparent black hemisphere vlab.plot_earth_3d(radius=1.01, night_only=True, opacity=0.5, crd_system=b) #################### # Finishing Touches # vlab.axes(pp_src, nb_labels=5) oa = vlab.orientation_axes() oa.marker.set_viewport(0.75, 0.75, 1.0, 1.0) # note that resize won't work if the current figure has the # off_screen_rendering flag set # vlab.resize([1200, 800]) vlab.view(azimuth=45, elevation=70, distance=35.0, focalpoint=[-2, 0, 0]) ############## # Save Figure # print("saving png") # vlab.savefig('mayavi_msphere_sample.png') # print("saving x3d") # # x3d files can be turned into COLLADA files with meshlab, and # # COLLADA (.dae) files can be opened in OS X's preview # # # # IMPORTANT: for some reason, using bounding_lat in vlab.plot_ionosphere # # causes a segfault when saving x3d files # # # vlab.savefig('mayavi_msphere_sample.x3d') # print("done") vlab.savefig(next_plot_fname(__file__)) ########################### # Interact Programatically if args.interact: vlab.interact() ####################### # Interact Graphically if args.show: vlab.show() try: vlab.mlab.close() except AttributeError: pass return 0
def _main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--show", "--plot", action="store_true") args = vutil.common_argparse(parser) b, e = make_arcade(8.0, N=[64, 64, 64]) epar = viscid.project(e, b) epar.pretty_name = "E parallel" ############### # Calculate Xi seeds = viscid.Volume(xl=[-10, 0.0, -10], xh=[10, 0.0, 10], n=[64, 1, 64]) b_lines, _ = viscid.calc_streamlines(b, seeds) xi_dat = viscid.integrate_along_lines(b_lines, e, reduction='dot') xi = seeds.wrap_field(xi_dat, name='xi', pretty_name=r"$\Xi$") ################################ # Make 2D Matplotlib plot of Xi vlt.plot(xi, x=(-10, 10), y=(-10, 10), style='contourf', levels=256, lin=(2e-4, 1.5718)) vlt.plot(xi, x=(-10, 10), y=(-10, 10), style='contour', colors='grey', levels=[0.5, 1.0]) vlt.savefig(next_plot_fname(__file__)) if args.show: vlt.show() ############################################################ # Make 3D mayavi plot of Xi and the 'brightest' field lines # as well as some other field lines for context try: from viscid.plot import vlab except ImportError: xfail("Mayavi not installed") vlab.figure(size=[1200, 800], offscreen=not args.show) inds = np.argsort(xi_dat)[-64:] inds = np.concatenate([inds, np.arange(len(xi_dat))[::71]]) s = vlab.plot_lines(b_lines[inds], scalars=epar, cmap='viridis') vlab.mesh_from_seeds(seeds, scalars=xi, cmap='inferno') vlab.colorbar(s, orientation='horizontal', title=epar.pretty_name) # vlab.streamline(b, scalars=e, seedtype='sphere', seed_resolution=4, # integration_direction='both') oa = vlab.orientation_axes() oa.marker.set_viewport(0.75, 0.75, 1.0, 1.0) vlab.view(roll=0, azimuth=90, elevation=25, distance=30.0, focalpoint=[0, 2, 0]) vlab.savefig(next_plot_fname(__file__)) if args.show: vlab.show() try: vlab.mlab.close() except AttributeError: pass return 0
def follow_fluid(dset, initial_seeds, time_slice=slice(None), curator=None, callback=default_fluid_callback, speed_scale=1.0, dt=None, tstart=None, tstop=None, duration=None, dt_interp=None, v_key='v', anc_keys=(), fld_slc=Ellipsis, stream_opts={}, callback_kwargs={}): """Trace fluid elements Note: you want speed_scale if say V is in km/s and x/y/z is in Re ;) Parameters: vfile: a vFile object that we can call iter_times on time_slice: string, slice notation, like 1200:2400:1 initial_seeds: any SeedGen object plot_function: function that is called each time step, arguments should be exactly: (i [int], grid, v [Vector Field], v_lines [result of streamline trace], root_seeds [SeedGen]) stream_opts: must have ds0 and max_length, maxit will be automatically calculated Returns: root points after following the fluid """ curator = SeedCurator() if curator is None else curator grids = [grid for grid in dset.iter_times(time_slice)] times = [g.time for g in grids] slc_range = dset.tslc_range(time_slice) time_slice_dir = np.sign(times[-1] - times[0]).astype('f') slice_min_dt = 1.0 if len(times) <= 1 else np.min(np.abs(np.diff(times))) # figure out direction (forward / backward) if tstart is not None and tstop is not None: tdir = np.sign(tstop - tstart).astype('f') elif (dt is not None and dt < 0) or (duration is not None and duration < 0): tdir = -1.0 else: tdir = 1.0 if time_slice_dir == 0.0 else time_slice_dir # enforce that grids and times arrays are reordered to match tdir if (tdir > 0 and time_slice_dir < 0) or (tdir < 0 and time_slice_dir > 0): grids = grids[::-1] times = times[::-1] slc_range = slc_range[::-1] time_slice_dir *= -1 # set tstart and tstop if they're not already given if tstart is None: tstart = slc_range[0] if tstop is None: if duration is not None: tstop = tstart + tdir * np.abs(duration) else: tstop = slc_range[1] # set dt if they're not given dt = np.abs(dt) if dt is not None else slice_min_dt dt_interp = np.abs(dt_interp) if dt_interp is not None else dt # ------ main loop fld_keys = [v_key] + list(anc_keys) times = np.array(times) t = tstart if np.any(np.sign(np.diff(times)) != tdir): raise RuntimeError("times is not monotonic") i = 0 seeds = initial_seeds.get_points() while tdir * (t - tstop) <= 0.0: idx0 = max(np.sum(tdir * (times - t) < 0.0) - 1, 0) idx1 = min(idx0 + 1, len(grids) - 1) time0, grid0 = times[idx0], grids[idx0] time1, grid1 = times[idx1], grids[idx1] frac_interp = 0.0 if time0 == time1 else (t - time0) / (time1 - time0) # get / calculate fields for each key at the current time if grid0 is grid1: flds = [grid0[key] for key in fld_keys] else: a = frac_interp b = 1.0 - frac_interp flds = [ viscid.axpby(a, grid0[k][fld_slc], b, grid1[k][fld_slc]) for k in fld_keys ] anc_fields = OrderedDict([(k, v) for k, v in zip(anc_keys, flds[1:])]) t_next_interp = t + tdir * dt_interp while tdir * (t - t_next_interp) < 0 and tdir * (t - tstop) <= 0.0: if 'method' not in stream_opts: stream_opts['method'] = 'rk45' vpaths = viscid.calc_streamlines(tdir * speed_scale * flds[0], seeds, max_t=dt, output=viscid.OUTPUT_STREAMLINES, stream_dir=viscid.DIR_FORWARD, **stream_opts)[0] callback(i, t, seeds=seeds, v_field=flds[0], anc_fields=anc_fields, grid0=grid0, grid1=grid1, streamlines=vpaths, **callback_kwargs) i += 1 # prepare seeds for next iteration for iseed in range(seeds.shape[1]): seeds[:, iseed] = vpaths[iseed][:, -1] seeds = curator.update(flds[0], seeds, time=t) t += tdir * dt
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