コード例 #1
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser)
    # args.show = True

    t = viscid.linspace_datetime64('2006-06-10 12:30:00.0',
                                   '2006-06-10 12:33:00.0', 16)
    tL = viscid.as_datetime64('2006-06-10 12:31:00.0')
    tR = viscid.as_datetime64('2006-06-10 12:32:00.0')
    y = np.linspace(2 * np.pi, 4 * np.pi, 12)

    ### plots with a datetime64 axis
    f0 = viscid.ones([t, y], crd_names='ty', center='node')
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = plt.figure(figsize=(10, 5))
    # 1D plot
    vlt.subplot(121)
    vlt.plot(f0[tL:tR]['y=0'], marker='^')
    plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    vlt.subplot(122)
    vlt.plot(f0, x=(t[0], t[-1]))

    plt.suptitle("datetime64")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))
    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close(fig)

    ### plots with a timedelta64 axis
    tL = tL - t[0]
    tR = tR - t[0]
    t = t - t[0]
    f0 = viscid.ones([t, y], crd_names='ty', center='node')
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = plt.figure(figsize=(10, 5))
    # 1D plot
    vlt.subplot(121)
    vlt.plot(f0[tL:tR]['y=0'], marker='^')
    plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    vlt.subplot(122)
    vlt.plot(f0, x=(t[0], t[-1]))

    plt.suptitle("timedelta64")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))
    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close(fig)

    return 0
コード例 #2
0
def do_test(lines, scalars, show=False, txt=""):
    viscid.logger.info('--> ' + txt)
    title = txt + '\n' + "\n".join(
        textwrap.wrap("scalars = {0}".format(scalars), width=50))

    try:
        from viscid.plot import vpyplot as vlt
        from matplotlib import pyplot as plt

        vlt.clf()
        vlt.plot_lines(lines, scalars=scalars)
        plt.title(title)
        vlt.savefig(next_plot_fname(__file__, series='q2'))
        if show:
            vlt.show()
    except ImportError:
        pass

    try:
        from mayavi import mlab
        vlab, _ = get_mvi_fig()

        vlab.clf()
        vlab.plot_lines3d(lines, scalars=scalars)
        vlab.fancy_axes()
        mlab.text(0.05, 0.05, title)
        vlab.savefig(next_plot_fname(__file__, series='q3'))
        if show:
            vlab.show(stop=True)
    except ImportError:
        pass
コード例 #3
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser)
    # args.show = True

    t = viscid.linspace_datetime64('2006-06-10 12:30:00.0',
                                   '2006-06-10 12:33:00.0', 16)
    tL = viscid.as_datetime64('2006-06-10 12:31:00.0')
    tR = viscid.as_datetime64('2006-06-10 12:32:00.0')
    y = np.linspace(2 * np.pi, 4 * np.pi, 12)

    ### plots with a datetime64 axis
    f0 = viscid.ones([t, y], crd_names='ty', center='node')
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = plt.figure(figsize=(10, 5))
    # 1D plot
    vlt.subplot(121)
    vlt.plot(f0[tL:tR]['y=0'], marker='^')
    plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    vlt.subplot(122)
    vlt.plot(f0, x=(t[0], t[-1]))

    plt.suptitle("datetime64")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))
    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close(fig)

    ### plots with a timedelta64 axis
    tL = tL - t[0]
    tR = tR - t[0]
    t = t - t[0]
    f0 = viscid.ones([t, y], crd_names='ty', center='node')
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = plt.figure(figsize=(10, 5))
    # 1D plot
    vlt.subplot(121)
    vlt.plot(f0[tL:tR]['y=0'], marker='^')
    plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    vlt.subplot(122)
    vlt.plot(f0, x=(t[0], t[-1]))

    plt.suptitle("timedelta64")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))
    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close(fig)

    return 0
コード例 #4
0
ファイル: test_seed.py プロジェクト: KristoforMaynard/Viscid
def run_test(fld, seeds, plot2d=True, plot3d=True, add_title="",
             view_kwargs=None, show=False, scatter_mpl=False, mesh_mvi=True):
    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 vpyplot as vlt
        from matplotlib import pyplot as plt
        plt.clf()
        # plt.plot(seeds.get_points()[2, :], fld)
        mpl_plot_kwargs = dict()
        if interpolated_fld.is_spherical():
            mpl_plot_kwargs['hemisphere'] = 'north'
        vlt.plot(interpolated_fld, **mpl_plot_kwargs)
        plt.title(seed_name)

        plt.savefig(next_plot_fname(__file__, series='2d'))
        if show:
            plt.show()

        if scatter_mpl:
            plt.clf()
            vlt.plot2d_line(seeds.get_points(), fld, symdir='z', marker='o')
            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

        _ = get_mvi_fig(offscreen=not show)

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

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

        vlab.savefig(next_plot_fname(__file__, series='3d'))
        if show:
            vlab.show(stop=True)
    except ImportError:
        pass
コード例 #5
0
def main():
    parser = argparse.ArgumentParser(description="Test divergence")
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser)
    # args.show = True

    t = viscid.linspace_datetime64("2006-06-10 12:30:00.0", "2006-06-10 12:33:00.0", 16)
    tL = viscid.as_datetime64("2006-06-10 12:31:00.0")
    tR = viscid.as_datetime64("2006-06-10 12:32:00.0")
    y = np.linspace(2 * np.pi, 4 * np.pi, 12)

    ### plots with a datetime64 axis
    f0 = viscid.ones([t, y], crd_names="ty", center="node")
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = mpl.plt.figure(figsize=(10, 5))
    # 1D plot
    mpl.subplot(121)
    mpl.plot(f0[tL:tR]["y=0"], marker="^")
    mpl.plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    mpl.subplot(122)
    mpl.plot(f0, x=(t[0], t[-1]))

    mpl.plt.suptitle("datetime64")
    mpl.auto_adjust_subplots(subplot_params=dict(top=0.9))
    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        mpl.show()
    mpl.plt.close(fig)

    ### plots with a timedelta64 axis
    tL = tL - t[0]
    tR = tR - t[0]
    t = t - t[0]
    f0 = viscid.ones([t, y], crd_names="ty", center="node")
    T, Y = f0.get_crds(shaped=True)
    f0.data += np.arange(T.size).reshape(T.shape)
    f0.data += np.cos(Y)

    fig = mpl.plt.figure(figsize=(10, 5))
    # 1D plot
    mpl.subplot(121)
    mpl.plot(f0[tL:tR]["y=0"], marker="^")
    mpl.plt.xlim(*viscid.as_datetime(t[[0, -1]]).tolist())
    # 2D plot
    mpl.subplot(122)
    mpl.plot(f0, x=(t[0], t[-1]), y=(y[0], y[-1]))

    mpl.plt.suptitle("timedelta64")
    mpl.auto_adjust_subplots(subplot_params=dict(top=0.9))
    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        mpl.show()
    mpl.plt.close(fig)

    return 0
コード例 #6
0
ファイル: test_seed.py プロジェクト: KristoforMaynard/Viscid
def run_test(fld, seeds, plot2d=True, plot3d=True, add_title="",
             view_kwargs=None, show=False, scatter_mpl=False, mesh_mvi=True):
    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 vpyplot as vlt
        from matplotlib import pyplot as plt
        plt.clf()
        # plt.plot(seeds.get_points()[2, :], fld)
        mpl_plot_kwargs = dict()
        if interpolated_fld.is_spherical():
            mpl_plot_kwargs['hemisphere'] = 'north'
        vlt.plot(interpolated_fld, **mpl_plot_kwargs)
        plt.title(seed_name)

        plt.savefig(next_plot_fname(__file__, series='2d'))
        if show:
            plt.show()

        if scatter_mpl:
            plt.clf()
            vlt.plot2d_line(seeds.get_points(), fld, symdir='z', marker='o')
            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()

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

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

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

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

    try:
        if not plot2d:
            raise ImportError
        from viscid.plot import vpyplot as vlt
        from matplotlib import pyplot as plt
        plt.clf()

        vlt.plot2d_lines(lines, scalars=topo_color, symdir='y', marker='^')
        if title:
            plt.title(title)

        plt.savefig(next_plot_fname(__file__, series='2d'))
        if show:
            plt.show()
    except ImportError:
        pass

    try:
        if not plot3d:
            raise ImportError
        from viscid.plot import vlab

        try:
            fig = _global_ns['figure']
            vlab.clf()
        except KeyError:
            fig = vlab.figure(size=[1200, 800], offscreen=not show,
                             bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
            _global_ns['figure'] = fig

        fld_mag = np.log(viscid.magnitude(_fld))
        try:
            # note: mayavi.mlab.mesh can't take color tuples as scalars
            #       so one can't use topo_color on a mesh surface. This
            #       is a limitation of mayavi. To actually plot a specific
            #       set of colors on a mesh, one must use a texture
            mesh = vlab.mesh_from_seeds(_seeds, scalars=topo, opacity=0.6)
            mesh.actor.property.backface_culling = True
        except RuntimeError:
            pass
        vlab.plot_lines(lines, scalars=fld_mag, tube_radius=0.01,
                       cmap='viridis')
        if title:
            vlab.title(title)

        vlab.savefig(next_plot_fname(__file__, series='3d'))
        if show:
            vlab.show()

    except ImportError:
        pass
コード例 #8
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 matplotlib import pyplot as plt
        from viscid.plot import vpyplot as vlt
        plt.clf()
        # plt.plot(seeds.get_points()[2, :], fld)
        mpl_plot_kwargs = dict()
        if interpolated_fld.is_spherical():
            mpl_plot_kwargs['hemisphere'] = 'north'
        vlt.plot(interpolated_fld, **mpl_plot_kwargs)
        plt.title(seed_name)

        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)
            _global_ns['figure'] = fig

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

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

        vlab.savefig(next_plot_fname(__file__, series='3d'))
        if show:
            vlab.show()
    except ImportError:
        pass
コード例 #9
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
コード例 #10
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
コード例 #11
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()
コード例 #12
0
def run_test(_fld, _seeds, plot2d=True, plot3d=True, title='', show=False,
             **kwargs):
    lines, topo = viscid.calc_streamlines(_fld, _seeds, **kwargs)
    topo_color = viscid.topology2color(topo)

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

    try:
        if not plot2d:
            raise ImportError
        from viscid.plot import vpyplot as vlt
        from matplotlib import pyplot as plt
        plt.clf()

        vlt.plot2d_lines(lines, scalars=topo_color, symdir='y', marker='^')
        if title:
            plt.title(title)

        plt.savefig(next_plot_fname(__file__, series='2d'))
        if show:
            plt.show()
    except ImportError:
        pass

    try:
        if not plot3d:
            raise ImportError
        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
コード例 #13
0
ファイル: test_vpic.py プロジェクト: KristoforMaynard/Viscid
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    f = viscid.load_file(os.path.join(sample_dir, 'vpic_sample', 'global.vpc'))

    # some slices that are good to check
    vlt.clf()
    vlt.plot(f['bx']['x=:32.01j'])
    plt.close()
    vlt.clf()
    vlt.plot(f['bx']['x=:33.0j'])
    plt.close()

    _, axes = vlt.subplots(2, 2, figsize=(8, 4))

    for i, ti in enumerate([0, -1]):
        f.activate_time(ti)
        vlt.plot(f['n_e']['y=0j'], symmetric=False, ax=axes[0, i])
        vlt.plot(f['bx']['y=0j'], symmetric=True, ax=axes[1, i])
        axes[0, i].set_title(f.get_grid().time)

    vlt.auto_adjust_subplots()

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close()

    return 0
コード例 #14
0
ファイル: test_gkeyll.py プロジェクト: zcl-maker/Viscid
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
コード例 #15
0
def run_mpl_testA(show=False):
    logger.info("2D cell centered tests")

    x = np.array(np.linspace(-10, 10, 100), dtype=dtype)
    y = np.array(np.linspace(-10, 10, 120), dtype=dtype)
    z = np.array(np.linspace(-1, 1, 2), dtype=dtype)

    fld_s = viscid.empty([x, y, z], center='cell')
    Xcc, Ycc, Zcc = fld_s.get_crds_cc(shaped=True)  # pylint: disable=unused-variable
    fld_s[:, :, :] = np.sin(Xcc) + np.cos(Ycc)

    nrows = 4
    ncols = 1

    plt.subplot2grid((nrows, ncols), (0, 0))
    mpl.plot(fld_s, "y=20f", show=False, plot_opts="lin_0")
    plt.subplot2grid((nrows, ncols), (1, 0))
    mpl.plot(fld_s, "x=0f:20f,y=0f:5f", earth=True, show=False,
             plot_opts="x_-10_0,y_0_7")
    plt.subplot2grid((nrows, ncols), (2, 0))
    mpl.plot(fld_s, "y=0f", show=False, plot_opts="lin_-1_1")
    plt.subplot2grid((nrows, ncols), (3, 0))
    mpl.plot(fld_s, "z=0f,x=-20f:0f", earth=True, show=False, plot_opts="lin_-5_5")

    mpl.plt.suptitle("2d cell centered")
    mpl.auto_adjust_subplots()

    mpl.plt.savefig(next_plot_fname(__file__))
    if show:
        mpl.mplshow()
コード例 #16
0
def run_test_2d(f, main__file__, show=False):
    mpl.clf()
    slc = "x=-20f:12f, y=0f"
    plot_kwargs = dict(title=True, earth=True)
    mpl.subplot(141)
    mpl.plot(f['pp'], slc, logscale=True, **plot_kwargs)
    mpl.plot(np.abs(f['psi']), style='contour', logscale=True, levels=30,
             linewidths=0.8, colors='grey', linestyles='solid', cbar=None,
             x=(-20, 12))
    mpl.subplot(142)
    mpl.plot(viscid.magnitude(f['bcc']), slc, logscale=True, **plot_kwargs)
    mpl.plot2d_quiver(f['v'][slc], step=5, color='y', pivot='mid', width=0.03,
                      scale=600)
    mpl.subplot(143)
    mpl.plot(f['jy'], slc, clim=[-0.005, 0.005], **plot_kwargs)
    mpl.streamplot(f['v'][slc], linewidth=0.3)
    mpl.subplot(144)
    mpl.plot(f['jy'], "x=7f:12f, y=0f, z=0f")

    mpl.plt.suptitle("2D File")
    mpl.auto_adjust_subplots(subplot_params=dict(top=0.9, wspace=1.3))
    mpl.plt.gcf().set_size_inches(10, 4)

    mpl.savefig(next_plot_fname(main__file__))
    if show:
        mpl.show()
コード例 #17
0
ファイル: test_mpl.py プロジェクト: KristoforMaynard/Viscid
def run_mpl_testB(show=False):
    logger.info("3D node centered tests")

    x = np.array(np.linspace(-10, 10, 100), dtype=dtype)
    y = np.array(np.linspace(-10, 10, 120), dtype=dtype)
    z = np.array(np.linspace(-10, 10, 140), dtype=dtype)

    fld_s = viscid.empty([x, y, z], center='node')
    X, Y, Z = fld_s.get_crds_nc(shaped=True)  # pylint: disable=W0612
    fld_s[:, :, :] = np.sin(X) + np.cos(Y) - np.cos(Z)
    # print("shape: ", fld_s.data.shape)

    _, axes = plt.subplots(4, 1, squeeze=False)

    vlt.plot(fld_s, "z=0,x=:30", ax=axes[0, 0], earth=True, plot_opts="lin_0")
    vlt.plot(fld_s, "z=0.75j,x=-4:-1,y=-3j:3j", ax=axes[1, 0], earth=True)
    vlt.plot(fld_s, "x=-0.5j:,y=-3j:3j,z=0j", ax=axes[2, 0], earth=True)
    vlt.plot(fld_s, "x=0.0j,y=-5.0j:5.0j", ax=axes[3, 0], earth=True,
             plot_opts="log,g")

    plt.suptitle("3d node centered")
    vlt.auto_adjust_subplots()

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
コード例 #18
0
ファイル: test_mpl.py プロジェクト: KristoforMaynard/Viscid
def run_mpl_testA(show=False):
    logger.info("2D cell centered tests")

    x = np.array(np.linspace(-10, 10, 100), dtype=dtype)
    y = np.array(np.linspace(-10, 10, 120), dtype=dtype)
    z = np.array(np.linspace(-1, 1, 2), dtype=dtype)

    fld_s = viscid.empty([x, y, z], center='cell')
    Xcc, Ycc, Zcc = fld_s.get_crds_cc(shaped=True)  # pylint: disable=unused-variable
    fld_s[:, :, :] = np.sin(Xcc) + np.cos(Ycc)

    _, axes = plt.subplots(4, 1, squeeze=False)

    vlt.plot(fld_s, "y=20j", ax=axes[0, 0], show=False, plot_opts="lin_0")
    vlt.plot(fld_s, "x=0j:20j,y=0j:5j", ax=axes[1, 0], earth=True, show=False,
             plot_opts="x_-10_0,y_0_7")
    vlt.plot(fld_s, "y=0j", ax=axes[2, 0], show=False, plot_opts="lin_-1_1")
    vlt.plot(fld_s, "z=0j,x=-20j:0j", ax=axes[3, 0], earth=True, show=False,
             plot_opts="lin_-5_5")

    plt.suptitle("2d cell centered")
    vlt.auto_adjust_subplots()

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
コード例 #19
0
def run_mpl_testB(show=False):
    logger.info("3D node centered tests")

    x = np.array(np.linspace(-10, 10, 100), dtype=dtype)
    y = np.array(np.linspace(-10, 10, 120), dtype=dtype)
    z = np.array(np.linspace(-10, 10, 140), dtype=dtype)

    fld_s = viscid.empty([x, y, z], center='node')
    X, Y, Z = fld_s.get_crds_nc(shaped=True)  # pylint: disable=W0612
    fld_s[:, :, :] = np.sin(X) + np.cos(Y) - np.cos(Z)
    # print("shape: ", fld_s.data.shape)

    nrows = 4
    ncols = 1

    plt.subplot2grid((nrows, ncols), (0, 0))
    mpl.plot(fld_s, "z=0,x=:30", earth=True, plot_opts="lin_0")
    plt.subplot2grid((nrows, ncols), (1, 0))
    mpl.plot(fld_s, "z=0.75f,x=-4:-1,y=-3f:3f", earth=True)
    plt.subplot2grid((nrows, ncols), (2, 0))
    mpl.plot(fld_s, "x=-0.5f:,y=-3f:3f,z=0f", earth=True)
    plt.subplot2grid((nrows, ncols), (3, 0))
    mpl.plot(fld_s, "x=0.0f,y=-5.0f:5.0f", earth=True, plot_opts="log,g")

    mpl.plt.suptitle("3d node centered")
    mpl.auto_adjust_subplots()

    mpl.plt.savefig(next_plot_fname(__file__))
    if show:
        mpl.mplshow()
コード例 #20
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
コード例 #21
0
ファイル: test_calc.py プロジェクト: KristoforMaynard/Viscid
def run_mag_test(fld, title="", show=False):
    vx, vy, vz = fld.component_views()  # pylint: disable=W0612
    vx, vy, vz = fld.component_fields()

    try:
        t0 = time()
        mag_ne = viscid.magnitude(fld, preferred="numexpr", only=False)
        t1 = time()
        logger.info("numexpr mag runtime: %g", t1 - t0)
    except viscid.verror.BackendNotFound:
        xfail("Numexpr is not installed")

    planes = ["z=0", "y=0"]
    nrows = 4
    ncols = len(planes)

    _, axes = plt.subplots(nrows, ncols, sharex=True, sharey=True, squeeze=False)

    for ind, p in enumerate(planes):
        vlt.plot(vx, p, ax=axes[0, ind], show=False)
        vlt.plot(vy, p, ax=axes[1, ind], show=False)
        vlt.plot(vz, p, ax=axes[2, ind], show=False)
        vlt.plot(mag_ne, p, ax=axes[3, ind], show=False)

    plt.suptitle(title)
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9, right=0.9))
    plt.gcf().set_size_inches(6, 7)

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
コード例 #22
0
ファイル: test_mpl.py プロジェクト: zcl-maker/Viscid
def run_mpl_testB(show=False):
    logger.info("3D node centered tests")

    x = np.array(np.linspace(-10, 10, 100), dtype=dtype)
    y = np.array(np.linspace(-10, 10, 120), dtype=dtype)
    z = np.array(np.linspace(-10, 10, 140), dtype=dtype)

    fld_s = viscid.empty([x, y, z], center='node')
    X, Y, Z = fld_s.get_crds_nc(shaped=True)  # pylint: disable=W0612
    fld_s[:, :, :] = np.sin(X) + np.cos(Y) - np.cos(Z)
    # print("shape: ", fld_s.data.shape)

    nrows = 4
    ncols = 1

    plt.subplot2grid((nrows, ncols), (0, 0))
    vlt.plot(fld_s, "z=0,x=:30", earth=True, plot_opts="lin_0")
    plt.subplot2grid((nrows, ncols), (1, 0))
    vlt.plot(fld_s, "z=0.75f,x=-4:-1,y=-3f:3f", earth=True)
    plt.subplot2grid((nrows, ncols), (2, 0))
    vlt.plot(fld_s, "x=-0.5f:,y=-3f:3f,z=0f", earth=True)
    plt.subplot2grid((nrows, ncols), (3, 0))
    vlt.plot(fld_s, "x=0.0f,y=-5.0f:5.0f", earth=True, plot_opts="log,g")

    plt.suptitle("3d node centered")
    vlt.auto_adjust_subplots()

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
コード例 #23
0
ファイル: test_mpl.py プロジェクト: KristoforMaynard/Viscid
def run_mpl_testB(show=False):
    logger.info("3D node centered tests")

    x = np.array(np.linspace(-10, 10, 100), dtype=dtype)
    y = np.array(np.linspace(-10, 10, 120), dtype=dtype)
    z = np.array(np.linspace(-10, 10, 140), dtype=dtype)

    fld_s = viscid.empty([x, y, z], center='node')
    X, Y, Z = fld_s.get_crds_nc(shaped=True)  # pylint: disable=W0612
    fld_s[:, :, :] = np.sin(X) + np.cos(Y) - np.cos(Z)
    # print("shape: ", fld_s.data.shape)

    _, axes = plt.subplots(4, 1, squeeze=False)

    vlt.plot(fld_s, "z=0,x=:30", ax=axes[0, 0], earth=True, plot_opts="lin_0")
    vlt.plot(fld_s, "z=0.75j,x=-4:-1,y=-3j:3j", ax=axes[1, 0], earth=True)
    vlt.plot(fld_s, "x=-0.5j:,y=-3j:3j,z=0j", ax=axes[2, 0], earth=True)
    vlt.plot(fld_s,
             "x=0.0j,y=-5.0j:5.0j",
             ax=axes[3, 0],
             earth=True,
             plot_opts="log,g")

    plt.suptitle("3d node centered")
    vlt.auto_adjust_subplots()

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
コード例 #24
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    f = viscid.load_file(os.path.join(sample_dir, 'vpic_sample', 'global.vpc'))

    # some slices that are good to check
    vlt.clf()
    vlt.plot(f['bx']['x=:32.01j'])
    plt.close()
    vlt.clf()
    vlt.plot(f['bx']['x=:33.0j'])
    plt.close()

    _, axes = vlt.subplots(2, 2, figsize=(8, 4))

    for i, ti in enumerate([0, -1]):
        f.activate_time(ti)
        vlt.plot(f['n_e']['y=0j'], symmetric=False, ax=axes[0, i])
        vlt.plot(f['bx']['y=0j'], symmetric=True, ax=axes[1, i])
        axes[0, i].set_title(f.get_grid().time)

    vlt.auto_adjust_subplots()

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close()

    return 0
コード例 #25
0
def run_test_iof(f, main__file__, show=False):
    vlt.clf()

    fac_tot = 1e9 * f["fac_tot"]
    plot_args = dict(projection="polar",
                     lin=[-300, 300],
                     bounding_lat=35.0,
                     drawcoastlines=True,  # for basemap only
                     title="Total FAC\n",
                     gridec='gray',
                     label_lat=True,
                     label_mlt=True,
                     colorbar=True,
                     cbar_kwargs=dict(pad=0.15)  # pad the colorbar away from the plot
                    )

    ax1 = vlt.subplot(121, projection='polar')
    vlt.plot(fac_tot, ax=ax1, hemisphere='north', **plot_args)
    ax1.annotate('(a)', xy=(0, 0), textcoords="axes fraction",
                 xytext=(-0.1, 1.0), fontsize=18)

    ax2 = vlt.subplot(122, projection='polar')
    plot_args['gridec'] = False
    vlt.plot(fac_tot, ax=ax2, hemisphere="south", style="contourf",
             levels=50, extend="both", **plot_args)
    ax2.annotate('(b)', xy=(0, 0), textcoords="axes fraction",
                 xytext=(-0.1, 1.0), fontsize=18)

    vlt.auto_adjust_subplots(subplot_params=dict())
    plt.gcf().set_size_inches(8, 4)

    plt.savefig(next_plot_fname(main__file__))
    if show:
        vlt.mplshow()
コード例 #26
0
def run_div_test(fld, exact, title='', show=False, ignore_inexact=False):
    t0 = time()
    result_numexpr = viscid.div(fld, preferred="numexpr", only=False)
    t1 = time()
    logger.info("numexpr magnitude runtime: %g", t1 - t0)

    result_diff = viscid.diff(result_numexpr, exact)['x=1:-1, y=1:-1, z=1:-1']
    if not ignore_inexact and not (result_diff.data < 5e-5).all():
        logger.warn("numexpr result is far from the exact result")
    logger.info("min/max(abs(numexpr - exact)): %g / %g",
                np.min(result_diff.data), np.max(result_diff.data))

    planes = ["y=0f", "z=0f"]
    nrows = 2
    ncols = len(planes)
    ax = plt.subplot2grid((nrows, ncols), (0, 0))
    ax.axis("equal")

    for i, p in enumerate(planes):
        plt.subplot2grid((nrows, ncols), (0, i), sharex=ax, sharey=ax)
        mpl.plot(result_numexpr, p, show=False)
        plt.subplot2grid((nrows, ncols), (1, i), sharex=ax, sharey=ax)
        mpl.plot(result_diff, p, show=False)

    mpl.plt.suptitle(title)
    mpl.auto_adjust_subplots(subplot_params=dict(top=0.9))

    mpl.plt.savefig(next_plot_fname(__file__))
    if show:
        mpl.mplshow()
コード例 #27
0
def run_mag_test(fld, title="", show=False):
    vx, vy, vz = fld.component_views()  # pylint: disable=W0612
    vx, vy, vz = fld.component_fields()

    try:
        t0 = time()
        mag_ne = viscid.magnitude(fld, preferred="numexpr", only=False)
        t1 = time()
        logger.info("numexpr mag runtime: %g", t1 - t0)
    except viscid.verror.BackendNotFound:
        xfail("Numexpr is not installed")

    planes = ["z=0", "y=0"]
    nrows = 4
    ncols = len(planes)
    ax = plt.subplot2grid((nrows, ncols), (0, 0))
    ax.axis("equal")

    for ind, p in enumerate(planes):
        plt.subplot2grid((nrows, ncols), (0, ind), sharex=ax, sharey=ax)
        mpl.plot(vx, p, show=False)
        plt.subplot2grid((nrows, ncols), (1, ind), sharex=ax, sharey=ax)
        mpl.plot(vy, p, show=False)
        plt.subplot2grid((nrows, ncols), (2, ind), sharex=ax, sharey=ax)
        mpl.plot(vz, p, show=False)
        plt.subplot2grid((nrows, ncols), (3, ind), sharex=ax, sharey=ax)
        mpl.plot(mag_ne, p, show=False)

    mpl.plt.suptitle(title)
    mpl.auto_adjust_subplots(subplot_params=dict(top=0.9))
    mpl.plt.gcf().set_size_inches(6, 7)

    mpl.plt.savefig(next_plot_fname(__file__))
    if show:
        mpl.mplshow()
コード例 #28
0
ファイル: ggcm_test_common.py プロジェクト: zcl-maker/Viscid
def run_test_3d(f, main__file__, show=False):
    vlt.clf()
    slc = "x=-20f:12f, y=0f"
    plot_kwargs = dict(title=True, earth=True)
    vlt.subplot(141)
    vlt.plot(f['pp'], slc, logscale=True, **plot_kwargs)
    vlt.subplot(142)
    vlt.plot(viscid.magnitude(f['bcc']), slc, logscale=True, **plot_kwargs)
    vlt.plot2d_quiver(f['v'][slc],
                      step=5,
                      color='y',
                      pivot='mid',
                      width=0.03,
                      scale=600)
    vlt.subplot(143)
    vlt.plot(f['jy'], slc, clim=(-0.005, 0.005), **plot_kwargs)
    vlt.streamplot(f['v'][slc], linewidth=0.3)
    vlt.subplot(144)
    vlt.plot(f['jy'], "x=7f:12f, y=0f, z=0f")

    plt.suptitle("3D File")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9, wspace=1.3))
    plt.gcf().set_size_inches(10, 4)

    vlt.savefig(next_plot_fname(main__file__))
    if show:
        vlt.show()
コード例 #29
0
def run_test_iof(f, main__file__, show=False):
    mpl.clf()

    fac_tot = 1e9 * f["fac_tot"]
    plot_args = dict(projection="polar",
                     lin=[-300, 300],
                     bounding_lat=35.0,
                     drawcoastlines=True,  # for basemap only
                     title="Total FAC\n",
                     gridec='gray',
                     label_lat=True,
                     label_mlt=True,
                     colorbar=dict(pad=0.1)  # pad the colorbar away from the plot
                    )

    ax1 = mpl.subplot(121, projection='polar')
    mpl.plot(fac_tot, ax=ax1, hemisphere='north', **plot_args)
    ax1.annotate('(a)', xy=(0, 0), textcoords="axes fraction",
                 xytext=(-0.1, 1.0), fontsize=18)

    ax2 = mpl.subplot(122, projection='polar')
    plot_args['gridec'] = False
    mpl.plot(fac_tot, ax=ax2, hemisphere="south", style="contourf",
             levels=50, extend="both", **plot_args)
    ax2.annotate('(b)', xy=(0, 0), textcoords="axes fraction",
                 xytext=(-0.1, 1.0), fontsize=18)

    mpl.auto_adjust_subplots(subplot_params=dict())
    mpl.plt.gcf().set_size_inches(8, 4)

    mpl.plt.savefig(next_plot_fname(main__file__))
    if show:
        mpl.mplshow()
コード例 #30
0
def run_div_test(fld, exact, title='', show=False, ignore_inexact=False):
    t0 = time()
    result_numexpr = viscid.div(fld, preferred="numexpr", only=False)
    t1 = time()
    logger.info("numexpr magnitude runtime: %g", t1 - t0)

    result_diff = viscid.diff(result_numexpr, exact)['x=1:-1, y=1:-1, z=1:-1']
    if not ignore_inexact and not (result_diff.data < 5e-5).all():
        logger.warning("numexpr result is far from the exact result")
    logger.info("min/max(abs(numexpr - exact)): %g / %g",
                np.min(result_diff.data), np.max(result_diff.data))

    planes = ["y=0j", "z=0j"]
    nrows = 2
    ncols = len(planes)
    _, axes = plt.subplots(nrows, ncols, squeeze=False)

    for i, p in enumerate(planes):
        vlt.plot(result_numexpr, p, ax=axes[0, i], show=False)
        vlt.plot(result_diff, p, ax=axes[1, i], show=False)

    plt.suptitle(title)
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
コード例 #31
0
def run_test_2d(f, main__file__, show=False):
    vlt.clf()
    slc = "x=-20j:12j, y=0j"
    plot_kwargs = dict(title=True, earth=True)
    vlt.subplot(141)
    vlt.plot(f['pp'], slc, logscale=True, **plot_kwargs)
    vlt.plot(np.abs(f['psi']), style='contour', logscale=True, levels=30,
             linewidths=0.8, colors='grey', linestyles='solid', colorbar=None,
             x=(-20, 12))
    vlt.subplot(142)
    vlt.plot(viscid.magnitude(f['bcc']), slc, logscale=True, **plot_kwargs)
    vlt.plot2d_quiver(f['v'][slc], step=5, color='y', pivot='mid', width=0.03,
                      scale=600)
    vlt.subplot(143)
    vlt.plot(f['jy'], slc, clim=[-0.005, 0.005], **plot_kwargs)
    vlt.streamplot(f['v'][slc], linewidth=0.3)
    vlt.subplot(144)
    vlt.plot(f['jy'], "x=7j:12j, y=0j, z=0j")

    plt.suptitle("2D File")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9, wspace=1.3))
    plt.gcf().set_size_inches(10, 4)

    vlt.savefig(next_plot_fname(main__file__))
    if show:
        vlt.show()
コード例 #32
0
ファイル: test_mpl.py プロジェクト: KristoforMaynard/Viscid
def run_mpl_testA(show=False):
    logger.info("2D cell centered tests")

    x = np.array(np.linspace(-10, 10, 100), dtype=dtype)
    y = np.array(np.linspace(-10, 10, 120), dtype=dtype)
    z = np.array(np.linspace(-1, 1, 2), dtype=dtype)

    fld_s = viscid.empty([x, y, z], center='cell')
    Xcc, Ycc, Zcc = fld_s.get_crds_cc(shaped=True)  # pylint: disable=unused-variable
    fld_s[:, :, :] = np.sin(Xcc) + np.cos(Ycc)

    _, axes = plt.subplots(4, 1, squeeze=False)

    vlt.plot(fld_s, "y=20j", ax=axes[0, 0], show=False, plot_opts="lin_0")
    vlt.plot(fld_s,
             "x=0j:20j,y=0j:5j",
             ax=axes[1, 0],
             earth=True,
             show=False,
             plot_opts="x_-10_0,y_0_7")
    vlt.plot(fld_s, "y=0j", ax=axes[2, 0], show=False, plot_opts="lin_-1_1")
    vlt.plot(fld_s,
             "z=0j,x=-20j:0j",
             ax=axes[3, 0],
             earth=True,
             show=False,
             plot_opts="lin_-5_5")

    plt.suptitle("2d cell centered")
    vlt.auto_adjust_subplots()

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
コード例 #33
0
def run_test(show=False):
    f = viscid.load_file(os.path.join(viscid.sample_dir, "amr.xdmf"))
    plot_kwargs = dict(patchec='y')
    vlt.plot(f['f'], "z=0.0f", **plot_kwargs)

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.show()
コード例 #34
0
def run_test(fld, seeds, kind, show=False):
    plt.clf()
    vlt.plot(viscid.interp(fld, seeds, kind=kind))
    plt.title(kind)

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.show()
コード例 #35
0
def run_test(fld, seeds, kind, show=False):
    plt.clf()
    vlt.plot(viscid.interp(fld, seeds, kind=kind))
    plt.title(kind)

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.show()
コード例 #36
0
ファイル: test_amr.py プロジェクト: KristoforMaynard/Viscid
def run_test(show=False):
    f = viscid.load_file(os.path.join(viscid.sample_dir, "amr.xdmf"))
    plot_kwargs = dict(patchec='y')
    vlt.plot(f['f'], "z=0.0j", **plot_kwargs)

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.show()
コード例 #37
0
ファイル: test_amr.py プロジェクト: KristoforMaynard/Viscid
def run_test(show=False):
    f = viscid.load_file(sample_dir + "/amr.xdmf")
    plot_kwargs = dict(patchec="y")
    mpl.plot(f["f"], "z=0.0f", **plot_kwargs)

    mpl.plt.savefig(next_plot_fname(__file__))
    if show:
        mpl.show()
コード例 #38
0
def main():
    parser = argparse.ArgumentParser(description="Test xdmf")
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    f = viscid.load_file(sample_dir + '/test.asc')
    mpl.plot(f['c1'], show=False)
    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        mpl.show()
コード例 #39
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    f = viscid.load_file(os.path.join(viscid.sample_dir, "test.asc"))
    vlt.plot(f['c1'], show=False)
    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()

    return 0
コード例 #40
0
def do_test(lines, scalars, show=False, txt=""):
    viscid.logger.info('--> ' + txt)
    title = txt + '\n' + "\n".join(textwrap.wrap("scalars = {0}".format(scalars),
                                                 width=50))

    try:
        from viscid.plot import vpyplot as vlt
        from matplotlib import pyplot as plt

        vlt.clf()
        vlt.plot_lines(lines, scalars=scalars)
        plt.title(title)
        vlt.savefig(next_plot_fname(__file__, series='q2'))
        if show:
            vlt.show()
    except ImportError:
        pass

    try:
        from mayavi import mlab
        from viscid.plot import vlab

        try:
            fig = _global_ns['figure']
            vlab.clf()
        except KeyError:
            fig = vlab.figure(size=[1200, 800], offscreen=not show,
                              bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
            _global_ns['figure'] = fig

        vlab.clf()
        vlab.plot_lines3d(lines, scalars=scalars)
        vlab.fancy_axes()
        mlab.text(0.05, 0.05, title)
        vlab.savefig(next_plot_fname(__file__, series='q3'))
        if show:
            vlab.show(stop=True)
    except ImportError:
        pass
コード例 #41
0
def do_test(lines, scalars, show=False, txt=""):
    viscid.logger.info('--> ' + txt)
    title = txt + '\n' + "\n".join(textwrap.wrap("scalars = {0}".format(scalars),
                                                 width=50))

    try:
        from matplotlib import pyplot as plt
        from viscid.plot import vpyplot as vlt

        vlt.clf()
        vlt.plot_lines(lines, scalars=scalars)
        plt.title(title)
        vlt.savefig(next_plot_fname(__file__, series='q2'))
        if show:
            vlt.show()
    except ImportError:
        pass

    try:
        from mayavi import mlab
        from viscid.plot import vlab

        try:
            fig = _global_ns['figure']
            vlab.clf()
        except KeyError:
            fig = vlab.figure(size=[1200, 800], offscreen=not show,
                              bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
            _global_ns['figure'] = fig

        vlab.clf()
        vlab.plot_lines3d(lines, scalars=scalars)
        vlab.fancy_axes()
        mlab.text(0.05, 0.05, title)
        vlab.savefig(next_plot_fname(__file__, series='q3'))
        if show:
            vlab.show(stop=True)
    except ImportError:
        pass
コード例 #42
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    ####### test binary files
    f_bin = viscid.load_file(os.path.join(sample_dir, 'ath_sample.*.bin'))

    for i, grid in enumerate(f_bin.iter_times(":")):
        plt.subplot2grid((2, 2), (0, i))
        vlt.plot(grid['bx'])
        plt.subplot2grid((2, 2), (1, i))
        vlt.plot(grid['by'])
    plt.suptitle("athena bin (binary) files")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.clf()

    ####### test ascii files
    f_tab = viscid.load_file(os.path.join(sample_dir, 'ath_sample.*.tab'))

    for i, grid in enumerate(f_tab.iter_times(":")):
        plt.subplot2grid((2, 2), (0, i))
        vlt.plot(grid['bx'])
        plt.subplot2grid((2, 2), (1, i))
        vlt.plot(grid['by'])
    plt.suptitle("athena tab (ascii) files")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.clf()

    return 0
コード例 #43
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    ####### test binary files
    f_bin = viscid.load_file(os.path.join(sample_dir, 'ath_sample.*.bin'))

    _, axes = plt.subplots(2, 2)
    for i, grid in enumerate(f_bin.iter_times(":")):
        vlt.plot(grid['bx'], ax=axes[0, i])
        vlt.plot(grid['by'], ax=axes[1, i])
    plt.suptitle("athena bin (binary) files")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close()

    ####### test ascii files
    f_tab = viscid.load_file(os.path.join(sample_dir, 'ath_sample.*.tab'))

    _, axes = plt.subplots(2, 2)
    for i, grid in enumerate(f_tab.iter_times(":")):
        vlt.plot(grid['bx'], ax=axes[0, i])
        vlt.plot(grid['by'], ax=axes[1, i])
    plt.suptitle("athena tab (ascii) files")
    vlt.auto_adjust_subplots(subplot_params=dict(top=0.9))

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()
    plt.close()

    return 0
コード例 #44
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    ####### test binary files
    f_bin = viscid.load_file(sample_dir + '/ath_sample.*.bin')

    for i, grid in enumerate(f_bin.iter_times(":")):
        plt.subplot2grid((2, 2), (0, i))
        mpl.plot(grid['bx'])
        plt.subplot2grid((2, 2), (1, i))
        mpl.plot(grid['by'])
    mpl.plt.suptitle("athena bin (binary) files")
    mpl.auto_adjust_subplots(subplot_params=dict(top=0.9))

    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        mpl.show()
    plt.clf()

    ####### test ascii files
    f_tab = viscid.load_file(sample_dir + '/ath_sample.*.tab')

    for i, grid in enumerate(f_tab.iter_times(":")):
        plt.subplot2grid((2, 2), (0, i))
        mpl.plot(grid['bx'])
        plt.subplot2grid((2, 2), (1, i))
        mpl.plot(grid['by'])
    mpl.plt.suptitle("athena tab (ascii) files")
    mpl.auto_adjust_subplots(subplot_params=dict(top=0.9))

    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        mpl.show()
    plt.clf()
コード例 #45
0
ファイル: test_hdf5.py プロジェクト: zcl-maker/Viscid
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    parser.add_argument("--keep", action="store_true")
    args = vutil.common_argparse(parser)

    # setup a simple force free field
    x = np.linspace(-2, 2, 20)
    y = np.linspace(-2.5, 2.5, 25)
    z = np.linspace(-3, 3, 30)
    psi = viscid.empty([x, y, z], name='psi', center='node')
    b = viscid.empty([x, y, z],
                     nr_comps=3,
                     name='b',
                     center='cell',
                     layout='interlaced')

    X, Y, Z = psi.get_crds_nc("xyz", shaped=True)
    Xcc, Ycc, Zcc = psi.get_crds_cc("xyz", shaped=True)
    psi[:, :, :] = 0.5 * (X**2 + Y**2 - Z**2)
    b['x'] = Xcc
    b['y'] = Ycc
    b['z'] = -Zcc

    # save an hdf5 file with companion xdmf file
    h5_fname = os.path.join(viscid.sample_dir, "test.h5")
    viscid.save_fields(h5_fname, [psi, b])

    # load the companion xdmf file
    xdmf_fname = h5_fname[:-3] + ".xdmf"
    f = viscid.load_file(xdmf_fname)
    plt.subplot(131)
    vlt.plot(f['psi'], "y=0")
    plt.subplot(132)
    vlt.plot(f['b'].component_fields()[0], "y=0")
    plt.subplot(133)
    vlt.plot(f['b'].component_fields()[2], "y=0")

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        plt.show()

    if not args.keep:
        os.remove(h5_fname)
        os.remove(xdmf_fname)

    return 0
コード例 #46
0
ファイル: test_hdf5.py プロジェクト: KristoforMaynard/Viscid
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    parser.add_argument("--keep", action="store_true")
    args = vutil.common_argparse(parser)

    # setup a simple force free field
    x = np.linspace(-2, 2, 20)
    y = np.linspace(-2.5, 2.5, 25)
    z = np.linspace(-3, 3, 30)
    psi = viscid.empty([x, y, z], name='psi', center='node')
    b = viscid.empty([x, y, z], nr_comps=3, name='b', center='cell',
                     layout='interlaced')

    X, Y, Z = psi.get_crds_nc("xyz", shaped=True)
    Xcc, Ycc, Zcc = psi.get_crds_cc("xyz", shaped=True)
    psi[:, :, :] = 0.5 * (X**2 + Y**2 - Z**2)
    b['x'] = Xcc
    b['y'] = Ycc
    b['z'] = -Zcc

    # save an hdf5 file with companion xdmf file
    h5_fname = os.path.join(".", "test.h5")
    viscid.save_fields(h5_fname, [psi, b])

    # load the companion xdmf file
    xdmf_fname = h5_fname[:-3] + ".xdmf"
    f = viscid.load_file(xdmf_fname)
    plt.subplot(131)
    vlt.plot(f['psi'], "y=0")
    plt.subplot(132)
    vlt.plot(f['b'].component_fields()[0], "y=0")
    plt.subplot(133)
    vlt.plot(f['b'].component_fields()[2], "y=0")

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        plt.show()

    if not args.keep:
        os.remove(h5_fname)
        os.remove(xdmf_fname)

    return 0
コード例 #47
0
ファイル: test_hdf5.py プロジェクト: KristoforMaynard/Viscid
def main():
    parser = argparse.ArgumentParser(description="Test xdmf")
    parser.add_argument("--show", "--plot", action="store_true")
    parser.add_argument("--keep", action="store_true")
    args = vutil.common_argparse(parser)

    # setup a simple force free field
    x = np.linspace(-2, 2, 20)
    y = np.linspace(-2.5, 2.5, 25)
    z = np.linspace(-3, 3, 30)
    psi = viscid.empty([x, y, z], name="psi", center="node")
    b = viscid.empty([x, y, z], nr_comps=3, name="b", center="cell", layout="interlaced")

    X, Y, Z = psi.get_crds_nc("xyz", shaped=True)
    Xcc, Ycc, Zcc = psi.get_crds_cc("xyz", shaped=True)
    psi[:, :, :] = 0.5 * (X ** 2 + Y ** 2 - Z ** 2)
    b["x"] = Xcc
    b["y"] = Ycc
    b["z"] = -Zcc

    # save an hdf5 file with companion xdmf file
    h5_fname = sample_dir + "/test.h5"
    viscid.save_fields(h5_fname, [psi, b])

    # load the companion xdmf file
    xdmf_fname = h5_fname[:-3] + ".xdmf"
    f = viscid.load_file(xdmf_fname)
    plt.subplot(131)
    mpl.plot(f["psi"], "y=0")
    plt.subplot(132)
    mpl.plot(f["b"].component_fields()[0], "y=0")
    plt.subplot(133)
    mpl.plot(f["b"].component_fields()[2], "y=0")

    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        plt.show()

    if not args.keep:
        os.remove(h5_fname)
        os.remove(xdmf_fname)
コード例 #48
0
def main():
    parser = argparse.ArgumentParser(description="Test xdmf")
    parser.add_argument("--show", "--plot", action="store_true")
    parser.add_argument("--keep", action="store_true")
    args = vutil.common_argparse(parser)

    # setup a simple force free field
    x = np.linspace(-2, 2, 20)
    y = np.linspace(-2.5, 2.5, 25)
    z = np.linspace(-3, 3, 30)
    psi = viscid.empty([x, y, z], name='psi', center='node')
    b = viscid.empty([x, y, z], nr_comps=3, name='b', center='cell',
                     layout='interlaced')

    X, Y, Z = psi.get_crds_nc("xyz", shaped=True)
    Xcc, Ycc, Zcc = psi.get_crds_cc("xyz", shaped=True)
    psi[:, :, :] = 0.5 * (X**2 + Y**2 - Z**2)
    b['x'] = Xcc
    b['y'] = Ycc
    b['z'] = -Zcc

    fname = sample_dir + '/test.npz'
    viscid.save_fields(fname, [psi, b])

    f = viscid.load_file(fname)
    plt.subplot(131)
    mpl.plot(f['psi'], "y=0")
    plt.subplot(132)
    mpl.plot(f['b'].component_fields()[0], "y=0")
    plt.subplot(133)
    mpl.plot(f['b'].component_fields()[2], "y=0")

    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        plt.show()

    if not args.keep:
        os.remove(fname)
コード例 #49
0
ファイル: ggcm_test_common.py プロジェクト: zcl-maker/Viscid
def run_test_timeseries(f, main__file__, show=False):
    vlt.clf()

    ntimes = f.nr_times()
    t = [None] * ntimes
    pressure = np.zeros((ntimes, ), dtype='f4')

    for i, grid in enumerate(f.iter_times()):
        t[i] = grid.time_as_datetime()
        pressure[i] = grid['pp']['x=10.0f, y=0.0f, z=0.0f']
    plt.plot(t, pressure)
    plt.ylabel('Pressure')

    dateFmt = mdates.DateFormatter('%H:%M:%S')
    plt.gca().xaxis.set_major_formatter(dateFmt)
    plt.gcf().autofmt_xdate()
    plt.gca().grid(True)

    plt.gcf().set_size_inches(8, 4)

    plt.savefig(next_plot_fname(main__file__))
    if show:
        vlt.mplshow()
コード例 #50
0
ファイル: test_mpl.py プロジェクト: zcl-maker/Viscid
def run_mpl_testA(show=False):
    logger.info("2D cell centered tests")

    x = np.array(np.linspace(-10, 10, 100), dtype=dtype)
    y = np.array(np.linspace(-10, 10, 120), dtype=dtype)
    z = np.array(np.linspace(-1, 1, 2), dtype=dtype)

    fld_s = viscid.empty([x, y, z], center='cell')
    Xcc, Ycc, Zcc = fld_s.get_crds_cc(shaped=True)  # pylint: disable=unused-variable
    fld_s[:, :, :] = np.sin(Xcc) + np.cos(Ycc)

    nrows = 4
    ncols = 1

    plt.subplot2grid((nrows, ncols), (0, 0))
    vlt.plot(fld_s, "y=20f", show=False, plot_opts="lin_0")
    plt.subplot2grid((nrows, ncols), (1, 0))
    vlt.plot(fld_s,
             "x=0f:20f,y=0f:5f",
             earth=True,
             show=False,
             plot_opts="x_-10_0,y_0_7")
    plt.subplot2grid((nrows, ncols), (2, 0))
    vlt.plot(fld_s, "y=0f", show=False, plot_opts="lin_-1_1")
    plt.subplot2grid((nrows, ncols), (3, 0))
    vlt.plot(fld_s,
             "z=0f,x=-20f:0f",
             earth=True,
             show=False,
             plot_opts="lin_-5_5")

    plt.suptitle("2d cell centered")
    vlt.auto_adjust_subplots()

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
コード例 #51
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--notwo", dest='notwo', action="store_true")
    parser.add_argument("--nothree", dest='nothree', action="store_true")
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser, default_verb=0)

    plot2d = not args.notwo
    plot3d = not args.nothree

    # plot2d = True
    # plot3d = True
    # args.show = True

    img = np.load(os.path.join(sample_dir, "logo.npy"))
    x = np.linspace(-1, 1, img.shape[0])
    y = np.linspace(-1, 1, img.shape[1])
    z = np.linspace(-1, 1, img.shape[2])
    logo = viscid.arrays2field([x, y, z], img)

    if 1:
        viscid.logger.info('Testing Line...')
        seeds = viscid.Line([-1, -1, 0], [1, 1, 2], n=5)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show)

    if 1:
        viscid.logger.info('Testing Plane...')
        seeds = viscid.Plane([0.0, 0.0, 0.0], [1, 1, 1], [1, 0, 0], 2, 2,
                             nl=160, nm=170, NL_are_vectors=True)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show)

    if 1:
        viscid.logger.info('Testing Volume...')
        seeds = viscid.Volume([-0.8, -0.8, -0.8], [0.8, 0.8, 0.8],
                              n=[64, 64, 3])
        # note: can't make a 2d plot of the volume w/o a slice
        run_test(logo, seeds, plot2d=False, plot3d=plot3d, add_title="3d",
                 show=args.show)

    if 1:
        viscid.logger.info('Testing Volume (with ignorable dim)...')
        seeds = viscid.Volume([-0.8, -0.8, 0.0], [0.8, 0.8, 0.0],
                              n=[64, 64, 1])
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="2d",
                 show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Sphere (phi, theta)...')
        seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170,
                              pole=[-1, -1, -1], theta_phi=False)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT",
                 show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Sphere (theta, phi)...')
        seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170,
                              pole=[-1, -1, -1], theta_phi=True)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP",
                 show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Cap (phi, theta)...')
        seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80,
                                    pole=[-1, -1, -1], theta_phi=False)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT",
                 view_kwargs=dict(azimuth=180, elevation=180), show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Cap (theta, phi)...')
        seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80,
                                    pole=[-1, -1, -1], theta_phi=True)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP",
                 view_kwargs=dict(azimuth=180, elevation=180), show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Patch...')
        seeds = viscid.SphericalPatch(p0=[0, 0, 0], p1=[0, -0, -1],
                                      max_alpha=30.0, max_beta=59.9,
                                      nalpha=65, nbeta=80, r=0.5, roll=45.0)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show)

    if 1:
        viscid.logger.info('Testing RectilinearMeshPoints...')
        f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[-1].xdmf'))
        slc = 'x=-40f:12f, y=-10f:10f, z=-10f:10f'
        b = f['b'][slc]
        z = b.get_crd('z')
        sheet_iz = np.argmin(b['x']**2, axis=2)
        sheet_pts = b['z=0:1'].get_points()
        sheet_pts[2, :] = z[sheet_iz].reshape(-1)
        isphere_mask = np.sum(sheet_pts[:2, :]**2, axis=0) < 5**2
        day_mask = sheet_pts[0:1, :] > -1.0
        sheet_pts[2, :] = np.choose(isphere_mask, [sheet_pts[2, :], 0])
        sheet_pts[2, :] = np.choose(day_mask, [sheet_pts[2, :], 0])
        nx, ny, _ = b.sshape
        sheet_seed = viscid.RectilinearMeshPoints(sheet_pts.reshape(3, nx, ny))
        vx_sheet = viscid.interp_nearest(f['vx'], sheet_seed)

        try:
            if not plot2d:
                raise ImportError
            from matplotlib import pyplot as plt
            from viscid.plot import vpyplot as vlt
            vlt.clf()
            vlt.plot(vx_sheet, symmetric=True)
            plt.savefig(next_plot_fname(__file__, series='2d'))
            if args.show:
                vlt.show()
        except ImportError:
            pass

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

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

        except ImportError:
            pass

    # prevent weird xorg bad-instructions on tear down
    if 'figure' in _global_ns and _global_ns['figure'] is not None:
        from viscid.plot import vlab
        vlab.mlab.close(_global_ns['figure'])

    return 0
コード例 #52
0
ファイル: test_mvi.py プロジェクト: KristoforMaynard/Viscid
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
コード例 #53
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
コード例 #54
0
ファイル: test_seed.py プロジェクト: KristoforMaynard/Viscid
def _main():
    global offscreen_vlab

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--notwo", dest='notwo', action="store_true")
    parser.add_argument("--nothree", dest='nothree', action="store_true")
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser, default_verb=0)

    plot2d = not args.notwo
    plot3d = not args.nothree

    # plot2d = True
    # plot3d = True
    # args.show = True

    offscreen_vlab = not args.show

    img = np.load(os.path.join(sample_dir, "logo.npy"))
    x = np.linspace(-1, 1, img.shape[0])
    y = np.linspace(-1, 1, img.shape[1])
    z = np.linspace(-1, 1, img.shape[2])
    logo = viscid.arrays2field([x, y, z], img)

    if 1:
        viscid.logger.info('Testing Point with custom local coordinates...')
        pts = np.vstack([[-1, -0.5, 0, 0.5, 1],
                         [-1, -0.5, 0, 0.5, 1],
                         [ 0,  0.5, 1, 1.5, 2]])
        local_crds = viscid.asarray_datetime64([0, 60, 120, 180, 240],
                                               conservative=True)
        seeds = viscid.Point(pts, local_crds=local_crds)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show)

    if 1:
        viscid.logger.info('Testing Line...')
        seeds = viscid.Line([-1, -1, 0], [1, 1, 2], n=5)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show)

    if 1:
        viscid.logger.info('Testing Plane...')
        seeds = viscid.Plane([0.0, 0.0, 0.0], [1, 1, 1], [1, 0, 0], 2, 2,
                             nl=160, nm=170, NL_are_vectors=True)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show)

    if 1:
        viscid.logger.info('Testing Volume...')
        seeds = viscid.Volume([-0.8, -0.8, -0.8], [0.8, 0.8, 0.8],
                              n=[64, 64, 3])
        # note: can't make a 2d plot of the volume w/o a slice
        run_test(logo, seeds, plot2d=False, plot3d=plot3d, add_title="3d",
                 show=args.show)

    if 1:
        viscid.logger.info('Testing Volume (with ignorable dim)...')
        seeds = viscid.Volume([-0.8, -0.8, 0.0], [0.8, 0.8, 0.0],
                              n=[64, 64, 1])
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="2d",
                 show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Sphere (phi, theta)...')
        seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170,
                              pole=[-1, -1, -1], theta_phi=False)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT",
                 show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Sphere (theta, phi)...')
        seeds = viscid.Sphere([0, 0, 0], r=1.0, ntheta=160, nphi=170,
                              pole=[-1, -1, -1], theta_phi=True)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP",
                 show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Cap (phi, theta)...')
        seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80,
                                    pole=[-1, -1, -1], theta_phi=False)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="PT",
                 view_kwargs=dict(azimuth=180, elevation=180), show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Cap (theta, phi)...')
        seeds = viscid.SphericalCap(p0=[0, 0, 0], r=1.0, ntheta=64, nphi=80,
                                    pole=[-1, -1, -1], theta_phi=True)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, add_title="TP",
                 view_kwargs=dict(azimuth=180, elevation=180), show=args.show)

    if 1:
        viscid.logger.info('Testing Spherical Patch...')
        seeds = viscid.SphericalPatch(p0=[0, 0, 0], p1=[0, -0, -1],
                                      max_alpha=30.0, max_beta=59.9,
                                      nalpha=65, nbeta=80, r=0.5, roll=45.0)
        run_test(logo, seeds, plot2d=plot2d, plot3d=plot3d, show=args.show)

    if 1:
        # this spline test is very custom
        viscid.logger.info('Testing Spline...')
        try:
            import scipy.interpolate as interpolate
        except ImportError:
            msg = "XFail: ImportError (is scipy installed?)"
            if plot2d:
                try:
                    from viscid.plot import vpyplot as vlt
                    from matplotlib import pyplot as plt
                    plt.clf()
                    plt.annotate(msg, xy=(0.3, 0.4), xycoords='axes fraction')
                    plt.savefig(next_plot_fname(__file__, series='2d'))
                    plt.savefig(next_plot_fname(__file__, series='2d'))
                    plt.savefig(next_plot_fname(__file__, series='3d'))
                    if args.show:
                        plt.show()
                except ImportError:
                    pass
        else:
            knots = np.array([[ 0.2,  0.5, 0.0], [-0.2,  0.5, 0.2],
                              [-0.2,  0.0, 0.4], [ 0.2,  0.0, 0.2],
                              [ 0.2, -0.5, 0.0], [-0.2, -0.5, 0.2]]).T
            seed_name = "Spline"
            fld = logo
            seeds = viscid.Spline(knots)
            seed_pts = seeds.get_points()
            interp_fld = viscid.interp_trilin(fld, seeds)

            if plot2d:
                try:
                    from viscid.plot import vpyplot as vlt
                    from matplotlib import pyplot as plt
                    plt.clf()
                    vlt.plot(interp_fld)
                    plt.title(seed_name)
                    plt.savefig(next_plot_fname(__file__, series='2d'))
                    if args.show:
                        plt.show()

                    plt.clf()
                    from matplotlib import rcParams
                    _ms = rcParams['lines.markersize']
                    plt.gca().scatter(knots[0, :], knots[1, :],
                                      s=(2 * _ms)**2, marker='^', color='y')
                    plt.gca().scatter(seed_pts[0, :], seed_pts[1, :],
                                      s=(1.5 * _ms)**2, marker='o', color='k')
                    vlt.plot2d_line(seed_pts, scalars=interp_fld.flat_data,
                                    symdir='z')
                    plt.title(seed_name)
                    plt.savefig(next_plot_fname(__file__, series='2d'))
                    if args.show:
                        plt.show()
                except ImportError:
                    pass
            if plot3d:
                try:
                    vlab, _ = get_mvi_fig()
                    vlab.points3d(knots[0], knots[1], knots[2],
                                  color=(1.0, 1.0, 0), scale_mode='none',
                                  scale_factor=0.04)
                    p = vlab.points3d(seed_pts[0], seed_pts[1], seed_pts[2],
                                      color=(0, 0, 0), scale_mode='none',
                                      scale_factor=0.03)
                    vlab.plot_line(seed_pts, scalars=interp_fld.flat_data,
                                   tube_radius=0.01)
                    vlab.axes(p)
                    vlab.title(seed_name)
                    vlab.mlab.roll(-90.0)
                    vlab.savefig(next_plot_fname(__file__, series='3d'))
                    if args.show:
                        vlab.show(stop=True)
                except ImportError:
                    pass

    if 1:
        viscid.logger.info('Testing RectilinearMeshPoints...')
        f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[-1].xdmf'))
        slc = 'x=-40j:12j, y=-10j:10j, z=-10j:10j'
        b = f['b'][slc]
        z = b.get_crd('z')
        sheet_iz = np.argmin(b['x']**2, axis=2)
        sheet_pts = b['z=0:1'].get_points()
        sheet_pts[2, :] = z[sheet_iz].reshape(-1)
        isphere_mask = np.sum(sheet_pts[:2, :]**2, axis=0) < 5**2
        day_mask = sheet_pts[0:1, :] > -1.0
        sheet_pts[2, :] = np.choose(isphere_mask, [sheet_pts[2, :], 0])
        sheet_pts[2, :] = np.choose(day_mask, [sheet_pts[2, :], 0])
        nx, ny, _ = b.sshape
        sheet_seed = viscid.RectilinearMeshPoints(sheet_pts.reshape(3, nx, ny))
        vx_sheet = viscid.interp_nearest(f['vx'], sheet_seed)

        try:
            if not plot2d:
                raise ImportError
            from viscid.plot import vpyplot as vlt
            from matplotlib import pyplot as plt
            vlt.clf()
            vlt.plot(vx_sheet, symmetric=True)
            plt.savefig(next_plot_fname(__file__, series='2d'))
            if args.show:
                vlt.show()
        except ImportError:
            pass

        try:
            if not plot3d:
                raise ImportError
            vlab, _ = get_mvi_fig()
            mesh = vlab.mesh_from_seeds(sheet_seed, scalars=vx_sheet,
                                        clim=(-400, 400))
            vlab.plot_earth_3d(crd_system=b)
            vlab.view(azimuth=+90.0 + 45.0, elevation=90.0 - 25.0,
                      distance=30.0, focalpoint=(-10.0, +1.0, +1.0))

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

        except ImportError:
            pass

    # prevent weird xorg bad-instructions on tear down
    if 'figure' in _global_ns and _global_ns['figure'] is not None:
        from viscid.plot import vlab
        vlab.mlab.close(_global_ns['figure'])

    return 0
コード例 #55
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--prof", action="store_true")
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    b = viscid.make_dipole(l=(-5, -5, -5), h=(5, 5, 5), n=(255, 255, 127),
                           m=(0, 0, -1))
    b2 = np.sum(b * b, axis=b.nr_comp)

    if args.prof:
        print("Without boundaries")
        viscid.timeit(viscid.grad, b2, bnd=False, timeit_repeat=10,
                      timeit_print_stats=True)
        print("With boundaries")
        viscid.timeit(viscid.grad, b2, bnd=True, timeit_repeat=10,
                      timeit_print_stats=True)

    grad_b2 = viscid.grad(b2)
    grad_b2.pretty_name = r"$\nabla$ B$^2$"
    conv = viscid.convective_deriv(b)
    conv.pretty_name = r"(B $\cdot \nabla$) B"

    _ = plt.figure(figsize=(9, 4.2))

    ax1 = vlt.subplot(231)
    vlt.plot(b2['z=0f'], logscale=True)
    vlt.plot(b2['z=0f'], logscale=True, style='contour', levels=10, colors='grey')
    # vlt.plot2d_quiver(viscid.normalize(b['z=0f']), step=16, pivot='mid')
    ax2 = vlt.subplot(234)
    vlt.plot(b2['y=0f'], logscale=True)
    vlt.plot(b2['y=0f'], logscale=True, style='contour', levels=10, colors='grey')
    vlt.plot2d_quiver(viscid.normalize(b['y=0f'], preferred='numpy'),
                      step=16, pivot='mid')

    vlt.subplot(232, sharex=ax1, sharey=ax1)
    vlt.plot(1e-4 + viscid.magnitude(grad_b2['z=0f']), logscale=True)
    vlt.plot(1e-4 + viscid.magnitude(grad_b2['z=0f']), logscale=True,
             style='contour', levels=10, colors='grey')
    vlt.plot2d_quiver(viscid.normalize(grad_b2['z=0f']), step=16, pivot='mid')
    vlt.subplot(235, sharex=ax2, sharey=ax2)
    vlt.plot(1e-4 + viscid.magnitude(grad_b2['y=0f']), logscale=True)
    vlt.plot(1e-4 + viscid.magnitude(grad_b2['y=0f']), logscale=True,
             style='contour', levels=10, colors='grey')
    vlt.plot2d_quiver(viscid.normalize(grad_b2['y=0f']), step=16, pivot='mid')

    vlt.subplot(233, sharex=ax1, sharey=ax1)
    vlt.plot(viscid.magnitude(conv['z=0f']), logscale=True)
    vlt.plot(viscid.magnitude(conv['z=0f']), logscale=True,
             style='contour', levels=10, colors='grey')
    vlt.plot2d_quiver(viscid.normalize(conv['z=0f']), step=16, pivot='mid')
    vlt.subplot(236, sharex=ax2, sharey=ax2)
    vlt.plot(viscid.magnitude(conv['y=0f']), logscale=True)
    vlt.plot(viscid.magnitude(conv['y=0f']), logscale=True,
             style='contour', levels=10, colors='grey')
    vlt.plot2d_quiver(viscid.normalize(conv['y=0f']), step=16, pivot='mid')

    vlt.auto_adjust_subplots()

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        vlt.show()

    return 0
コード例 #56
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--notwo", dest='notwo', action="store_true")
    parser.add_argument("--nothree", dest='nothree', action="store_true")
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser, default_verb=0)

    plot2d = not args.notwo
    plot3d = not args.nothree

    # #################################################
    # viscid.logger.info("Testing field lines on 2d field...")
    B = viscid.make_dipole(twod=True)
    line = viscid.seed.Line((0.2, 0.0, 0.0), (1.0, 0.0, 0.0), 10)
    obound0 = np.array([-4, -4, -4], dtype=B.data.dtype)
    obound1 = np.array([4, 4, 4], dtype=B.data.dtype)
    run_test(B,
             line,
             plot2d=plot2d,
             plot3d=plot3d,
             title='2D',
             show=args.show,
             ibound=0.07,
             obound0=obound0,
             obound1=obound1)

    #################################################
    viscid.logger.info("Testing field lines on 3d field...")
    B = viscid.make_dipole(m=[0.2, 0.3, -0.9])
    sphere = viscid.seed.Sphere((0.0, 0.0, 0.0), 2.0, ntheta=20, nphi=10)
    obound0 = np.array([-4, -4, -4], dtype=B.data.dtype)
    obound1 = np.array([4, 4, 4], dtype=B.data.dtype)
    run_test(B,
             sphere,
             plot2d=plot2d,
             plot3d=plot3d,
             title='3D',
             show=args.show,
             ibound=0.12,
             obound0=obound0,
             obound1=obound1,
             method=viscid.RK12)

    # The Remainder of this test makes sure higher order methods are indeed
    # more accurate than lower order methods... this could find a bug in
    # the integrators

    ##################################################
    # test accuracy of streamlines in an ideal dipole
    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=(256, 256, 256),
                           l=(-25, -25, -25),
                           h=(25, 25, 25),
                           dtype='f8')

    seeds_xyz = seeds.get_points()
    # seeds_lsp = viscid.xyz2lsrlp(seeds_xyz, cotr=cotr, crd_system=B)[(0, 3), :]
    seeds_lsp = viscid.xyz2lsrlp(seeds_xyz, cotr=cotr, crd_system=B)[(0, 3), :]

    e1_lines, e1_lsps, t_e1 = lines_and_lsps(B,
                                             seeds,
                                             method='euler1',
                                             ibound=1.0,
                                             cotr=cotr)
    rk2_lines, rk2_lsps, t_rk2 = lines_and_lsps(B,
                                                seeds,
                                                method='rk2',
                                                ibound=1.0,
                                                cotr=cotr)
    rk4_lines, rk4_lsps, t_rk4 = lines_and_lsps(B,
                                                seeds,
                                                method='rk4',
                                                ibound=1.0,
                                                cotr=cotr)
    e1a_lines, e1a_lsps, t_e1a = lines_and_lsps(B,
                                                seeds,
                                                method='euler1a',
                                                ibound=1.0,
                                                cotr=cotr)
    rk12_lines, rk12_lsps, t_rk12 = lines_and_lsps(B,
                                                   seeds,
                                                   method='rk12',
                                                   ibound=1.0,
                                                   cotr=cotr)
    rk45_lines, rk45_lsps, t_rk45 = lines_and_lsps(B,
                                                   seeds,
                                                   method='rk45',
                                                   ibound=1.0,
                                                   cotr=cotr)

    def _calc_rel_diff(_lsp, _ideal_lsp, _d):
        _diffs = []
        for _ilsp, _iideal in zip(_lsp, _ideal_lsp.T):
            _a = _ilsp[_d, :]
            _b = _iideal[_d]
            _diffs.append((_a - _b) / _b)
        return _diffs

    lshell_diff_e1 = _calc_rel_diff(e1_lsps, seeds_lsp, 0)
    phi_diff_e1 = _calc_rel_diff(e1_lsps, seeds_lsp, 1)

    lshell_diff_rk2 = _calc_rel_diff(rk2_lsps, seeds_lsp, 0)
    phi_diff_rk2 = _calc_rel_diff(rk2_lsps, seeds_lsp, 1)

    lshell_diff_rk4 = _calc_rel_diff(rk4_lsps, seeds_lsp, 0)
    phi_diff_rk4 = _calc_rel_diff(rk4_lsps, seeds_lsp, 1)

    lshell_diff_e1a = _calc_rel_diff(e1a_lsps, seeds_lsp, 0)
    phi_diff_e1a = _calc_rel_diff(e1a_lsps, seeds_lsp, 1)

    lshell_diff_rk12 = _calc_rel_diff(rk12_lsps, seeds_lsp, 0)
    phi_diff_rk12 = _calc_rel_diff(rk12_lsps, seeds_lsp, 1)

    lshell_diff_rk45 = _calc_rel_diff(rk45_lsps, seeds_lsp, 0)
    phi_diff_rk45 = _calc_rel_diff(rk45_lsps, seeds_lsp, 1)

    methods = [
        'Euler 1', 'Runge Kutta 2', 'Runge Kutta 4', 'Euler 1 Adaptive Step',
        'Runge Kutta 12 Adaptive Step', 'Runge Kutta 45 Adaptive Step'
    ]
    wall_ts = [t_e1, t_rk2, t_rk4, t_e1a, t_rk12, t_rk45]
    all_lines = [
        e1_lines, rk2_lines, rk4_lines, e1a_lines, rk12_lines, rk45_lines
    ]
    all_lshell_diffs = [
        lshell_diff_e1, lshell_diff_rk2, lshell_diff_rk4, lshell_diff_e1a,
        lshell_diff_rk12, lshell_diff_rk45
    ]
    lshell_diffs = [
        np.abs(np.concatenate(lshell_diff_e1, axis=0)),
        np.abs(np.concatenate(lshell_diff_rk2, axis=0)),
        np.abs(np.concatenate(lshell_diff_rk4, axis=0)),
        np.abs(np.concatenate(lshell_diff_e1a, axis=0)),
        np.abs(np.concatenate(lshell_diff_rk12, axis=0)),
        np.abs(np.concatenate(lshell_diff_rk45, axis=0))
    ]
    phi_diffs = [
        np.abs(np.concatenate(phi_diff_e1, axis=0)),
        np.abs(np.concatenate(phi_diff_rk2, axis=0)),
        np.abs(np.concatenate(phi_diff_rk4, axis=0)),
        np.abs(np.concatenate(phi_diff_e1a, axis=0)),
        np.abs(np.concatenate(phi_diff_rk12, axis=0)),
        np.abs(np.concatenate(phi_diff_rk45, axis=0))
    ]
    npts = [len(lsd) for lsd in lshell_diffs]
    lshell_75 = [np.percentile(lsdiff, 75) for lsdiff in lshell_diffs]

    # # 3D DEBUG PLOT:: for really getting under the covers
    # vlab.clf()
    # earth1 = viscid.seed.Sphere((0.0, 0.0, 0.0), 1.0, pole=-m, ntheta=60, nphi=120,
    #                             thetalim=(15, 165), philim=(0, 360))
    # ls1 = viscid.xyz2lsrlp(earth1.get_points(), cotr=cotr, crd_system='gse')[0, :]
    # earth2 = viscid.seed.Sphere((0.0, 0.0, 0.0), 2.0, pole=-m, ntheta=60, nphi=120,
    #                             thetalim=(15, 165), philim=(0, 360))
    # ls2 = viscid.xyz2lsrlp(earth2.get_points(), cotr=cotr, crd_system='gse')[0, :]
    # earth4 = viscid.seed.Sphere((0.0, 0.0, 0.0), 4.0, pole=-m, ntheta=60, nphi=120,
    #                             thetalim=(15, 165), philim=(0, 360))
    # ls4 = viscid.xyz2lsrlp(earth4.get_points(), cotr=cotr, crd_system='gse')[0, :]
    # clim = [2.0, 6.0]
    # vlab.mesh_from_seeds(earth1, scalars=ls1, clim=clim, logscale=True)
    # vlab.mesh_from_seeds(earth2, scalars=ls2, clim=clim, logscale=True, opacity=0.5)
    # vlab.mesh_from_seeds(earth4, scalars=ls2, clim=clim, logscale=True, opacity=0.25)
    # vlab.plot3d_lines(e1_lines, scalars=[_e1_lsp[0, :] for _e1_lsp in e1_lsps],
    #                  clim=clim, logscale=True)
    # vlab.colorbar(title="L-Shell")
    # vlab.show()

    assert lshell_75[1] < lshell_75[0], "RK2 should have less error than Euler"
    assert lshell_75[2] < lshell_75[1], "RK4 should have less error than RK2"
    assert lshell_75[3] < lshell_75[
        0], "Euler 1a should have less error than Euler 1"
    assert lshell_75[4] < lshell_75[
        0], "RK 12 should have less error than Euler 1"
    assert lshell_75[5] < lshell_75[1], "RK 45 should have less error than RK2"

    try:
        if not plot2d:
            raise ImportError
        from matplotlib import pyplot as plt
        from viscid.plot import vpyplot as vlt

        # stats on error for all points on all lines
        _ = plt.figure(figsize=(15, 8))
        ax1 = vlt.subplot(121)
        v = plt.violinplot(lshell_diffs,
                           showextrema=False,
                           showmedians=False,
                           vert=False)
        colors = set_violin_colors(v)
        xl, xh = plt.gca().get_xlim()
        for i, txt, c in zip(count(), methods, colors):
            t_txt = ", took {0:.2e} seconds".format(wall_ts[i])
            stat_txt = format_data_range(lshell_diffs[i])
            plt.text(xl + 0.35 * (xh - xl), i + 1.15, txt + t_txt, color=c)
            plt.text(xl + 0.35 * (xh - xl), i + 0.85, stat_txt, color=c)
        ax1.get_yaxis().set_visible(False)
        plt.title('L-Shell')
        plt.xlabel('Relative Difference from Ideal (as fraction)')

        ax2 = vlt.subplot(122)
        v = plt.violinplot(phi_diffs,
                           showextrema=False,
                           showmedians=False,
                           vert=False)
        colors = set_violin_colors(v)
        xl, xh = plt.gca().get_xlim()
        for i, txt, c in zip(count(), methods, colors):
            t_txt = ", took {0:.2e} seconds".format(wall_ts[i])
            stat_txt = format_data_range(phi_diffs[i])
            plt.text(xl + 0.35 * (xh - xl), i + 1.15, txt + t_txt, color=c)
            plt.text(xl + 0.35 * (xh - xl), i + 0.85, stat_txt, color=c)
        ax2.get_yaxis().set_visible(False)
        plt.title('Longitude')
        plt.xlabel('Relative Difference from Ideal (as fraction)')

        vlt.auto_adjust_subplots()

        vlt.savefig(next_plot_fname(__file__, series='q2'))
        if args.show:
            vlt.show()

        # stats for ds for all points on all lines
        _ = plt.figure(figsize=(10, 8))
        ax1 = vlt.subplot(111)

        ds = [
            np.concatenate([
                np.linalg.norm(_l[:, 1:] - _l[:, :-1], axis=0) for _l in lines
            ]) for lines in all_lines
        ]
        v = plt.violinplot(ds,
                           showextrema=False,
                           showmedians=False,
                           vert=False)
        colors = set_violin_colors(v)
        xl, xh = plt.gca().get_xlim()
        for i, txt, c in zip(count(), methods, colors):
            stat_txt = format_data_range(ds[i])
            plt.text(xl + 0.01 * (xh - xl), i + 1.15, txt, color=c)
            plt.text(xl + 0.01 * (xh - xl), i + 0.85, stat_txt, color=c)
        ax1.get_yaxis().set_visible(False)
        plt.xscale('log')
        plt.title('Step Size')
        plt.xlabel('Absolute Step Size')
        vlt.savefig(next_plot_fname(__file__, series='q2'))
        if args.show:
            vlt.show()

        # random other information
        _ = plt.figure(figsize=(13, 10))

        ## wall time for each method
        vlt.subplot(221)
        plt.scatter(range(len(methods)),
                    wall_ts,
                    color=colors,
                    s=150,
                    marker='s',
                    edgecolors='none')
        for i, meth in enumerate(methods):
            meth = meth.replace(" Adaptive Step", "\nAdaptive Step")
            plt.annotate(meth, (i, wall_ts[i]),
                         xytext=(0, 15.0),
                         color=colors[i],
                         horizontalalignment='center',
                         verticalalignment='bottom',
                         textcoords='offset points')
        plt.ylabel("Wall Time (s)")
        x_padding = 0.5
        plt.xlim(-x_padding, len(methods) - x_padding)
        yl, yh = np.min(wall_ts), np.max(wall_ts)
        y_padding = 0.4 * (yh - yl)
        plt.ylim(yl - y_padding, yh + y_padding)
        plt.gca().get_xaxis().set_visible(False)
        for _which in ('right', 'top'):
            plt.gca().spines[_which].set_color('none')

        ## number of points calculated for each method
        vlt.subplot(222)
        plt.scatter(range(len(methods)),
                    npts,
                    color=colors,
                    s=150,
                    marker='s',
                    edgecolors='none')
        for i, meth in enumerate(methods):
            meth = meth.replace(" Adaptive Step", "\nAdaptive Step")
            plt.annotate(meth, (i, npts[i]),
                         xytext=(0, 15.0),
                         color=colors[i],
                         horizontalalignment='center',
                         verticalalignment='bottom',
                         textcoords='offset points')
        plt.ylabel("Number of Streamline Points Calculated")
        x_padding = 0.5
        plt.xlim(-x_padding, len(methods) - x_padding)
        yl, yh = np.min(npts), np.max(npts)
        y_padding = 0.4 * (yh - yl)
        plt.ylim(yl - y_padding, yh + y_padding)
        plt.gca().get_xaxis().set_visible(False)
        for _which in ('right', 'top'):
            plt.gca().spines[_which].set_color('none')

        ## Wall time per segment, this should show the overhead of the method
        vlt.subplot(223)
        wall_t_per_seg = np.asarray(wall_ts) / np.asarray(npts)
        plt.scatter(range(len(methods)),
                    wall_t_per_seg,
                    color=colors,
                    s=150,
                    marker='s',
                    edgecolors='none')
        for i, meth in enumerate(methods):
            meth = meth.replace(" Adaptive Step", "\nAdaptive Step")
            plt.annotate(meth, (i, wall_t_per_seg[i]),
                         xytext=(0, 15.0),
                         color=colors[i],
                         horizontalalignment='center',
                         verticalalignment='bottom',
                         textcoords='offset points')
        plt.ylabel("Wall Time Per Line Segment")
        x_padding = 0.5
        plt.xlim(-x_padding, len(methods) - x_padding)
        yl, yh = np.min(wall_t_per_seg), np.max(wall_t_per_seg)
        y_padding = 0.4 * (yh - yl)
        plt.ylim(yl - y_padding, yh + y_padding)
        plt.gca().get_xaxis().set_visible(False)
        plt.gca().xaxis.set_major_formatter(viscid.plot.mpl_extra.steve_axfmt)
        for _which in ('right', 'top'):
            plt.gca().spines[_which].set_color('none')

        ## 75th percentile of l-shell error for each method
        vlt.subplot(224)
        plt.scatter(range(len(methods)),
                    lshell_75,
                    color=colors,
                    s=150,
                    marker='s',
                    edgecolors='none')
        plt.yscale('log')

        for i, meth in enumerate(methods):
            meth = meth.replace(" Adaptive Step", "\nAdaptive Step")
            plt.annotate(meth, (i, lshell_75[i]),
                         xytext=(0, 15.0),
                         color=colors[i],
                         horizontalalignment='center',
                         verticalalignment='bottom',
                         textcoords='offset points')
        plt.ylabel("75th Percentile of Relative L-Shell Error")
        x_padding = 0.5
        plt.xlim(-x_padding, len(methods) - x_padding)
        ymin, ymax = np.min(lshell_75), np.max(lshell_75)
        plt.ylim(0.75 * ymin, 2.5 * ymax)
        plt.gca().get_xaxis().set_visible(False)
        for _which in ('right', 'top'):
            plt.gca().spines[_which].set_color('none')

        vlt.auto_adjust_subplots(subplot_params=dict(wspace=0.25, hspace=0.15))

        vlt.savefig(next_plot_fname(__file__, series='q2'))
        if args.show:
            vlt.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 args.show,
                              bgcolor=(1, 1, 1),
                              fgcolor=(0, 0, 0))
            _global_ns['figure'] = fig

        for i, method in zip(count(), methods):
            # if i in (3, 4):
            #     next_plot_fname(__file__, series='q3')
            #     print(i, "::", [line.shape[1] for line in all_lines[i]])
            #     # continue
            vlab.clf()
            _lshell_diff = [np.abs(s) for s in all_lshell_diffs[i]]
            vlab.plot3d_lines(all_lines[i], scalars=_lshell_diff)
            vlab.colorbar(title="Relative L-Shell Error (as fraction)")
            vlab.title(method, size=0.5)
            vlab.orientation_axes()
            vlab.view(azimuth=40,
                      elevation=140,
                      distance=80.0,
                      focalpoint=[0, 0, 0])
            vlab.savefig(next_plot_fname(__file__, series='q3'))
            if args.show:
                vlab.show()
    except ImportError:
        pass

    # prevent weird xorg bad-instructions on tear down
    if 'figure' in _global_ns and _global_ns['figure'] is not None:
        from viscid.plot import vlab
        vlab.mlab.close(_global_ns['figure'])

    return 0
コード例 #57
0
ファイル: test_numpy.py プロジェクト: KristoforMaynard/Viscid
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)
    dtype = 'float32'

    ########################################################################
    # hard core test transpose (since this is used for mapfield transforms)
    x = np.array(np.linspace(1, -1, 9), dtype=dtype)
    y = np.array(np.linspace(-1, 1, 9), dtype=dtype)
    z = np.array(np.linspace(-1, 1, 9), dtype=dtype)
    vI1 = viscid.empty([x, y, z],
                       nr_comps=3,
                       name='V',
                       center='cell',
                       layout='interlaced')
    vI2 = viscid.empty([z, y, x],
                       nr_comps=3,
                       name='V',
                       center='cell',
                       layout='interlaced',
                       crd_names='zyx')
    vF1 = viscid.empty([x, y, z],
                       nr_comps=3,
                       name='V',
                       center='cell',
                       layout='flat')
    vF2 = viscid.empty([z, y, x],
                       nr_comps=3,
                       name='V',
                       center='cell',
                       layout='flat',
                       crd_names='zyx')
    X1, Y1, Z1 = vI1.get_crds_cc(shaped=True)
    X2, Y2, Z2 = vI2.get_crds_cc(shaped=True)

    for v in (vI1, vF1):
        v['x'] = (0.5 * X1) + (0.0 * Y1) + (0.0 * Z1)
        v['y'] = (0.0 * X1) + (0.5 * Y1) + (0.5 * Z1)
        v['z'] = (0.0 * X1) + (0.5 * Y1) + (0.5 * Z1)
    for v in (vI2, vF2):
        v['z'] = (0.5 * X2) + (0.5 * Y2) + (0.0 * Z2)
        v['y'] = (0.5 * X2) + (0.5 * Y2) + (0.0 * Z2)
        v['x'] = (0.0 * X2) + (0.0 * Y2) + (0.5 * Z2)

    assert_different(vI1, vI2)

    # test some straight up transposes of both interlaced and flat fields
    assert_similar(vI1.spatial_transpose(), vI2)
    assert_similar(vI1.ST, vI2)
    assert_similar(vF1.spatial_transpose(), vF2)
    assert_similar(vI1.transpose(), vF2)
    assert_similar(vI1.T, vF2)
    assert_different(vI1.transpose(), vI2)
    assert_similar(vF1.transpose(), vI2)
    assert_different(vF1.transpose(), vF2)
    assert_similar(np.transpose(vI1), vF2)
    assert_similar(np.transpose(vF1), vI2)

    # now specify specific axes using all 3 interfaces
    assert_similar(vI1.spatial_transpose('x', 'z', 'y'), vI1)
    assert_similar(np.transpose(vI1, axes=[0, 2, 1, 3]), vI1)
    assert_similar(vI1.transpose(0, 2, 1, 3), vI1)
    assert_similar(vF1.spatial_transpose('x', 'z', 'y'), vF1)
    assert_similar(np.transpose(vF1, axes=(0, 1, 3, 2)), vF1)
    assert_similar(vF1.transpose(0, 1, 3, 2), vF1)

    # now test swapaxes since that uses
    assert_similar(vI1.swapaxes(1, 2), vI1)
    assert_similar(np.swapaxes(vI1, 1, 2), vI1)
    assert_similar(vI1.swap_crd_axes('y', 'z'), vI1)

    ##############################
    # test some other mathy stuff
    x = np.array(np.linspace(-1, 1, 2), dtype=dtype)
    y = np.array(np.linspace(-2, 2, 30), dtype=dtype)
    z = np.array(np.linspace(-5, 5, 90), dtype=dtype)
    v = viscid.empty([x, y, z],
                     nr_comps=3,
                     name='V',
                     center='cell',
                     layout='interlaced')
    X, Y, Z = v.get_crds_cc(shaped=True)

    v['x'] = (0.5 * X**2) + (Y) + (0.0 * Z)
    v['y'] = (0.0 * X) + (0.5 * Y**2) + (0.0 * Z)
    v['z'] = (0.0 * X) + (0.0 * Y) + (0.5 * Z**2)

    mag = viscid.magnitude(v)
    mag2 = np.sqrt(np.sum(v * v, axis=v.nr_comp))
    another = np.transpose(mag)

    plt.subplot(151)
    vlt.plot(v['x'])
    plt.subplot(152)
    vlt.plot(v['y'])
    plt.subplot(153)
    vlt.plot(mag)
    plt.subplot(154)
    vlt.plot(mag2)
    plt.subplot(155)
    vlt.plot(another)

    plt.savefig(next_plot_fname(__file__))
    if args.show:
        plt.show()

    return 0