Esempio n. 1
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(_viscid_root + "/../sample/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"])
    if args.show:
        mpl.tighten()
        mpl.mplshow()
    plt.clf()

    ####### test ascii files
    f_tab = viscid.load_file(_viscid_root + "/../sample/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"])
    if args.show:
        mpl.tighten()
        mpl.mplshow()
    plt.clf()
Esempio n. 2
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(_viscid_root + '/../sample/test.asc')
    mpl.plot(f['c1'], show=args.show)
Esempio n. 3
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
Esempio n. 4
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'))

    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
Esempio n. 5
0
def main():
    parser = argparse.ArgumentParser(description="Test divergence")
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    dtype = 'float64'

    # use 512 512 256 to inspect memory related things
    x = np.array(np.linspace(-0.5, 0.5, 256), dtype=dtype)
    y = np.array(np.linspace(-0.5, 0.5, 256), dtype=dtype)
    z = np.array(np.linspace(-0.5, 0.5, 64), dtype=dtype)

    v = viscid.empty([x, y, z], name="V", nr_comps=3, center="cell",
                     layout="interlaced")
    exact_cc = viscid.empty([x, y, z], name="exact_cc", center='cell')


    Xcc, Ycc, Zcc = exact_cc.get_crds_cc(shaped=True) #pylint: disable=W0612

    v['x'] = ne.evaluate("(sin(Xcc))")  # + Zcc
    v['y'] = ne.evaluate("(cos(Ycc))")  # + Xcc# + Zcc
    v['z'] = ne.evaluate("-((sin(Zcc)))")  # + Xcc# + Ycc
    exact_cc[:, :, :] = ne.evaluate("cos(Xcc) - sin(Ycc) - cos(Zcc)")

    logger.info("node centered tests")
    v_nc = v.as_centered('node')
    exact_nc = viscid.empty_like(v_nc['x'])
    X, Y, Z = exact_nc.get_crds_nc(shaped=True) #pylint: disable=W0612
    exact_nc[:, :, :] = ne.evaluate("cos(X) - sin(Y) - cos(Z)")
    # FIXME: why is the error so much larger here?
    run_div_test(v_nc, exact_nc, show=args.show, ignore_inexact=True)

    logger.info("cell centered tests")
    v_cc = v_nc.as_centered('cell')
    run_div_test(v_cc, exact_cc, show=args.show)
Esempio n. 6
0
def main():
    parser = argparse.ArgumentParser(description="Test calc")
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    run_mpl_testA(show=args.show)
    run_mpl_testB(show=args.show)
Esempio n. 7
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)
    dtype = "float32"

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

    v["x"] = 0.5 * X ** 2 + Y + 0.0 * Z
    v["y"] = 0.0 * X + 0.5 * Y ** 2 + 0.0 * Z
    v["z"] = 0.0 * X + 0.0 * Y + 0.5 * Z ** 2

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

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

    if args.show:
        plt.show()

    return 0
Esempio n. 8
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
Esempio n. 9
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
Esempio n. 10
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    f3d = viscid.load_file(_viscid_root + '/../sample/sample.3df.xdmf',
                           grid_type=MyGGCMGrid)

    pp = f3d['pp']
    rr = f3d['rr']
    T = f3d['T']
    # bmag = timeit(lambda: f3d['bmag'])
    bmag = f3d["bmag"]

    plt.subplot(141)
    mpl.plot(pp, "y=0f,x=-20f:10f", plot_opts="log", earth=True, show=False)
    plt.subplot(142)
    mpl.plot(rr, "y=0f,x=-20f:10f", plot_opts="log", earth=True, show=False)
    plt.subplot(143)
    mpl.plot(T, "y=0f,x=-20f:10f", plot_opts="log", earth=True, show=False)
    plt.subplot(144)
    mpl.plot(bmag, "y=0f,x=-20f:10f", plot_opts="log", earth=True, show=False)

    if args.show:
        mpl.mplshow()
Esempio n. 11
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    args = vutil.common_argparse(parser)  # pylint: disable=unused-variable

    fiof = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.iof.xdmf'))

    fac = fiof['fac_tot']

    fac_mf = viscid.as_mapfield(fac)
    fac_sphere = viscid.as_spherefield(fac)
    if fac_sphere is not fac:
        raise RuntimeError("cenversion should have been a noop")

    fac_mf_rad = viscid.as_mapfield(fac, units='rad')
    fac_sphere_rad = viscid.as_spherefield(fac, units='rad')

    fac_mf_sphere = viscid.as_spherefield(fac_mf)
    assert_similar(fac_mf_sphere, fac)

    fac_mf_sphere_deg_rad = viscid.as_spherefield(fac_mf, units='rad')
    assert_similar(fac_mf_sphere_deg_rad, fac_sphere_rad)

    fac_mf_sphere_rad_deg = viscid.as_spherefield(fac_mf_rad, units='deg')
    assert_similar(fac_mf_sphere_rad_deg, fac)

    fac_sphere_mf_rad_deg = viscid.as_mapfield(fac_sphere_rad, units='deg')
    assert_similar(fac_sphere_mf_rad_deg, fac_mf)

    fac_sphere_mf_rad_rad = viscid.as_mapfield(fac_sphere_rad, units='rad')
    assert_similar(fac_sphere_mf_rad_rad, fac_mf_rad)

    fac_mf_T = viscid.as_mapfield(fac, order=('lat', 'lon'))
    assert_similar(fac_mf_T, fac_mf.T)

    return 0
Esempio n. 12
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    args = vutil.common_argparse(parser)  # pylint: disable=unused-variable

    fiof = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.iof.xdmf'))

    fac = fiof['fac_tot']

    fac_mf = viscid.as_mapfield(fac)
    fac_sphere = viscid.as_spherefield(fac)
    if fac_sphere is not fac:
        raise RuntimeError("cenversion should have been a noop")

    fac_mf_rad = viscid.as_mapfield(fac, units='rad')
    fac_sphere_rad = viscid.as_spherefield(fac, units='rad')

    fac_mf_sphere = viscid.as_spherefield(fac_mf)
    assert_similar(fac_mf_sphere, fac)

    fac_mf_sphere_deg_rad = viscid.as_spherefield(fac_mf, units='rad')
    assert_similar(fac_mf_sphere_deg_rad, fac_sphere_rad)

    fac_mf_sphere_rad_deg = viscid.as_spherefield(fac_mf_rad, units='deg')
    assert_similar(fac_mf_sphere_rad_deg, fac)

    fac_sphere_mf_rad_deg = viscid.as_mapfield(fac_sphere_rad, units='deg')
    assert_similar(fac_sphere_mf_rad_deg, fac_mf)

    fac_sphere_mf_rad_rad = viscid.as_mapfield(fac_sphere_rad, units='rad')
    assert_similar(fac_sphere_mf_rad_rad, fac_mf_rad)

    fac_mf_T = viscid.as_mapfield(fac, order=('lat', 'lon'))
    assert_similar(fac_mf_T, fac_mf.T)

    return 0
Esempio n. 13
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    iono_file = viscid.load_file(_viscid_root + '/../sample/jrrle_sample.iof.*')

    fac_tot = 1e9 * iono_file["fac_tot"]

    plot_args = dict(projection="polar",
                     lin=[-4e3, 3e3],
                     bounding_lat=35.0,
                     drawcoastlines=True,  # for basemap only, probably will never be used
                     title="Total FAC\n",  # make a title, or if a string, use the string as title
                     gridec='gray',
                     label_lat=True,
                     label_mlt=True,
                     colorbar=dict(pad=0.1)  # pad the colorbar away from the plot
                    )

    ax1 = plt.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 = plt.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)

    if args.show:
        mpl.mplshow()
Esempio n. 14
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)
    dtype = 'float32'

    x = np.array(np.linspace(-5, 5, 512), dtype=dtype)
    y = np.array(np.linspace(-5, 5, 256), dtype=dtype)
    z = np.array(np.linspace(-5, 5, 256), dtype=dtype)
    v = viscid.empty([x, y, z], name="V", nr_comps=3, center='node',
                     layout='interlaced')
    X, Y, Z = v.get_crds_nc(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)

    logger.info("Testing node centered magnitudes")
    run_mag_test(v, title="node centered", show=args.show)

    logger.info("Testing cell centered magnitudes")
    v = v.as_centered('cell')
    run_mag_test(v, title="cell centered", show=args.show)

    # print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024**2)
    # print("ne: ", timereps(10, Div1ne, [vx, vy, vz]))
    # print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024**2)
    # print("inline: ", timereps(10, Div1inline, [vx, vy, vz]))
    # print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024**2)

    return 0
Esempio n. 15
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    run_test(show=args.show)

    return 0
Esempio n. 16
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    run_test(show=args.show)

    return 0
Esempio n. 17
0
def main():
    parser = argparse.ArgumentParser(description="Test xdmf")
    parser.add_argument("--show", "--plot", action="store_true")
    parser.add_argument('file', nargs="?", default=None)
    args = vutil.common_argparse(parser)

    # f3d = readers.load_file(_viscid_root + '/../../sample/sample.3df.xdmf')
    # b3d = f3d['b']
    # bx, by, bz = b3d.component_fields()  # pylint: disable=W0612

    if args.file is None:
        args.file = "/Users/kmaynard/dev/work/cen4000/cen4000.3d.xdmf"
    f3d = readers.load_file(args.file)

    bx = f3d["bx"]
    by = f3d["by"]
    bz = f3d["bz"]
    B = field.scalar_fields_to_vector([bx, by, bz], name="B_cc",
                                      _force_layout=field.LAYOUT_INTERLACED)

    t0 = time()
    lines_single, topo = trace_cython(B, nr_procs=1)
    t1 = time()
    topo_single = vol.wrap_field(topo, name="CyTopo1")
    print("single proc:", t1 - t0, "s")

    nr_procs_list = np.array([1, 2, 3])
    # nr_procs_list = np.array([1, 2, 3, 4, 5, 6, 7, 8])
    times = np.empty_like(nr_procs_list, dtype="float")

    print("always parallel overhead now...")
    for i, nr_procs in enumerate(nr_procs_list):
        t0 = time()
        lines, topo = trace_cython(B, nr_procs=nr_procs, force_subprocess=True)
        t1 = time()
        fld = vol.wrap_field(topo, name="CyTopo")
        same_topo = (fld.data == topo_single.data).all()
        same_lines = True
        for j, line in enumerate(lines):
            same_lines = same_lines and (line == lines_single[j]).all()
        print("nr_procs:", nr_procs, "time:", t1 - t0, "s",
              "same topo:", same_topo, "same lines:", same_lines)
        times[i] = t1 - t0

    plt.plot(nr_procs_list, times, 'k^')
    plt.plot(nr_procs_list, times[0] / nr_procs_list, 'b--')
    plt.xscale("log")
    plt.yscale("log")
    plt.show()

    if False:
        cmap = plt.get_cmap('spectral')
        levels = [4, 5, 6, 7, 8, 13, 14, 16, 17]
        norm = BoundaryNorm(levels, cmap.N)
        mpl.plot(topo_flds[-1], "y=0", cmap=cmap, norm=norm, show=False)
        #mpl.plot_streamlines2d(lines[::5], "y", topology=topo[::5], show=False)
        #mpl.plot_streamlines(lines, topology=topo, show=False)
        mpl.mplshow()
Esempio n. 18
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()
Esempio n. 19
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)

    dtype = 'float64'

    # use 512 512 256 to inspect memory related things
    x = np.array(np.linspace(-0.5, 0.5, 256), dtype=dtype)
    y = np.array(np.linspace(-0.5, 0.5, 256), dtype=dtype)
    z = np.array(np.linspace(-0.5, 0.5, 64), dtype=dtype)

    v = viscid.empty([x, y, z], name="V", nr_comps=3, center="cell",
                     layout="interlaced")
    exact_cc = viscid.empty([x, y, z], name="exact_cc", center='cell')

    Xcc, Ycc, Zcc = exact_cc.get_crds_cc(shaped=True)  # pylint: disable=W0612

    if HAS_NUMEXPR:
        v['x'] = ne.evaluate("(sin(Xcc))")  # + Zcc
        v['y'] = ne.evaluate("(cos(Ycc))")  # + Xcc# + Zcc
        v['z'] = ne.evaluate("-((sin(Zcc)))")  # + Xcc# + Ycc
        exact_cc[:, :, :] = ne.evaluate("cos(Xcc) - sin(Ycc) - cos(Zcc)")
    else:
        v['x'] = (np.sin(Xcc))  # + Zcc
        v['y'] = (np.cos(Ycc))  # + Xcc# + Zcc
        v['z'] = -((np.sin(Zcc)))  # + Xcc# + Ycc
        exact_cc[:, :, :] = np.cos(Xcc) - np.sin(Ycc) - np.cos(Zcc)

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

    logger.info("node centered tests")
    v_nc = v.as_centered('node')
    exact_nc = viscid.empty_like(v_nc['x'])
    X, Y, Z = exact_nc.get_crds_nc(shaped=True)  # pylint: disable=W0612
    if HAS_NUMEXPR:
        exact_nc[:, :, :] = ne.evaluate("cos(X) - sin(Y) - cos(Z)")
    else:
        exact_nc[:, :, :] = np.cos(X) - np.sin(Y) - np.cos(Z)
    # FIXME: why is the error so much larger here?
    run_div_test(v_nc, exact_nc, title='Node Centered', show=args.show,
                 ignore_inexact=True)

    logger.info("cell centered tests")
    v_cc = v_nc.as_centered('cell')
    run_div_test(v_cc, exact_cc, title="Cell Centered", show=args.show)

    return 0
Esempio n. 20
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()
Esempio n. 21
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
Esempio n. 22
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    f3d = viscid.load_file(sample_dir + '/sample_xdmf.3d.xdmf',
                           grid_type=ggcm_test_common.MyGGCMGrid)
    ggcm_test_common.run_test_3d(f3d, __file__, show=args.show)

    f2d = viscid.load_file(sample_dir + '/sample_xdmf.py_0.xdmf',
                           grid_type=ggcm_test_common.MyGGCMGrid)
    ggcm_test_common.run_test_2d(f2d, __file__, show=args.show)
    ggcm_test_common.run_test_timeseries(f2d, __file__, show=args.show)

    fiof = viscid.load_file(sample_dir + '/sample_xdmf.iof.xdmf')
    ggcm_test_common.run_test_iof(fiof, __file__, show=args.show)
Esempio n. 23
0
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
Esempio n. 24
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    _ = vutil.common_argparse(parser)

    if _HAS_SCIPY:
        warnings.filterwarnings("ignore", category=OptimizeWarning)

    f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[0].xdmf'))
    mp = viscid.get_mp_info(f['pp'],
                            f['b'],
                            f['j'],
                            f['e_cc'],
                            fit='mp_xloc',
                            slc="x=7f:12.0f, y=-6f:6f, z=-6f:6f",
                            cache=False)

    Y, Z = mp['pp_max_xloc'].meshgrid(prune=True)

    # # get normals from paraboloid surface
    if isinstance(mp['paraboloid'], viscid.DeferredImportError):
        xfail("Scipy not installed; paraboloid curve fitting not tested")
    else:
        parab_n = viscid.paraboloid_normal(Y, Z, *mp['paraboloid'][0])
        parab_n = parab_n.reshape(3, -1)

    # get normals from minvar
    minvar_y = Y.reshape(-1)
    minvar_z = Z.reshape(-1)
    minvar_n = np.zeros([3, len(minvar_y)])

    for i in range(minvar_n.shape[1]):
        p0 = [0.0, minvar_y[i], minvar_z[i]]
        p0[0] = mp['pp_max_xloc']['y={0[0]}f, z={0[1]}f'.format(p0)]
        lmn = viscid.find_minvar_lmn_around(f['b'], p0, l=2.0, n=64)
        minvar_n[:, i] = lmn[2, :]

    theta = (180 / np.pi) * np.arccos(np.sum(parab_n * minvar_n, axis=0))

    # make sure paraboloid normals and minvar normals are closeish
    # this is a poor check, but at least it's something
    assert np.min(theta) < 3.0
    assert np.average(theta) < 20.0
    assert np.median(theta) < 20.0
    assert np.max(theta) < 70.0

    return 0
Esempio n. 25
0
def main():
    parser = argparse.ArgumentParser(description="Load some data files")
    parser.add_argument('files', nargs="*", help='input files')
    args = vutil.common_argparse(parser)

    # print("args", args)
    # logger.error(args)
    # logger.warn(args)
    logger.info("args: {0}".format(args))
    # logger.debug(args)
    print()

    files = readers.load_files(args.files)
    readers.__filebucket__.print_tree()
    print()

    for f in files:
        f.print_tree(depth=-1)
Esempio n. 26
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    f3d = viscid.load_file(os.path.join(sample_dir, 'sample_jrrle.3df.*'),
                           grid_type=ggcm_test_common.MyGGCMGrid)
    ggcm_test_common.run_test_3d(f3d, __file__, show=args.show)

    f2d = viscid.load_file(os.path.join(sample_dir, 'sample_jrrle.py_0.*'),
                           grid_type=ggcm_test_common.MyGGCMGrid)
    ggcm_test_common.run_test_2d(f2d, __file__, show=args.show)
    ggcm_test_common.run_test_timeseries(f2d, __file__, show=args.show)

    fiof = viscid.load_file(os.path.join(sample_dir, 'sample_jrrle.iof.*'))
    ggcm_test_common.run_test_iof(fiof, __file__, show=args.show)

    return 0
Esempio n. 27
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    f3d = viscid.load_file(os.path.join(sample_dir, 'sample_jrrle.3df.*'),
                           grid_type=ggcm_test_common.MyGGCMGrid)
    ggcm_test_common.run_test_3d(f3d, __file__, show=args.show)

    f2d = viscid.load_file(os.path.join(sample_dir, 'sample_jrrle.py_0.*'),
                           grid_type=ggcm_test_common.MyGGCMGrid)
    ggcm_test_common.run_test_2d(f2d, __file__, show=args.show)
    ggcm_test_common.run_test_timeseries(f2d, __file__, show=args.show)

    fiof = viscid.load_file(os.path.join(sample_dir, 'sample_jrrle.iof.*'))
    ggcm_test_common.run_test_iof(fiof, __file__, show=args.show)

    return 0
Esempio n. 28
0
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
Esempio n. 29
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    _ = vutil.common_argparse(parser)

    if _HAS_SCIPY:
        warnings.filterwarnings("ignore", category=OptimizeWarning)

    f = viscid.load_file(os.path.join(sample_dir, 'sample_xdmf.3d.[0].xdmf'))
    mp = viscid.get_mp_info(f['pp'], f['b'], f['j'], f['e_cc'], fit='mp_xloc',
                            slc="x=7j:12.0j, y=-6j:6j, z=-6j:6j",
                            cache=False)

    Y, Z = mp['pp_max_xloc'].meshgrid(prune=True)

    # # get normals from paraboloid surface
    if isinstance(mp['paraboloid'], viscid.DeferredImportError):
        xfail("Scipy not installed; paraboloid curve fitting not tested")
    else:
        parab_n = viscid.paraboloid_normal(Y, Z, *mp['paraboloid'][0])
        parab_n = parab_n.reshape(3, -1)

    # get normals from minvar
    minvar_y = Y.reshape(-1)
    minvar_z = Z.reshape(-1)
    minvar_n = np.zeros([3, len(minvar_y)])

    for i in range(minvar_n.shape[1]):
        p0 = [0.0, minvar_y[i], minvar_z[i]]
        p0[0] = mp['pp_max_xloc']['y={0[0]}f, z={0[1]}f'.format(p0)]
        lmn = viscid.find_minvar_lmn_around(f['b'], p0, l=2.0, n=64)
        minvar_n[:, i] = lmn[2, :]

    theta = (180 / np.pi) * np.arccos(np.sum(parab_n * minvar_n, axis=0))

    # make sure paraboloid normals and minvar normals are closeish
    # this is a poor check, but at least it's something
    assert np.min(theta) < 3.0
    assert np.average(theta) < 20.0
    assert np.median(theta) < 20.0
    assert np.max(theta) < 70.0

    return 0
Esempio n. 30
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, 'sample_xdmf.py_0.xdmf'))

    xl, xh = f.get_grid().xl_nc, f.get_grid().xh_nc
    seeds0 = viscid.Circle(p0=0.5 * (xl + xh), r=0.2 * np.max(xh - xl),
                           pole=(0, 0, 1), n=10)
    seeds1 = viscid.Circle(p0=0.5 * (xl + xh), r=0.4 * np.max(xh - xl),
                           pole=(0, 0, 1), n=10)
    seeds = viscid.Point(np.concatenate([seeds0.get_points(),
                                         seeds1.get_points()], axis=1))

    viscid.follow_fluid(f, seeds, dt=1.0, speed_scale=1 / 6.4e3,
                        callback_kwargs=dict(show=args.show,
                                             series_fname='plots/fluidtrace'))

    return 0
Esempio n. 31
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

    # 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)
Esempio n. 32
0
def main():
    parser = argparse.ArgumentParser(description="Test xdmf")
    parser.add_argument("--show", "--plot", action="store_true")
    parser.add_argument('file', nargs="?", default=None)
    args = vutil.common_argparse(parser)

    # f3d = readers.load_file(_viscid_root + '/../../sample/sample.3df.xdmf')
    # b3d = f3d['b']
    # bx, by, bz = b3d.component_fields()  # pylint: disable=W0612

    if args.file is None:
        # args.file = "/Users/kmaynard/dev/work/cen4000/cen4000.3d.xdmf"
        # args.file = "/Users/kmaynard/dev/work/tmp/cen2000.3d.004045.xdmf"
        args.file = "~/dev/work/api_05_180_0.00_5e2.3d.007200.xdmf"
    f3d = readers.load_file(args.file)

    bx = f3d["bx"]
    by = f3d["by"]
    bz = f3d["bz"]

    profile = False

    print("Fortran...")
    if profile:
        cProfile.runctx("lines, topo_fort = trace_fortran(bx, by, bz)",
                        globals(), locals(), "topo_fort.prof")
        s = pstats.Stats("topo_fort.prof")
        s.strip_dirs().sort_stats("cumtime").print_stats(10)
    else:
        lines, topo_fort = trace_fortran(bx, by, bz)

    print("Cython...")
    if profile:
        cProfile.runctx("lines, topo_cy = trace_cython(bx, by, bz)",
                        globals(), locals(), "topo_cy.prof")
        s = pstats.Stats("topo_cy.prof")
        s.strip_dirs().sort_stats("cumtime").print_stats(15)
    else:
        lines, topo_cy = trace_cython(bx, by, bz)
Esempio n. 33
0
def main():
    parser = argparse.ArgumentParser(description="Test calc")
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)
    dtype = 'float32'

    x = np.array(np.linspace(-5, 5, 512), dtype=dtype)
    y = np.array(np.linspace(-5, 5, 256), dtype=dtype)
    z = np.array(np.linspace(-5, 5, 256), dtype=dtype)
    v = viscid.empty([x, y, z], name="V", nr_comps=3, center='node',
                     layout='interlaced')
    X, Y, Z = v.get_crds_nc(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

    logger.info("Testing node centered magnitudes")
    run_mag_test(v, show=args.show)

    logger.info("Testing cell centered magnitudes")
    v = v.as_centered('cell')
    run_mag_test(v, show=args.show)
Esempio n. 34
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
Esempio n. 35
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)
Esempio n. 36
0
def main():
    parser = argparse.ArgumentParser(description="Test xdmf")
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

    f2d = viscid.load_file(_viscid_root + '/../sample/sample.py_0.xdmf')
    b2d = viscid.scalar_fields_to_vector([f2d['bx'], f2d['by'], f2d['bz']],
                                         name="b")
    bx2d, by2d, bz2d = b2d.component_fields() #pylint: disable=W0612

    f3d = viscid.load_file(_viscid_root + '/../sample/sample.3df.xdmf')
    b3d = f3d['b']
    bx, by, bz = b3d.component_fields() #pylint: disable=W0612

    nrows = 4
    ncols = 2

    plt.subplot2grid((nrows, ncols), (0, 0))
    mpl.plot(bx, "z=0,x=:30", earth=True, show=False)
    plt.subplot2grid((nrows, ncols), (1, 0))
    mpl.plot(bx, "z=0.5f,x=0:2,y=-100.0f:100.0f", earth=True, show=False)
    plt.subplot2grid((nrows, ncols), (2, 0))
    mpl.plot(bx, "z=-1,x=-10.0f:,y=-100.0f:100.0f", earth=True, show=False)
    plt.subplot2grid((nrows, ncols), (3, 0))
    mpl.plot(bx, "x=0.0f,y=-5.0f:5.0f,z=-5.0f:5.0f", earth=True, show=False)

    plt.subplot2grid((nrows, ncols), (0, 1))
    mpl.plot(bx2d, "y=20.0f,z=-100.0f:100.0f", earth=True, show=False)
    plt.subplot2grid((nrows, ncols), (1, 1))
    mpl.plot(bx2d, "x=0f:20:-1,y=0.0f,z=0.0f", show=False)
    plt.subplot2grid((nrows, ncols), (2, 1))
    mpl.plot(bx2d, earth=True, show=False)
    plt.subplot2grid((nrows, ncols), (3, 1))
    mpl.plot(bx2d, "z=0.0f,x=-20.0f:0.0f", show=False)

    if args.show:
        mpl.mplshow()
Esempio n. 37
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
Esempio n. 38
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()
Esempio n. 39
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    args = vutil.common_argparse(parser)  # pylint: disable=unused-variable

    # viscid.logger.setLevel(10)

    grids = [viscid.grid.Grid(time=t) for t in np.linspace(1.0, 10.0, 8)]
    dset = viscid.dataset.DatasetTemporal(*grids, basetime='1980-01-01')

    times = np.array([g.time for g in dset])

    ###################
    # slice by integer

    test_slice(dset, np.s_[2], times[2])
    # forward
    test_slice(dset, np.s_[4:], times[4:])
    test_slice(dset, np.s_[2::3], times[2::3])
    test_slice(dset, np.s_[:4], times[:4])
    test_slice(dset, np.s_[:5:2], times[:5:2])
    test_slice(dset, np.s_[2:5:2], times[2:5:2])
    test_slice(dset, np.s_[6:5:1], times[6:5:1])
    # backward
    test_slice(dset, np.s_[4::-1], times[4::-1])
    test_slice(dset, np.s_[:4:-1], times[:4:-1])
    test_slice(dset, np.s_[:4:-2], times[:4:-2])
    test_slice(dset, np.s_[2:5:-2], times[2:5:-2])
    test_slice(dset, np.s_[6:4:-1], times[6:4:-1])
    # forward
    test_slice(dset, '4:', times[4:])
    test_slice(dset, '2::3', times[2::3])
    test_slice(dset, ':4', times[:4])
    test_slice(dset, ':5:2', times[:5:2])
    test_slice(dset, '2:5:2', times[2:5:2])
    test_slice(dset, '6:5:1', times[6:5:1])
    # backward
    test_slice(dset, '4::-1', times[4::-1])
    test_slice(dset, ':4:-1', times[:4:-1])
    test_slice(dset, ':4:-2', times[:4:-2])
    test_slice(dset, '2:5:-2', times[2:5:-2])
    test_slice(dset, '6:4:-1', times[6:4:-1])

    #################
    # slice by float

    # Note: times = [  1.           2.28571429   3.57142857   4.85714286
    #                  6.14285714   7.42857143   8.71428571  10.        ]

    test_slice(dset, np.s_['4.0f'], times[2])
    test_slice(dset, np.s_['4.0f':], times[3:])
    test_slice(dset, np.s_['4.0f'::2], times[3::2])
    test_slice(dset, np.s_[:'4.0f':2], times[:3:2])
    test_slice(dset, np.s_['2.0f':'7.8f'], times[1:6])
    test_slice(dset, np.s_['2.0f':'7.8f':2], times[1:6:2])
    test_slice(dset, np.s_['7.8f':'2.0f':-1], times[5:0:-1])
    test_slice(dset,
               np.s_['7.8f':'2.0f':-1],
               times[5:1:-1],
               val_endpoint=False)
    test_slice(dset, np.s_['7.8f':'2.0f':-2], times[5:0:-2])
    test_slice(dset,
               np.s_['7.8f':'2.0f':-2],
               times[5:1:-2],
               val_endpoint=False)
    test_slice(dset, np.s_['3.4f':'7.3f'], times[2:5])
    test_slice(dset, np.s_['3.4f':'7.3f'], times[1:6], interior=True)
    test_slice(dset, np.s_['2.4f':'2.5f'], times[2:2])
    test_slice(dset, np.s_['2.1f':'2.5f'], times[1:2])
    test_slice(dset, np.s_['2.1f':'2.5f'], times[1:1], val_endpoint=False)
    test_slice(dset, np.s_['2.3f':'2.5f'], times[1:3], interior=True)

    ################
    # slice by imag
    test_slice(dset, np.s_[4.0j], times[2])
    test_slice(dset, np.s_[4.0j:], times[3:])
    test_slice(dset, np.s_[4.0j::2], times[3::2])
    test_slice(dset, np.s_[:4.0j:2], times[:3:2])
    test_slice(dset, np.s_[2.0j:7.8j], times[1:6])
    test_slice(dset, np.s_[2.0j:7.8j:2], times[1:6:2])
    test_slice(dset, np.s_[7.8j:2.0j:-1], times[5:0:-1])
    test_slice(dset, np.s_[7.8j:2.0j:-1], times[5:1:-1], val_endpoint=False)
    test_slice(dset, np.s_[7.8j:2.0j:-2], times[5:0:-2])
    test_slice(dset, np.s_[7.8j:2.0j:-2], times[5:1:-2], val_endpoint=False)
    test_slice(dset, np.s_[3.4j:7.3j], times[2:5])
    test_slice(dset, np.s_[3.4j:7.3j], times[1:6], interior=True)
    test_slice(dset, np.s_[2.4j:2.5j], times[2:2])
    test_slice(dset, np.s_[2.1j:2.5j], times[1:2])
    test_slice(dset, np.s_[2.1j:2.5j], times[1:1], val_endpoint=False)
    test_slice(dset, np.s_[2.3j:2.5j], times[1:3], interior=True)

    ####################
    # slice by imag str
    test_slice(dset, np.s_['4.0j'], times[2])
    test_slice(dset, np.s_['4.0j':], times[3:])
    test_slice(dset, np.s_['4.0j'::2], times[3::2])
    test_slice(dset, np.s_[:'4.0j':2], times[:3:2])
    test_slice(dset, np.s_['2.0j':'7.8j'], times[1:6])
    test_slice(dset, np.s_['2.0j':'7.8j':2], times[1:6:2])
    test_slice(dset, np.s_['7.8j':'2.0j':-1], times[5:0:-1])
    test_slice(dset,
               np.s_['7.8j':'2.0j':-1],
               times[5:1:-1],
               val_endpoint=False)
    test_slice(dset, np.s_['7.8j':'2.0j':-2], times[5:0:-2])
    test_slice(dset,
               np.s_['7.8j':'2.0j':-2],
               times[5:1:-2],
               val_endpoint=False)
    test_slice(dset, np.s_['3.4j':'7.3j'], times[2:5])
    test_slice(dset, np.s_['3.4j':'7.3j'], times[1:6], interior=True)
    test_slice(dset, np.s_['2.4j':'2.5j'], times[2:2])
    test_slice(dset, np.s_['2.1j':'2.5j'], times[1:2])
    test_slice(dset, np.s_['2.1j':'2.5j'], times[1:1], val_endpoint=False)
    test_slice(dset, np.s_['2.3j':'2.5j'], times[1:3], interior=True)

    ############################
    # slice by deprecated float
    viscid.logger.info("testing deprecated slice-by-location")
    test_slice(dset, np.s_['4.0'], times[2])
    test_slice(dset, np.s_['4.0':], times[3:])
    test_slice(dset, np.s_['4.0'::2], times[3::2])
    test_slice(dset, np.s_[:'4.0':2], times[:3:2])
    test_slice(dset, np.s_['2.0':'7.8'], times[1:6])
    test_slice(dset, np.s_['2.0':'7.8':2], times[1:6:2])
    test_slice(dset, np.s_['7.8':'2.0':-1], times[5:0:-1])
    test_slice(dset, np.s_['7.8':'2.0':-1], times[5:1:-1], val_endpoint=False)
    test_slice(dset, np.s_['7.8':'2.0':-2], times[5:0:-2])
    test_slice(dset, np.s_['7.8':'2.0':-2], times[5:1:-2], val_endpoint=False)
    test_slice(dset, np.s_['3.4':'7.3'], times[2:5])
    test_slice(dset, np.s_['3.4':'7.3'], times[1:6], interior=True)
    test_slice(dset, np.s_['2.4':'2.5'], times[2:2])
    test_slice(dset, np.s_['2.1':'2.5'], times[1:2])
    test_slice(dset, np.s_['2.1':'2.5'], times[1:1], val_endpoint=False)
    test_slice(dset, np.s_['2.3':'2.5'], times[1:3], interior=True)
    viscid.logger.info("done testing deprecated slice-by-location")

    ####################
    # slice by datetime
    test_slice(dset, np.s_['1980-01-01T00:00:03.0':'1980-01-01T00:00:07.8'],
               times[2:6])
    test_slice(dset, np.s_['UT1980-01-01T00:00:03.0:UT1980-01-01T00:00:07.8'],
               times[2:6])
    test_slice(dset, np.s_['T1980-01-01T00:00:03.0:T1980-01-01T00:00:07.8'],
               times[2:6])

    test_slice(dset, np.s_['1980-01-01T00:00:07.8':'1980-01-01T00:00:03.0':-2],
               times[5:1:-2])

    #####################
    # slice by timedelta
    test_slice(dset, np.s_['00:03.0':'00:07.8'], times[2:6])
    test_slice(dset, np.s_['T00:03.0:T00:07.8'], times[2:6])

    #############################
    # slice by a few mixed types
    test_slice(dset, np.s_['UT1980-01-01T00:00:03.0:T00:07.8'], times[2:6])
    test_slice(dset, np.s_['3f:T00:07.8'], times[2:6])
    test_slice(dset, np.s_['3:T00:07.8'], times[3:6])

    assert dset.tslc_range('2:5') == (3.5714285714285716, 7.4285714285714288)
    assert dset.tslc_range('2.3f:2.5f') == (2.3, 2.5)
    assert dset.tslc_range('UT1980-01-01T00:00:03.0:'
                           'UT1980-01-01T00:00:07.8') == (3.0, 7.8)

    t = viscid.linspace_datetime64('2010-01-01T12:00:00',
                                   '2010-01-01T15:00:00', 8)
    x = np.linspace(-1, 1, 12)
    fld = viscid.zeros([t, x], crd_names='tx', center='node')
    assert fld[:'2010-01-01T13:30:00'].shape == (4, 12)
    fld = viscid.zeros([t, x], crd_names='tx', center='cell')
    assert fld[:'2010-01-01T13:30:00'].shape == (4, 11)

    t = viscid.linspace_datetime64('2010-01-01T12:00:00',
                                   '2010-01-01T15:00:00', 8)
    t = t - t[0]
    x = np.linspace(-1, 1, 12)
    fld = viscid.zeros([t, x], crd_names='tx', center='node')
    assert fld[:'01:30:00'].shape == (4, 12)
    fld = viscid.zeros([t, x], crd_names='tx', center='cell')
    assert fld[:'01:30:00'].shape == (4, 11)

    return 0
Esempio n. 40
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)
    dtype = 'float32'

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

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

    assert_different(vI1, vI2)

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

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

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

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

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

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

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

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

    return 0
Esempio n. 41
0
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
Esempio n. 42
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    args = vutil.common_argparse(parser)  # pylint: disable=unused-variable

    # CELL CENTERED TESTS
    shape = [30, 40, 50]
    center = 'cell'
    fld = viscid.dat2field(np.arange(np.prod(shape)).reshape(shape),
                           center=center)
    fld_f = viscid.dat2field(np.arange(np.prod([3] + shape)).reshape([3] +
                                                                     shape),
                             fldtype='vector',
                             layout='flat',
                             center=center)
    fld_i = viscid.dat2field(np.arange(np.prod(shape + [3])).reshape(shape +
                                                                     [3]),
                             fldtype='vector',
                             layout='interlaced',
                             center=center)

    #### SLICE 1
    selection = np.s_[None, 1, ..., 2]
    test_slice(selection, fld, (1, 40), nc_shape=(2, 41), cc_shape=(1, 40))
    test_slice(selection,
               fld_f, (3, 1, 40),
               nc_shape=(2, 41),
               cc_shape=(1, 40))
    test_slice(selection,
               fld_i, (1, 40, 3),
               nc_shape=(2, 41),
               cc_shape=(1, 40))

    selection = "None, 1, ..., 2"
    test_slice(selection, fld, (1, 40), nc_shape=(2, 41), cc_shape=(1, 40))
    test_slice(selection,
               fld_f, (3, 1, 40),
               nc_shape=(2, 41),
               cc_shape=(1, 40))
    test_slice(selection,
               fld_i, (1, 40, 3),
               nc_shape=(2, 41),
               cc_shape=(1, 40))

    #### SLICE 2
    selection = np.s_[1, ..., None, 2]
    test_slice(selection, fld, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (3, 40, 1),
               nc_shape=(41, 2),
               cc_shape=(40, 1))
    test_slice(selection,
               fld_i, (40, 1, 3),
               nc_shape=(41, 2),
               cc_shape=(40, 1))

    selection = "1, ..., None, 2"
    test_slice(selection, fld, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (3, 40, 1),
               nc_shape=(41, 2),
               cc_shape=(40, 1))
    test_slice(selection,
               fld_i, (40, 1, 3),
               nc_shape=(41, 2),
               cc_shape=(40, 1))

    #### SLICE 3
    selection = np.s_[None, ..., None, 1]
    test_slice(selection,
               fld, (1, 30, 40, 1),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_f, (3, 1, 30, 40, 1),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_i, (1, 30, 40, 1, 3),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))

    selection = "None, ..., None, 1"
    test_slice(selection,
               fld, (1, 30, 40, 1),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_f, (3, 1, 30, 40, 1),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_i, (1, 30, 40, 1, 3),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))

    #### SLICE 4
    selection = np.s_[5j, ..., None, 2]
    test_slice(selection, fld, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (3, 40, 1),
               nc_shape=(41, 2),
               cc_shape=(40, 1))
    test_slice(selection,
               fld_i, (40, 1, 3),
               nc_shape=(41, 2),
               cc_shape=(40, 1))

    #### SLICE 4
    selection = "5j, ..., t=None, 2"
    test_slice(selection, fld, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (3, 40, 1),
               nc_shape=(41, 2),
               cc_shape=(40, 1))
    test_slice(selection,
               fld_i, (40, 1, 3),
               nc_shape=(41, 2),
               cc_shape=(40, 1))

    # with crd slice
    selection = np.s_[5j, ..., None, 2, 'x']
    test_slice(selection, fld_f, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection, fld_i, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))

    selection = "5j, ..., t=None, 2, x"
    test_slice(selection, fld_f, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection, fld_i, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))

    # NODE CENTERED TESTS
    shape = [31, 41, 51]
    center = 'node'
    fld = viscid.dat2field(np.arange(np.prod(shape)).reshape(shape),
                           center=center)
    fld_f = viscid.dat2field(np.arange(np.prod([3] + shape)).reshape([3] +
                                                                     shape),
                             fldtype='vector',
                             layout='flat',
                             center=center)
    fld_i = viscid.dat2field(np.arange(np.prod(shape + [3])).reshape(shape +
                                                                     [3]),
                             fldtype='vector',
                             layout='interlaced',
                             center=center)

    #### SLICE 1
    selection = np.s_[None, 1, ..., 2]
    test_slice(selection, fld, (1, 41), nc_shape=(1, 41), cc_shape=(0, 40))
    test_slice(selection,
               fld_f, (3, 1, 41),
               nc_shape=(1, 41),
               cc_shape=(0, 40))
    test_slice(selection,
               fld_i, (1, 41, 3),
               nc_shape=(1, 41),
               cc_shape=(0, 40))

    selection = "None, 1, ..., 2"
    test_slice(selection, fld, (1, 41), nc_shape=(1, 41), cc_shape=(0, 40))
    test_slice(selection,
               fld_f, (3, 1, 41),
               nc_shape=(1, 41),
               cc_shape=(0, 40))
    test_slice(selection,
               fld_i, (1, 41, 3),
               nc_shape=(1, 41),
               cc_shape=(0, 40))

    #### SLICE 2
    selection = np.s_[1, ..., None, 2]
    test_slice(selection, fld, (41, 1), nc_shape=(41, 1), cc_shape=(40, 0))
    test_slice(selection,
               fld_f, (3, 41, 1),
               nc_shape=(41, 1),
               cc_shape=(40, 0))
    test_slice(selection,
               fld_i, (41, 1, 3),
               nc_shape=(41, 1),
               cc_shape=(40, 0))

    selection = "1, ..., None, 2"
    test_slice(selection, fld, (41, 1), nc_shape=(41, 1), cc_shape=(40, 0))
    test_slice(selection,
               fld_f, (3, 41, 1),
               nc_shape=(41, 1),
               cc_shape=(40, 0))
    test_slice(selection,
               fld_i, (41, 1, 3),
               nc_shape=(41, 1),
               cc_shape=(40, 0))

    #### SLICE 3
    selection = np.s_[None, ..., None, 1]
    test_slice(selection,
               fld, (1, 31, 41, 1),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(0, 30, 40, 0))
    test_slice(selection,
               fld_f, (3, 1, 31, 41, 1),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(0, 30, 40, 0))
    test_slice(selection,
               fld_i, (1, 31, 41, 1, 3),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(0, 30, 40, 0))

    selection = "None, ..., None, 1"
    test_slice(selection,
               fld, (1, 31, 41, 1),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(0, 30, 40, 0))
    test_slice(selection,
               fld_f, (3, 1, 31, 41, 1),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(0, 30, 40, 0))
    test_slice(selection,
               fld_i, (1, 31, 41, 1, 3),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(0, 30, 40, 0))

    #### SLICE 4
    selection = np.s_[5j, ..., None, 2]
    test_slice(selection, fld, (41, 1), nc_shape=(41, 1), cc_shape=(40, 0))
    test_slice(selection,
               fld_f, (3, 41, 1),
               nc_shape=(41, 1),
               cc_shape=(40, 0))
    test_slice(selection,
               fld_i, (41, 1, 3),
               nc_shape=(41, 1),
               cc_shape=(40, 0))

    #### SLICE 4
    selection = "5j, ..., t=None, 2"
    test_slice(selection, fld, (41, 1), nc_shape=(41, 1), cc_shape=(40, 0))
    test_slice(selection,
               fld_f, (3, 41, 1),
               nc_shape=(41, 1),
               cc_shape=(40, 0))
    test_slice(selection,
               fld_i, (41, 1, 3),
               nc_shape=(41, 1),
               cc_shape=(40, 0))

    # with crd slice
    selection = np.s_[5j, ..., None, 2, 'x']
    test_slice(selection, fld_f, (41, 1), nc_shape=(41, 1), cc_shape=(40, 0))
    test_slice(selection, fld_i, (41, 1), nc_shape=(41, 1), cc_shape=(40, 0))

    selection = "5j, ..., t=None, 2, x"
    test_slice(selection, fld_f, (41, 1), nc_shape=(41, 1), cc_shape=(40, 0))
    test_slice(selection, fld_i, (41, 1), nc_shape=(41, 1), cc_shape=(40, 0))

    ################################################################
    #### test newaxes with slice_and_keep dims (None == newaxis)
    fld_A = fld.slice_and_keep(np.s_[None, :, '0j', ..., None])
    assert fld_A.crds.axes == ['new-x0', 'x', 'y', 'z', 'new-x1']
    assert fld_A.shape == (1, 31, 1, 51, 1)

    fld_A = fld.slice_and_keep(np.s_[None, ..., '0j', None])
    assert fld_A.crds.axes == ['new-x0', 'x', 'y', 'z', 'new-x1']
    assert fld_A.shape == (1, 31, 41, 1, 1)

    fld_A = fld.slice_and_keep(np.s_[None, :, '0j', None])
    assert fld_A.crds.axes == ['new-x0', 'x', 'y', 'new-x1', 'z']
    assert fld_A.shape == (1, 31, 1, 1, 51)

    fld_A = fld.slice_and_keep(np.s_[None, :, ..., None])
    assert fld_A.crds.axes == ['new-x0', 'x', 'y', 'z', 'new-x1']
    assert fld_A.shape == (1, 31, 41, 51, 1)

    fld_A = fld.slice_and_keep(np.s_[None, :, None, ...])
    assert fld_A.crds.axes == ['new-x0', 'x', 'new-x1', 'y', 'z']
    assert fld_A.shape == (1, 31, 1, 41, 51)

    fld_A = fld.slice_and_keep(np.s_[None, :, '0j', None, ...])
    assert fld_A.crds.axes == ['new-x0', 'x', 'y', 'new-x1', 'z']
    assert fld_A.shape == (1, 31, 1, 1, 51)

    # -
    # assorted other quick tests
    def _quick_test1(_fld, selection, axes, shape, verb=False):
        slcfld = _fld[selection]
        if verb:
            print("axes:", slcfld.crds.axes)
            print("shape:", slcfld.shape, '\n')
        assert slcfld.crds.axes == axes
        assert slcfld.shape == shape

    _quick_test1(fld, ':', ['x', 'y', 'z'], (31, 41, 51))
    _quick_test1(fld, ':, w=newaxis, z=0.0j:0.3j', ['x', 'w', 'y', 'z'],
                 (31, 1, 41, 1))
    _quick_test1(fld, ':, w=newaxis, 0.0j, v=newaxis, z=0.0j:0.3j',
                 ['x', 'w', 'v', 'z'], (31, 1, 1, 1))
    _quick_test1(fld, ':, w=newaxis, ..., 0.0j:0.3j', ['x', 'w', 'y', 'z'],
                 (31, 1, 41, 1))
    _quick_test1(fld, '..., :, w=newaxis, 0.0j:0.3j', ['x', 'y', 'w', 'z'],
                 (31, 41, 1, 1))
    _quick_test1(fld, 'u=newaxis, ..., w=newaxis', ['u', 'x', 'y', 'z', 'w'],
                 (1, 31, 41, 51, 1))
    _quick_test1(fld, 'newaxis, ..., w=newaxis',
                 ['new-x0', 'x', 'y', 'z', 'w'], (1, 31, 41, 51, 1))
    _quick_test1(fld, 'u=newaxis, ..., newaxis',
                 ['u', 'x', 'y', 'z', 'new-x0'], (1, 31, 41, 51, 1))

    # -
    #       implied x

    fld_A = fld.slice_and_keep('u=newaxis, :, 0j, ..., w=newaxis')
    assert fld_A.crds.axes == ['u', 'x', 'y', 'z', 'w']
    assert fld_A.shape == (1, 31, 1, 51, 1)

    fld_A = fld.slice_and_keep('u=newaxis, :, 0j, w=newaxis')
    assert fld_A.crds.axes == ['u', 'x', 'y', 'w', 'z']
    assert fld_A.shape == (1, 31, 1, 1, 51)

    fld_A = fld.slice_and_keep('u=newaxis, :, 0j, w=newaxis, ...')
    assert fld_A.crds.axes == ['u', 'x', 'y', 'w', 'z']
    assert fld_A.shape == (1, 31, 1, 1, 51)

    # test slice_interp
    shape = [31, 41, 51]
    fld = viscid.dat2field(np.arange(
        np.prod(shape)).astype('f4').reshape(shape),
                           center='node')
    fld_A = fld.interpolated_slice(np.s_[:, 10.5])
    fld_A = fld.interpolated_slice('y=10.5')
    fld_A = fld.interpolated_slice('..., 10.5j')

    shape = [30, 40, 50]
    fld = viscid.dat2field(np.arange(
        np.prod(shape)).astype('f4').reshape(shape),
                           center='cell')
    fld_A = fld.interpolated_slice(np.s_[:, 10.5])
    fld_A = fld.interpolated_slice('y=10.5')
    fld_A = fld.interpolated_slice('..., 10.5j')

    return 0
Esempio n. 43
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
Esempio n. 44
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
Esempio n. 45
0
def _main():
    parser = argparse.ArgumentParser(description=__doc__)
    args = vutil.common_argparse(parser)  # pylint: disable=unused-variable

    # CELL CENTERED TESTS
    shape = [30, 40, 50]
    center = 'cell'
    fld = viscid.dat2field(np.arange(np.prod(shape)).reshape(shape),
                           center=center)
    fld_f = viscid.dat2field(np.arange(np.prod([3] + shape)).reshape([3] +
                                                                     shape),
                             fldtype='vector',
                             layout='flat',
                             center=center)
    fld_i = viscid.dat2field(np.arange(np.prod(shape + [3])).reshape(shape +
                                                                     [3]),
                             fldtype='vector',
                             layout='interlaced',
                             center=center)

    #### SLICE 1
    selection = np.s_[None, 1, ..., 2]
    test_slice(selection, fld, (1, 40), nc_shape=(2, 41), cc_shape=(1, 40))
    test_slice(selection,
               fld_f, (1, 30, 40),
               nc_shape=(2, 31, 41),
               cc_shape=(1, 30, 40))
    test_slice(selection,
               fld_i, (1, 40, 50),
               nc_shape=(2, 41, 51),
               cc_shape=(1, 40, 50))

    selection = "None, 1, ..., 2"
    test_slice(selection, fld, (1, 40), nc_shape=(2, 41), cc_shape=(1, 40))
    test_slice(selection,
               fld_f, (1, 30, 40),
               nc_shape=(2, 31, 41),
               cc_shape=(1, 30, 40))
    test_slice(selection,
               fld_i, (1, 40, 50),
               nc_shape=(2, 41, 51),
               cc_shape=(1, 40, 50))

    #### SLICE 2
    selection = np.s_[1, ..., None, 2]
    test_slice(selection, fld, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (30, 40, 1),
               nc_shape=(31, 41, 2),
               cc_shape=(30, 40, 1))
    test_slice(selection,
               fld_i, (40, 50, 1),
               nc_shape=(41, 51, 2),
               cc_shape=(40, 50, 1))

    selection = "1, ..., None, 2"
    test_slice(selection, fld, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (30, 40, 1),
               nc_shape=(31, 41, 2),
               cc_shape=(30, 40, 1))
    test_slice(selection,
               fld_i, (40, 50, 1),
               nc_shape=(41, 51, 2),
               cc_shape=(40, 50, 1))

    #### SLICE 3
    selection = np.s_[None, ..., None, 1]
    test_slice(selection,
               fld, (1, 30, 40, 1),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_f, (3, 1, 30, 40, 1),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_i, (1, 30, 40, 50, 1),
               nc_shape=(2, 31, 41, 51, 2),
               cc_shape=(1, 30, 40, 50, 1))

    selection = "None, ..., None, 1"
    test_slice(selection,
               fld, (1, 30, 40, 1),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_f, (3, 1, 30, 40, 1),
               nc_shape=(2, 31, 41, 2),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_i, (1, 30, 40, 50, 1),
               nc_shape=(2, 31, 41, 51, 2),
               cc_shape=(1, 30, 40, 50, 1))

    #### SLICE 4
    selection = "x=0, ..., None, 2"
    test_slice(selection, fld, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (3, 40, 1),
               nc_shape=(41, 2),
               cc_shape=(40, 1))
    test_slice(selection,
               fld_i, (40, 50, 1),
               nc_shape=(41, 51, 2),
               cc_shape=(40, 50, 1))

    #### SLICE 4
    selection = "x=5f, ..., t=None, 2"
    test_slice(selection, fld, (40, 1), nc_shape=(41, 2), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (3, 40, 1),
               nc_shape=(41, 2),
               cc_shape=(40, 1))
    test_slice(selection,
               fld_i, (40, 50, 1),
               nc_shape=(41, 51, 2),
               cc_shape=(40, 50, 1))

    # NODE CENTERED TESTS
    shape = [31, 41, 51]
    center = 'node'
    fld = viscid.dat2field(np.arange(np.prod(shape)).reshape(shape),
                           center=center)
    fld_f = viscid.dat2field(np.arange(np.prod([3] + shape)).reshape([3] +
                                                                     shape),
                             fldtype='vector',
                             layout='flat',
                             center=center)
    fld_i = viscid.dat2field(np.arange(np.prod(shape + [3])).reshape(shape +
                                                                     [3]),
                             fldtype='vector',
                             layout='interlaced',
                             center=center)

    #### SLICE 1
    selection = np.s_[None, 1, ..., 2]
    test_slice(selection, fld, (1, 41), nc_shape=(1, 41), cc_shape=(1, 40))
    test_slice(selection,
               fld_f, (1, 31, 41),
               nc_shape=(1, 31, 41),
               cc_shape=(1, 30, 40))
    test_slice(selection,
               fld_i, (1, 41, 51),
               nc_shape=(1, 41, 51),
               cc_shape=(1, 40, 50))

    selection = "None, 1, ..., 2"
    test_slice(selection, fld, (1, 41), nc_shape=(1, 41), cc_shape=(1, 40))
    test_slice(selection,
               fld_f, (1, 31, 41),
               nc_shape=(1, 31, 41),
               cc_shape=(1, 30, 40))
    test_slice(selection,
               fld_i, (1, 41, 51),
               nc_shape=(1, 41, 51),
               cc_shape=(1, 40, 50))

    #### SLICE 2
    selection = np.s_[1, ..., None, 2]
    test_slice(selection, fld, (41, 1), nc_shape=(41, 1), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (31, 41, 1),
               nc_shape=(31, 41, 1),
               cc_shape=(30, 40, 1))
    test_slice(selection,
               fld_i, (41, 51, 1),
               nc_shape=(41, 51, 1),
               cc_shape=(40, 50, 1))

    selection = "1, ..., None, 2"
    test_slice(selection, fld, (41, 1), nc_shape=(41, 1), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (31, 41, 1),
               nc_shape=(31, 41, 1),
               cc_shape=(30, 40, 1))
    test_slice(selection,
               fld_i, (41, 51, 1),
               nc_shape=(41, 51, 1),
               cc_shape=(40, 50, 1))

    #### SLICE 3
    selection = np.s_[None, ..., None, 1]
    test_slice(selection,
               fld, (1, 31, 41, 1),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_f, (3, 1, 31, 41, 1),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_i, (1, 31, 41, 51, 1),
               nc_shape=(1, 31, 41, 51, 1),
               cc_shape=(1, 30, 40, 50, 1))

    selection = "None, ..., None, 1"
    test_slice(selection,
               fld, (1, 31, 41, 1),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_f, (3, 1, 31, 41, 1),
               nc_shape=(1, 31, 41, 1),
               cc_shape=(1, 30, 40, 1))
    test_slice(selection,
               fld_i, (1, 31, 41, 51, 1),
               nc_shape=(1, 31, 41, 51, 1),
               cc_shape=(1, 30, 40, 50, 1))

    #### SLICE 4
    selection = "x=0, ..., None, 2"
    test_slice(selection, fld, (41, 1), nc_shape=(41, 1), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (3, 41, 1),
               nc_shape=(41, 1),
               cc_shape=(40, 1))
    test_slice(selection,
               fld_i, (41, 51, 1),
               nc_shape=(41, 51, 1),
               cc_shape=(40, 50, 1))

    #### SLICE 4
    selection = "x=5f, ..., t=None, 2"
    test_slice(selection, fld, (41, 1), nc_shape=(41, 1), cc_shape=(40, 1))
    test_slice(selection,
               fld_f, (3, 41, 1),
               nc_shape=(41, 1),
               cc_shape=(40, 1))
    test_slice(selection,
               fld_i, (41, 51, 1),
               nc_shape=(41, 51, 1),
               cc_shape=(40, 50, 1))

    return 0