예제 #1
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)
예제 #2
0
def guess_dipole_moment(b, r=2.0, strength=DEFAULT_STRENGTH, cap_angle=40,
                        cap_ntheta=121, cap_nphi=121, plot=False):
    """guess dipole moment from a B field"""
    viscid.warn("guess_dipole_moment doesn't seem to do better than 1.6 "
                "degrees, you may want to use cotr instead.")
    cap = seed.SphericalCap(r=r, angle=cap_angle, ntheta=cap_ntheta,
                            nphi=cap_nphi)
    b_cap = interp_trilin(b, cap)

    # FIXME: this doesn't get closer than 1.6 deg @ (theta, mu) = (0, 7.5)
    #        so maybe the index is incorrect somehow?
    idx = np.argmax(viscid.magnitude(b_cap).data)
    pole = cap.points()[:, idx]
    # FIXME: it should be achievabe to get strength from the magimum magnitude,
    #        up to the direction
    pole = strength * pole / np.linalg.norm(pole)
    # # not sure where 0.133 comes from, this is probably not correct
    # pole *= 0.133 * np.dot(pole, b_cap.data.reshape(-1, 3)[idx, :]) * r**3

    if plot:
        from viscid.plot import mpl
        mpl.plot(viscid.magnitude(b_cap))
        mpl.plot(viscid.magnitude(b_cap), style='contour', levels=10,
                 colors='k', colorbar=False, ax=mpl.plt.gca())
        mpl.show()
    return pole
예제 #3
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()
예제 #4
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()
예제 #5
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()
예제 #6
0
파일: test_div.py 프로젝트: jobejen/Viscid
def run_div_test(fld, exact, show=False, ignore_inexact=False):
    t0 = time()
    result_numexpr = viscid.div(fld, preferred="numexpr", only=True)
    t1 = time()
    logger.info("numexpr magnitude runtime: %g", t1 - t0)

    result_diff = viscid.diff(result_numexpr, exact[1:-1, 1:-1, 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)

    if show:
        mpl.mplshow()
예제 #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
예제 #8
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()
예제 #9
0
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()
예제 #10
0
def run_test(fld, seeds, kind, show=False):
    mpl.plt.clf()
    mpl.plot(viscid.interp(fld, seeds, kind=kind))
    mpl.plt.title(kind)

    mpl.plt.savefig(next_plot_fname(__file__))
    if show:
        mpl.show()
예제 #11
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()
예제 #12
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
예제 #13
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()
예제 #14
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()
예제 #15
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()
예제 #16
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()
예제 #17
0
파일: test_ggcm.py 프로젝트: jobejen/Viscid
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()
예제 #18
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()
예제 #19
0
파일: test_calc.py 프로젝트: jobejen/Viscid
def run_mag_test(fld, show=False):
    vx, vy, vz = fld.component_views() #pylint: disable=W0612
    vx, vy, vz = fld.component_fields()

    t0 = time()
    mag_ne = viscid.magnitude(fld, preferred="numexpr", only=True)
    t1 = time()
    logger.info("numexpr mag runtime: %g", t1 - t0)
    t0 = time()

    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)

    if show:
        mpl.mplshow()
예제 #20
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()
예제 #21
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
예제 #22
0
def compare_vectors(orig_fld, cmp_fld, catol=1e-8, rtol=2e-6,
                          trim_slc='x=2:-2, y=2:-2, z=2:-2', make_plots=False):
    # mag_shape = list(orig_fld.sshape) + [1]
    mag = viscid.magnitude(orig_fld)  # .data.reshape(mag_shape)
    reldiff = (cmp_fld - orig_fld) / mag
    reldiff = reldiff[trim_slc]
    reldiff.name = cmp_fld.name + " - " + orig_fld.name
    reldiff.pretty_name = cmp_fld.pretty_name + " - " + orig_fld.pretty_name
    comp_beyond_limit = [False] * 3

    for i, d in enumerate('xyz'):
        abs_max_rel_diff = np.nanmax(np.abs(reldiff[d]))
        max_crd_diff = np.max(orig_fld.get_crd(d) - cmp_fld.get_crd(d))
        print("{0}{1}, max absolute relative diff: {2:.3e} ({1} crds: {3:.1e})"
              "".format(cmp_fld.name, d, abs_max_rel_diff, max_crd_diff))
        if abs_max_rel_diff > rtol or abs(max_crd_diff) > catol:
            comp_beyond_limit[i] = True

        # plot differences?
        if make_plots:
            mpl.plt.clf()
            ax1 = mpl.plt.subplot(311)
            mpl.plot(orig_fld[d]['y=0f'], symmetric=True, earth=True)
            mpl.plt.subplot(312, sharex=ax1, sharey=ax1)
            mpl.plot(cmp_fld[d]['y=0f'], symmetric=True, earth=True)
            mpl.plt.subplot(313, sharex=ax1, sharey=ax1)
            mpl.plot(reldiff[d]['y=0f'], symmetric=True, earth=True)
            mpl.show()
예제 #23
0
def compare_vectors(cc_fld, ecfc_fld, to_cc_fn, catol=1e-8, rtol=2.2e-6,
                    trim_slc='x=1:-1, y=1:-1, z=1:-1', make_plots=False):
    trimmed = cc_fld[trim_slc]
    cc = to_cc_fn(ecfc_fld)
    reldiff = (cc - trimmed) / viscid.magnitude(trimmed)
    reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"]
    reldiff.name = cc.name + " - " + trimmed.name
    reldiff.pretty_name = cc.pretty_name + " - " + trimmed.pretty_name
    comp_beyond_limit = [False] * 3

    for i, d in enumerate('xyz'):
        abs_max_rel_diff = np.nanmax(np.abs(reldiff[d]))
        max_crd_diff = np.max(trimmed.get_crd(d) - cc.get_crd(d))
        print("{0}{1}, max absolute relative diff: {2:.3e} ({1} crds: {3:.1e})"
              "".format(cc_fld.name, d, abs_max_rel_diff, max_crd_diff))
        if abs_max_rel_diff > rtol or abs(max_crd_diff) > catol:
            comp_beyond_limit[i] = True

        # plot differences?
        if make_plots:
            ax1 = mpl.plt.subplot(311)
            mpl.plot(cc_fld[d]['y=0f'], symmetric=True, earth=True)
            mpl.plt.subplot(312, sharex=ax1, sharey=ax1)
            mpl.plot(cc[d]['y=0f'], symmetric=True, earth=True)
            mpl.plt.subplot(313, sharex=ax1, sharey=ax1)
            mpl.plot(reldiff[d]['y=0f'], symmetric=True, earth=True)
            mpl.show()

    if any(comp_beyond_limit):
        raise RuntimeError("Tolerance exceeded on ->CC accuracy")
예제 #24
0
def main():
    f = viscid.load_file("~/dev/work/tmedium/*.3d.[-1].xdmf")
    grid = f.get_grid()

    gslc = "x=-26f:12.5f, y=-15f:15f, z=-15f:15f"
    # gslc = "x=-12.5f:26f, y=-15f:15f, z=-15f:15f"

    b_cc = f['b_cc'][gslc]
    b_cc.name = "b_cc"
    b_fc = f['b_fc'][gslc]
    b_fc.name = "b_fc"

    e_cc = f['e_cc'][gslc]
    e_cc.name = "e_cc"
    e_ec = f['e_ec'][gslc]
    e_ec.name = "e_ec"

    pp = f['pp'][gslc]
    pp.name = 'pp'

    pargs = dict(logscale=True, earth=True)

    # mpl.clf()
    # ax1 = mpl.subplot(211)
    # mpl.plot(f['pp']['y=0f'], **pargs)
    # # mpl.plot(viscid.magnitude(f['b_cc']['y=0f']), **pargs)
    # # mpl.show()
    # mpl.subplot(212, sharex=ax1, sharey=ax1)
    # mpl.plot(viscid.magnitude(viscid.fc2cc(f['b_fc'])['y=0f']), **pargs)
    # mpl.show()

    basename = './tmediumR.3d.{0:06d}'.format(int(grid.time))
    viscid.save_fields(basename + '.h5', [b_cc, b_fc, e_cc, e_ec, pp])

    f2 = viscid.load_file(basename + ".xdmf")

    pargs = dict(logscale=True, earth=True)

    mpl.clf()
    ax1 = mpl.subplot(211)
    mpl.plot(f2['pp']['y=0f'], style='contour', levels=5, colorbar=None,
             colors='k', **pargs)
    mpl.plot(viscid.magnitude(f2['b_cc']['y=0f']), **pargs)
    mpl.subplot(212, sharex=ax1, sharey=ax1)
    mpl.plot(viscid.magnitude(viscid.fc2cc(f2['b_fc'])['y=0f']), **pargs)
    mpl.show()

    os.remove(basename + '.h5')
    os.remove(basename + '.xdmf')

    return 0
예제 #25
0
def run_test_3d(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.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("3D 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()
예제 #26
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()
예제 #27
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)
예제 #28
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)
예제 #29
0
파일: plot.py 프로젝트: psc-code/psc
#!/usr/bin/env python

import matplotlib
matplotlib.use("Agg")
import viscid
from viscid.plot import mpl

steps = range(0, 4)

flds = ['rr', 'vx', 'pp']

plot_kwargs = dict()

f = viscid.load_file("run.3d.xdmf")

for step in steps:
    print("Plotting step {}".format(step))
    f.activate_time(step)
    for fld in flds:
        mpl.plt.figure()

        dat = f[fld]

        mpl.plot(dat, marker='o', **plot_kwargs)

        mpl.plt.savefig("%s-xy-%06d.png" % (fld, step), dpi=200)
        mpl.plt.close()
예제 #30
0
파일: plot.py 프로젝트: psc-code/psc
matplotlib.use("Agg")
import viscid
from viscid.plot import mpl

steps = range(0, 100)

flds = ['divB', 'rr', 'bx', 'by', 'bz', 'vx', 'vy', 'vz', 'pp']
flds = ['vx']

f = viscid.load_file("run.3d.xdmf")

for step in steps:
    print("Plotting step {}".format(step))
    f.activate_time(step)
    for fld in flds:
        mpl.plt.figure()

        plot_kwargs = dict()
        dat = f[fld]
        # if fld == "divB":
        #     dat *= f["ymask"]

        if fld == "vx":
            plot_kwargs["cmap"] = "hot"
            plot_kwargs["clim"] = (-150, 150)

        mpl.plot(dat, "y=0.f", **plot_kwargs)

        mpl.plt.savefig("%s-xz-%06d.png" % (fld, step), dpi=200)
        mpl.plt.close()
예제 #31
0
def benchmark_streamline(precompile=True, profile=True, scale=True, plot=True):
    which = "streamline"
    print(which)
    print('-' * len(which))

    f0, seeds = make_vector_fld()

    print("Timing", which)

    sl_kwargs = dict(ibound=3.7, ds0=0.020)
    lines, _ = viscid.streamlines(f0, seeds, **sl_kwargs)
    nsegs_cython = np.sum([line.shape[1] for line in lines])
    lines = None

    ft_stats, cy_stats = dict(), dict()
    bench_output_type = viscid.OUTPUT_TOPOLOGY
    sl_kwargs.update(output=bench_output_type)

    retFT = viscid.timeit(fort_topology,
                          f0,
                          seeds,
                          timeit_repeat=6,
                          timeit_stats=ft_stats)
    _, retCY = viscid.timeit(viscid.streamlines,
                             f0,
                             seeds,
                             timeit_repeat=6,
                             timeit_stats=cy_stats,
                             **sl_kwargs)

    fort_per_seg = ft_stats['min'] / retFT.get_info('nsegs')
    cy_per_seg = cy_stats['min'] / nsegs_cython

    print("Segs Fortran", retFT.get_info('nsegs'))
    print("Segs Cython ", nsegs_cython)

    print("Fortran took {0:.3g} sec/seg".format(fort_per_seg))
    print("Cython took {0:.3g} sec/seg".format(cy_per_seg))
    print_seedup("Cython", cy_per_seg, "Fortran", fort_per_seg, prefix="@ ")

    if plot:
        from viscid.plot import mpl
        mpl.clf()
        mpl.subplot(121, projection='polar')
        mpl.plot(retCY, hemisphere='north')
        mpl.subplot(122, projection='polar')
        mpl.plot(retCY, hemisphere='south')
        mpl.show()

    if scale:
        thetas = np.logspace(np.log10(3), np.log10(144), 8).astype('i')

        cy_nsegs = [None] * len(thetas)
        fort_nsegs = [None] * len(thetas)
        cy_mintime = [None] * len(thetas)
        fort_mintime = [None] * len(thetas)

        for i, ntheta in enumerate(thetas):
            seeds = viscid.Sphere(r=10.0, ntheta=ntheta, nphi=32)
            _stats = dict()

            topo = viscid.timeit(fort_topology,
                                 f0,
                                 seeds,
                                 timeit_repeat=5,
                                 timeit_stats=_stats,
                                 timeit_quiet=True)
            fort_nsegs[i] = topo.get_info('nsegs')
            fort_mintime[i] = _stats['min']

            _, topo = viscid.timeit(viscid.calc_streamlines,
                                    f0,
                                    seeds,
                                    ibound=3.7,
                                    ds0=0.020,
                                    output=bench_output_type,
                                    timeit_repeat=5,
                                    timeit_stats=_stats,
                                    timeit_quiet=True)
            lines, _ = viscid.streamlines(f0, seeds, ibound=3.7, ds0=0.020)
            cy_nsegs[i] = np.sum([line.shape[1] for line in lines])
            cy_mintime[i] = _stats['min']

        from viscid.plot import mpl
        mpl.clf()
        mpl.plt.plot(cy_nsegs, cy_mintime, label="Cython")
        mpl.plt.plot(fort_nsegs, fort_mintime, label="Fortran")
        mpl.plt.legend(loc=0)
        mpl.plt.xlabel('Number of segments calculated')
        mpl.plt.ylabel('time to calculate')
        mpl.show()

        mpl.clf()
        cy_tperseg = np.array(cy_mintime) / np.array(cy_nsegs)
        fort_tperseg = np.array(fort_mintime) / np.array(fort_nsegs)
        mpl.plt.plot(thetas, cy_tperseg / fort_tperseg, label="over cython")
        mpl.plt.xlabel('ntheta')
        mpl.plt.ylabel('Fortran Speedup')
        mpl.show()
예제 #32
0
파일: plot.py 프로젝트: ALaDyn/psc
#!/usr/bin/env python

import matplotlib
matplotlib.use("Agg")
import viscid
from viscid.plot import mpl

steps = range(0, 4)

flds = ['rr', 'vx', 'vy', 'by', 'pp']

plot_kwargs = dict()

f = viscid.load_file("run.3d.xdmf")

for step in steps:
    print("Plotting step {}".format(step))
    f.activate_time(step)
    for fld in flds:
        mpl.plt.figure()

        dat = f[fld]
                                   
        mpl.plot(dat, marker='o', **plot_kwargs)

        mpl.plt.savefig("%s-xy-%06d.png" % (fld, step), dpi=200)
        mpl.plt.close()
예제 #33
0
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-s', "--slices", default="y=0.0,x=0.0",
                        help="comma separated list of slices, one figure per "
                             "slice; default is 'y=0.0,x=0.0'")
    parser.add_argument("--sample", default="",
                        help="optional datafile to plot sample data with grid "
                             "(requires Viscid to be in your PYTHONPATH)")
    parser.add_argument('-p', "--sample_var", default="rr",
                        help="optional sample quantity to plot")
    parser.add_argument('-o', "--plot_opts", default="",
                        help="options for sample plot")
    parser.add_argument("grid2", nargs=1, help="RUN.grid2 file")
    parser.add_argument("hgrid2", nargs=1, help="RUN.hgrid2 file")
    args = parser.parse_args()

    x, y, z = read_grid(args.grid2[0])
    dx, dy, dz = read_grid(args.hgrid2[0])

    dxmin = np.min(dx)
    dymin = np.min(dy)
    dzmin = np.min(dz)

    # setup fld if we're plotting a sample
    fld = None
    if args.sample:
        try:
            import viscid
            from viscid.plot import mpl
            viscid.readers.openggcm.GGCMGrid.mhd_to_gse_on_read = False
            fld = viscid.load_file(args.sample)[args.sample_var]
        except ImportError:
            print("Must have Viscid in your PYTHONPATH to plot a sample")
        except KeyError:
            print("Warning; unknown variable for sample")
        except TypeError:
            # given if the file doesnt exist, it will print its own warning
            pass
        except RuntimeError:
            # given if the calculator fails, it will print its own warning
            pass

    wrats = [1, 5]
    hrats = [1, 3]
    guides = [1.0, 2.0, 10.0]
    guide_colors = "rgy"
    circles = [1.0, 3.0, 6.0, 10.0, 20.0]
    circle_colors = 'krgby'

    for slc in args.slices.split(','):
        plane_dir, plane_loc = slc.lower().split('=')
        xstr, ystr = "xyz".replace(plane_dir, '')
        plane_str = "{0} Plane ({1} = {2})".format("-".join([xstr, ystr]).upper(),
                                                   plane_dir, plane_loc)

        _ = plt.figure()
        gspec = GridSpec(2, 2, width_ratios=wrats, height_ratios=hrats)
        ax_mesh = plt.subplot(gspec[3])
        ax_xcrds = plt.subplot(gspec[1], sharex=ax_mesh)
        ax_ycrds = plt.subplot(gspec[2], sharey=ax_mesh)

        # plot grid cells
        if fld is not None:
            mpl.plot(fld, slc, ax=ax_mesh, style="contourf", levels=100,
                     plot_opts=args.plot_opts,
                     colorbar=dict(ax=[ax_mesh, ax_xcrds], fraction=0.1))

        xarr = [x, y, z]["xyz".index(xstr)]
        yarr = [x, y, z]["xyz".index(ystr)]
        dxarr = [dx, dy, dz]["xyz".index(xstr)]
        dyarr = [dx, dy, dz]["xyz".index(ystr)]
        _dxmin = np.min(dxarr)
        _dymin = np.min(dyarr)
        _dxmax = np.max(dxarr)
        _dymax = np.max(dyarr)

        plot_2d_gridcells(xarr, yarr, circles=circles, colors=circle_colors,
                          ax=ax_mesh)
        ax_mesh.set_xlabel(xstr)

        # plot x vs dx for horizontal axis
        ax_xcrds.plot(xarr, dxarr)
        for i, guide in enumerate(guides):
            if guide * _dxmin > _dxmax:
                continue
            ax_xcrds.axhline(guide * _dxmin,
                             color=guide_colors[i % len(guide_colors)],
                             linestyle='--')
        ax_xcrds.set_ylabel('d' + xstr)

        # plot x vs dx for vertical axis
        ax_ycrds.plot(dyarr, yarr)
        for i, guide in enumerate(guides):
            if guide * _dymin > _dymax:
                continue
            ax_ycrds.axvline(guide * _dymin,
                             color=guide_colors[i % len(guide_colors)],
                             linestyle='--')
        ax_ycrds.set_ylabel(ystr)
        ax_ycrds.set_xlabel("d" + ystr)

        plt.suptitle(plane_str)
        info = """min dx: {0:.3g}
min dy: {1:.3g}
min dz: {2:.3g}""".format(dxmin, dymin, dzmin)
        ax = plt.subplot(gspec[0])
        ax.axis('off')
        ax.annotate(info, xy=(0, 0), xytext=(-0.3, 0.3),
                    textcoords='axes fraction')

    plt.show()

    return 0
예제 #34
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)
    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)

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

    return 0
예제 #35
0
파일: plot.py 프로젝트: psc-code/psc
#!/usr/bin/env python

import matplotlib

matplotlib.use("Agg")
import viscid
from viscid.plot import mpl

steps = range(0, 101, 1)

flds = ['rr_i', 'rvx_i', 'bx', 'by', 'bz']  #, 'ex', 'ey', 'ez']

plot_kwargs = dict(cmap='hot')

f = viscid.load_file("run.3d.xdmf")

for step in steps:
    print("Plotting step {}".format(step))
    f.activate_time(step)
    for fld in flds:
        mpl.plt.figure()

        dat = f[fld]
        if fld == "divB":
            dat *= f["ymask"]

        mpl.plot(dat, **plot_kwargs)

        mpl.plt.savefig("%s-xy-%06d.png" % (fld, step), dpi=200)
        mpl.plt.close()
예제 #36
0
#!/usr/bin/env python

import matplotlib

matplotlib.use("Agg")
import viscid
from viscid.plot import mpl

steps = range(0, 30)

flds = ['divB', 'rr', 'bx', 'by', 'bz', 'vx', 'vy', 'vz', 'pp']
flds = ['rr']

plot_kwargs = dict()

f = viscid.load_file("run.3d.xdmf")

for step in steps:
    print("Plotting step {}".format(step))
    f.activate_time(step)
    for fld in flds:
        mpl.plt.figure()

        mpl.plot(f[fld], **plot_kwargs)

        mpl.plt.savefig("%s-xy-%06d.png" % (fld, step), dpi=200)
        mpl.plt.close()