コード例 #1
0
def run_test(fld, seeds, plot2d=True, plot3d=True, add_title="",
             view_kwargs=None, show=False):
    interpolated_fld = viscid.interp_trilin(fld, seeds)
    seed_name = seeds.__class__.__name__
    if add_title:
        seed_name += " " + add_title

    try:
        if not plot2d:
            raise ImportError
        from viscid.plot import mpl
        mpl.plt.clf()
        # mpl.plt.plot(seeds.get_points()[2, :], fld)
        mpl_plot_kwargs = dict()
        if interpolated_fld.is_spherical():
            mpl_plot_kwargs['hemisphere'] = 'north'
        mpl.plot(interpolated_fld, **mpl_plot_kwargs)
        mpl.plt.title(seed_name)

        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

        try:
            mesh = mvi.mesh_from_seeds(seeds, scalars=interpolated_fld)
            mesh.actor.property.backface_culling = True
        except RuntimeError:
            pass

        pts = seeds.get_points()
        p = mvi.points3d(pts[0], pts[1], pts[2], interpolated_fld.flat_data,
                         scale_mode='none', scale_factor=0.02)
        mvi.axes(p)
        mvi.title(seed_name)
        if view_kwargs:
            mvi.view(**view_kwargs)

        mvi.savefig(next_plot_fname(__file__, series='3d'))
        if show:
            mvi.show()
    except ImportError:
        pass
コード例 #2
0
def run_test(_fld, _seeds, plot2d=True, plot3d=True, title="", show=False, **kwargs):
    lines, topo = viscid.calc_streamlines(_fld, _seeds, **kwargs)
    topo_color = viscid.topology2color(topo)

    # downsample lines for plotting
    lines = [line[:, ::8] for line in lines]

    try:
        if not plot2d:
            raise ImportError
        from viscid.plot import 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
コード例 #3
0
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()
コード例 #4
0
ファイル: test_streamline.py プロジェクト: jobejen/Viscid
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
コード例 #5
0
ファイル: mapfield.py プロジェクト: KristoforMaynard/Viscid
def _main():
    try:
        # raise ImportError
        from viscid.plot import mvi

        _HAS_MVI = True
    except ImportError:
        _HAS_MVI = False

    def _test(_p1, _p2, r1=None, r2=None, color=(0.8, 0.8, 0.8)):
        if r1 is not None:
            _p1 = r1 * np.asarray(_p1) / np.linalg.norm(_p1)
        if r2 is not None:
            _p2 = r2 * np.asarray(_p2) / np.linalg.norm(_p2)
        circ = great_circle(_p1, _p2)
        if not np.all(np.isclose(circ[:, 0], _p1)):
            print("!! great circle error P1:", _p1, ", P2:", _p2)
            print("             first_point:", circ[:, 0], "!= P1")
        if not np.all(np.isclose(circ[:, -1], _p2)):
            print("!! great circle error P1:", _p1, ", P2:", _p2)
            print("              last_point:", circ[:, -1], "!= P2")

        if _HAS_MVI:
            mvi.plot_lines([circ], tube_radius=0.02, color=color)

    print("TEST 1")
    _test([1, 0, 0], [0, 1, 0], r1=1.0, r2=1.0, color=(0.8, 0.8, 0.2))
    print("TEST 2")
    _test([1, 0, 0], [-1, 0, 0], r1=1.0, r2=1.0, color=(0.2, 0.8, 0.8))
    print("TEST 3")
    _test([1, 1, 0.01], [-1, -1, 0.01], r1=1.0, r2=1.5, color=(0.8, 0.2, 0.8))

    print("TEST 4")
    _test([-0.9947146, 1.3571029, 2.6095123], [-0.3371437, -1.5566425, 2.6634643], color=(0.8, 0.2, 0.2))
    print("TEST 5")
    _test([0.9775307, -1.3741084, 2.6030273], [0.3273931, 1.5570284, 2.6652965], color=(0.2, 0.2, 0.8))

    if _HAS_MVI:
        mvi.plot_blue_marble(r=1.0, lines=False, ntheta=64, nphi=128)
        mvi.plot_earth_3d(radius=1.01, night_only=True, opacity=0.5)
        mvi.show()

    return 0
コード例 #6
0
def _main():
    f = viscid.load_file("$WORK/xi_fte_001/*.3d.[4050f].xdmf")
    mp = get_mp_info(f['pp'], f['b'], f['j'], f['e_cc'], fit='mp_xloc',
                     slc="x=6.5f:10.5f, y=-4f:4f, z=-4.8f:3f", cache=False)

    y, z = mp['pp_max_xloc'].meshgrid_flat(prune=True)
    x = mp['pp_max_xloc'].data.reshape(-1)

    Y, Z = mp['pp_max_xloc'].meshgrid(prune=True)
    x2 = paraboloid(Y, Z, *mp['paraboloid'][0])

    skip = 117
    n = paraboloid_normal(Y, Z, *mp['paraboloid'][0]).reshape(3, -1)[:, ::skip]

    minvar_y = Y.reshape(-1)[::skip]
    minvar_z = Z.reshape(-1)[::skip]
    minvar_n = np.zeros([3, len(minvar_y)])
    for i in range(minvar_n.shape[0]):
        p0 = [0.0, minvar_y[i], minvar_z[i]]
        p0[0] = mp['pp_max_xloc']['y={0[0]}f, z={0[1]}f'.format(p0)]
        minvar_n[:, i] = viscid.find_minvar_lmn_around(f['b'], p0, l=2.0, n=64)[2, :]

    # 2d plots, normals don't look normal in the matplotlib projection
    if False:  # pylint: disable=using-constant-test
        from viscid.plot import mpl

        normals = paraboloid_normal(Y, Z, *mp['paraboloid'][0])
        p0 = np.array([x2, Y, Z]).reshape(3, -1)
        p1 = p0 + normals.reshape(3, -1)

        mpl.scatter_3d(np.vstack([x, y, z])[:, ::skip], equal=True)
        for i in range(0, p0.shape[1], skip):
            mpl.plt.gca().plot([p0[0, i], p1[0, i]],
                               [p0[1, i], p1[1, i]],
                               [p0[2, i], p1[2, i]], color='c')
        # z2 = _ellipsiod(X, Y, *popt)
        mpl.plt.gca().plot_surface(Y, Z, x2, color='r')
        mpl.show()

    # mayavi 3d plots, normals look better here
    if True:  # pylint: disable=using-constant-test
        from viscid.plot import mvi
        mvi.points3d(x[::skip], y[::skip], z[::skip], scale_factor=0.25,
                     color=(0.0, 0.0, 1.0))

        mp_width = mp['mp_width']['x=0']
        mp_sheath_edge = mp['mp_sheath_edge']['x=0']
        mp_sphere_edge = mp_sheath_edge - mp_width

        mvi.mesh(x2, Y, Z, scalars=mp_width.data)
        mvi.mesh(mp_sheath_edge.data, Y, Z, opacity=0.75, color=(0.75, ) * 3)
        mvi.mesh(mp_sphere_edge.data, Y, Z, opacity=0.75, color=(0.75, ) * 3)

        n = paraboloid_normal(Y, Z, *mp['paraboloid'][0]).reshape(3, -1)[:, ::skip]
        mvi.quiver3d(x2.reshape(-1)[::skip],
                     Y.reshape(-1)[::skip],
                     Z.reshape(-1)[::skip],
                     n[0], n[1], n[2], color=(1, 0, 0))
        mvi.quiver3d(x2.reshape(-1)[::skip],
                     Y.reshape(-1)[::skip],
                     Z.reshape(-1)[::skip],
                     minvar_n[0], minvar_n[1], minvar_n[2], color=(0, 0, 1))
        mvi.show()
コード例 #7
0
def main():
    parser = argparse.ArgumentParser(description="Test calc")
    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(sample_dir + '/sample_xdmf.3d.[0].xdmf')
    f_iono = viscid.load_file(sample_dir + "/sample_xdmf.iof.[0].xdmf")

    b = f3d["b"]
    v = f3d["v"]
    pp = f3d["pp"]
    e = f3d["e_cc"]

    mvi.figure(size=(1200, 800), offscreen=not args.show)

    ##########################################################
    # make b a dipole inside 3.1Re and set e = 0 inside 4.0Re
    cotr = viscid.Cotr(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 = mvi.field2source(pp, center='node')
    scp = mvi.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]
    cbar = mvi.colorbar(scp, title=pp.name, orientation='vertical')

    ######################################
    # plot a vector cut plane of the flow
    vcp = mvi.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
    iso = mvi.iso_surface(pp_src, contours=5, opacity=0.1, cmap=False)

    ##############################################################
    # 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], wrap=True)
    mvi.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 = mvi.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 = mvi.streamline(b, epar, seedtype='sphere', 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.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 update
    bsl2.start()
    bsl2.seed.widget.enabled = False

    cbar = mvi.colorbar(bsl2, title=epar.name, orientation='horizontal')
    cbar.scalar_bar_representation.position = (0.2, 0.01)
    cbar.scalar_bar_representation.position2 = (0.6, 0.14)

    ###############################################################
    # 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 = mvi.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

    ####################################################################
    # 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 = mvi.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
    mvi.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
    mvi.plot_earth_3d(radius=1.01, night_only=True, opacity=0.5, crd_system=b)

    ####################
    # Finishing Touches
    # mvi.axes(pp_src, nb_labels=5)
    oa = mvi.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
    # mvi.resize([1200, 800])
    mvi.view(azimuth=45, elevation=70, distance=35.0, focalpoint=[-2, 0, 0])

    ##############
    # Save Figure

    # print("saving png")
    # mvi.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.savefig('mayavi_msphere_sample.x3d')
    # print("done")

    mvi.savefig(next_plot_fname(__file__))

    ###########################
    # Interact Programatically
    if args.interact:
        mvi.interact()

    #######################
    # Interact Graphically
    if args.show:
        mvi.show()
コード例 #8
0
def main():
    parser = argparse.ArgumentParser()
    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(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(img, [x, y, z])

    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(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 viscid.plot import mpl
            mpl.clf()
            mpl.plot(vx_sheet, symmetric=True)
            mpl.plt.savefig(next_plot_fname(__file__, series='2d'))
            if args.show:
                mpl.show()
        except ImportError:
            pass

        try:
            if not plot3d:
                raise ImportError
            from viscid.plot import mvi
            mvi.clf()
            mesh = mvi.mesh_from_seeds(sheet_seed, scalars=vx_sheet,
                                       clim=(-400, 400))
            mvi.plot_earth_3d(crd_system=b)
            mvi.view(azimuth=+90.0 + 45.0, elevation=90.0 - 25.0,
                     distance=30.0, focalpoint=(-10.0, +1.0, +1.0))

            mvi.title("RectilinearMeshPoints")
            mvi.savefig(next_plot_fname(__file__, series='3d'))
            if args.show:
                mvi.show()

        except ImportError:
            pass

    return 0
コード例 #9
0
def main():
    mhd_type = "C"
    make_plots = 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 = 2e-6
    elif mhd_type in ("F", "FORTRAN"):
        f = viscid.load_file("$WORK/tmedium3/*.3df.[-1]")
        catol = 1e-8
        rtol = 7e-2
    else:
        raise ValueError()

    do_fill_dipole = True

    gslc = "x=-21.2f:12f, y=-11f:11f, z=-11f:11f"
    b = f['b_cc'][gslc]
    b1 = f['b_fc'][gslc]
    e_cc = f['e_cc'][gslc]
    e_ec = f['e_ec'][gslc]

    if do_fill_dipole:
        mask = viscid.make_spherical_mask(b, rmax=3.5)
        viscid.fill_dipole(b, mask=mask)

        mask = viscid.make_spherical_mask(b1, rmax=3.5)
        viscid.fill_dipole(b1, mask=mask)

        mask = None

    # seeds = viscid.SphericalCap(r=1.02, ntheta=64, nphi=32, angle0=17, angle=20,
    #                             philim=(100, 260), roll=-180.0)
    # seeds = viscid.SphericalCap(r=1.02, ntheta=64, nphi=32, angle0=17, angle=20,
    #                             philim=(0, 10), roll=0.0)
    seedsN = viscid.Sphere(r=1.02, ntheta=16, nphi=16, thetalim=(15, 25),
                           philim=(0, 300), crd_system=b)
    seedsS = viscid.Sphere(r=1.02, ntheta=16, nphi=16, thetalim=(155, 165),
                           philim=(0, 300), crd_system=b)

    bl_kwargs = dict(ibound=0.9, obound0=(-20, -10, -10), obound1=(11, 10, 10))

    # blines_cc, topo_cc = viscid.streamlines(b, seeds, **bl_kwargs)
    blinesN_fc, topoN_fc = viscid.streamlines(b1, seedsN, **bl_kwargs)
    _, topoS_fc = viscid.streamlines(b1, seedsS, output=viscid.OUTPUT_TOPOLOGY,
                                     **bl_kwargs)

    if True:
        from viscid.plot import mvi
        mesh = mvi.mesh_from_seeds(seedsN, scalars=topoN_fc)
        mesh.actor.property.backface_culling = True
        # mvi.plot_lines(blines_cc, scalars="#000000", tube_radius=0.03)
        mvi.plot_lines(blinesN_fc, scalars=viscid.topology2color(topoN_fc),
                       opacity=0.7)

        mvi.plot_blue_marble(r=1.0)
        mvi.plot_earth_3d(radius=1.01, crd_system=b, night_only=True,
                          opacity=0.5)
        mvi.show()

    if True:
        mpl.subplot(121, projection='polar')
        mpl.plot(topoN_fc)
        mpl.subplot(122, projection='polar')
        mpl.plot(topoS_fc)
        mpl.show()

    return 0
コード例 #10
0
ファイル: separator.py プロジェクト: KristoforMaynard/Viscid
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