예제 #1
0
파일: test_div.py 프로젝트: jobejen/Viscid
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)
예제 #2
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
예제 #3
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))
    vlt.plot(fld_s, "z=0,x=:30", earth=True, plot_opts="lin_0")
    plt.subplot2grid((nrows, ncols), (1, 0))
    vlt.plot(fld_s, "z=0.75f,x=-4:-1,y=-3f:3f", earth=True)
    plt.subplot2grid((nrows, ncols), (2, 0))
    vlt.plot(fld_s, "x=-0.5f:,y=-3f:3f,z=0f", earth=True)
    plt.subplot2grid((nrows, ncols), (3, 0))
    vlt.plot(fld_s, "x=0.0f,y=-5.0f:5.0f", earth=True, plot_opts="log,g")

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

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
예제 #4
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
예제 #5
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
예제 #6
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()
예제 #7
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()
예제 #8
0
def get_trilinear_field():
    """get a generic trilinear field"""
    xl, xh, nx = -1.0, 1.0, 41
    yl, yh, ny = -1.5, 1.5, 41
    zl, zh, nz = -2.0, 2.0, 41
    x = np.linspace(xl, xh, nx)
    y = np.linspace(yl, yh, ny)
    z = np.linspace(zl, zh, nz)
    crds = viscid.wrap_crds("nonuniform_cartesian",
                            [('x', x), ('y', y), ('z', z)])
    b = viscid.empty(crds, name="f", nr_comps=3, center="Cell",
                     layout="interlaced")
    X, Y, Z = b.get_crds(shaped=True)

    x01, y01, z01 = 0.5, 0.5, 0.5
    x02, y02, z02 = 0.5, 0.5, 0.5
    x03, y03, z03 = 0.5, 0.5, 0.5

    b['x'][:] = (0.0 + 1.0 * (X - x01) + 1.0 * (Y - y01) + 1.0 * (Z - z01) +
                 1.0 * (X - x01) * (Y - y01) + 1.0 * (Y - y01) * (Z - z01) +
                 1.0 * (X - x01) * (Y - y01) * (Z - z01))
    b['y'][:] = (0.0 + 1.0 * (X - x02) - 1.0 * (Y - y02) + 1.0 * (Z - z02) +
                 1.0 * (X - x02) * (Y - y02) + 1.0 * (Y - y02) * (Z - z02) -
                 1.0 * (X - x02) * (Y - y02) * (Z - z02))
    b['z'][:] = (0.0 + 1.0 * (X - x03) + 1.0 * (Y - y03) - 1.0 * (Z - z03) +
                 1.0 * (X - x03) * (Y - y03) + 1.0 * (Y - y03) * (Z - z03) +
                 1.0 * (X - x03) * (Y - y03) * (Z - z03))
    return b
예제 #9
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)

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

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

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

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
예제 #10
0
def make_vector_fld():
    x, y, z = make_grid()
    f0 = viscid.empty((x, y, z), dtype=DTYPE, nr_comps=3, center='node')
    viscid.fill_dipole(f0)
    # seeds = viscid.Sphere(r=10.0, nphi=64, ntheta=32)
    seeds = viscid.Sphere(r=10.0, nphi=32, ntheta=48)
    return f0, seeds
예제 #11
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)

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

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

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

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
예제 #12
0
def make_vector_fld():
    x, y, z = make_grid()
    f0 = viscid.empty((x, y, z), dtype=DTYPE, nr_comps=3, center='node')
    viscid.fill_dipole(f0)
    # seeds = viscid.Sphere(r=10.0, nphi=64, ntheta=32)
    seeds = viscid.Sphere(r=10.0, nphi=32, ntheta=48)
    return f0, seeds
예제 #13
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)

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

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

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

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
예제 #14
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)

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

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

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

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
예제 #15
0
파일: vutil.py 프로젝트: zcl-maker/Viscid
def get_trilinear_field():
    """get a generic trilinear field"""
    xl, xh, nx = -1.0, 1.0, 41
    yl, yh, ny = -1.5, 1.5, 41
    zl, zh, nz = -2.0, 2.0, 41
    x = np.linspace(xl, xh, nx)
    y = np.linspace(yl, yh, ny)
    z = np.linspace(zl, zh, nz)
    crds = viscid.wrap_crds("nonuniform_cartesian", [('x', x), ('y', y),
                                                     ('z', z)])
    b = viscid.empty(crds,
                     name="f",
                     nr_comps=3,
                     center="Cell",
                     layout="interlaced")
    X, Y, Z = b.get_crds(shaped=True)

    x01, y01, z01 = 0.5, 0.5, 0.5
    x02, y02, z02 = 0.5, 0.5, 0.5
    x03, y03, z03 = 0.5, 0.5, 0.5

    b['x'][:] = (0.0 + 1.0 * (X - x01) + 1.0 * (Y - y01) + 1.0 * (Z - z01) +
                 1.0 * (X - x01) * (Y - y01) + 1.0 * (Y - y01) * (Z - z01) +
                 1.0 * (X - x01) * (Y - y01) * (Z - z01))
    b['y'][:] = (0.0 + 1.0 * (X - x02) - 1.0 * (Y - y02) + 1.0 * (Z - z02) +
                 1.0 * (X - x02) * (Y - y02) + 1.0 * (Y - y02) * (Z - z02) -
                 1.0 * (X - x02) * (Y - y02) * (Z - z02))
    b['z'][:] = (0.0 + 1.0 * (X - x03) + 1.0 * (Y - y03) - 1.0 * (Z - z03) +
                 1.0 * (X - x03) * (Y - y03) + 1.0 * (Y - y03) * (Z - z03) +
                 1.0 * (X - x03) * (Y - y03) * (Z - z03))
    return b
예제 #16
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
예제 #17
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
예제 #18
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)
예제 #19
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)
예제 #20
0
def run_test(x, y, profile=False):
    z = np.array([0.0])
    fld_nc = viscid.empty([x, y, z], center='node', name="MyField",
                          pretty_name="My Field [Units]")

    fld_cc = fld_nc.as_centered('cell')
    x2, y2 = fld_cc.get_crds_nc('xy')

    dx = x2[:-1] - x
    dy = y2[:-1] - y
    assert np.all(dx < np.zeros_like(dx)), 'cells are jumbled in x'
    assert np.all(dy < np.zeros_like(dy)), 'cells are jumbled in y'

    dx = x - x2[1:]
    dy = y - y2[1:]
    assert np.all(dx < np.zeros_like(dx)), 'cells are jumbled in x'
    assert np.all(dy < np.zeros_like(dy)), 'cells are jumbled in y'

    dx = x2[1:] - x2[:-1]
    dy = y2[1:] - y2[:-1]
    assert np.all(dx > np.zeros_like(dx)), 'new x nc not monotonic'
    assert np.all(dy > np.zeros_like(dy)), 'new y nc not monotonic'
예제 #21
0
파일: test_calc.py 프로젝트: jobejen/Viscid
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)
예제 #22
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))
    vlt.plot(fld_s, "y=20f", show=False, plot_opts="lin_0")
    plt.subplot2grid((nrows, ncols), (1, 0))
    vlt.plot(fld_s,
             "x=0f:20f,y=0f:5f",
             earth=True,
             show=False,
             plot_opts="x_-10_0,y_0_7")
    plt.subplot2grid((nrows, ncols), (2, 0))
    vlt.plot(fld_s, "y=0f", show=False, plot_opts="lin_-1_1")
    plt.subplot2grid((nrows, ncols), (3, 0))
    vlt.plot(fld_s,
             "z=0f,x=-20f:0f",
             earth=True,
             show=False,
             plot_opts="lin_-5_5")

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

    plt.savefig(next_plot_fname(__file__))
    if show:
        vlt.mplshow()
예제 #23
0
def run_test(x, y, profile=False):
    z = np.array([0.0])
    fld_nc = viscid.empty([x, y, z],
                          center='node',
                          name="MyField",
                          pretty_name="My Field [Units]")

    fld_cc = fld_nc.as_centered('cell')
    x2, y2 = fld_cc.get_crds_nc('xy')

    dx = x2[:-1] - x
    dy = y2[:-1] - y
    assert np.all(dx < np.zeros_like(dx)), 'cells are jumbled in x'
    assert np.all(dy < np.zeros_like(dy)), 'cells are jumbled in y'

    dx = x - x2[1:]
    dy = y - y2[1:]
    assert np.all(dx < np.zeros_like(dx)), 'cells are jumbled in x'
    assert np.all(dy < np.zeros_like(dy)), 'cells are jumbled in y'

    dx = x2[1:] - x2[:-1]
    dy = y2[1:] - y2[:-1]
    assert np.all(dx > np.zeros_like(dx)), 'new x nc not monotonic'
    assert np.all(dy > np.zeros_like(dy)), 'new y nc not monotonic'
예제 #24
0
def make_scalar_fld():
    x, y, z = make_grid()
    f0 = viscid.empty((x, y, z), dtype=DTYPE, center='node')
    f0.data = np.arange(np.prod(f0.shape)).astype(f0.dtype)
    seeds = viscid.Volume(xl=XL, xh=XH, n=N)
    return f0, seeds
예제 #25
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
예제 #26
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
예제 #27
0
def main():
    mhd_type = "C"
    make_plots = 1
    test_fc = 1
    test_ec = 1
    test_div = 1
    test_interp = 1
    test_streamline = 1

    mhd_type = mhd_type.upper()
    if mhd_type.startswith("C"):
        if mhd_type in ("C", ):
            f = viscid.load_file("$WORK/tmedium/*.3d.[-1].xdmf")
        elif mhd_type in ("C2", "C3"):
            f = viscid.load_file("$WORK/tmedium2/*.3d.[-1].xdmf")
        else:
            raise ValueError()
        catol = 1e-8
        rtol = 5e-6
    elif mhd_type in ("F", "FORTRAN"):
        f = viscid.load_file("$WORK/tmedium3/*.3df.[-1]")
        catol = 1e-8
        rtol = 7e-2
    else:
        raise ValueError()

    ISLICE = slice(None)
    # ISLICE = 'y=0f:0.15f'

    # #################
    # # test out fc2cc
    if test_fc:
        b = f['b'][ISLICE]
        b1 = f['b1'][ISLICE]

        compare_vectors(b,
                        b1,
                        viscid.fc2cc,
                        catol=catol,
                        rtol=rtol,
                        make_plots=make_plots)

    #################
    # test out ec2cc
    if test_ec:
        e_cc = f['e_cc'][ISLICE]
        e_ec = f['e_ec'][ISLICE]

        if mhd_type not in ("F", "FORTRAN"):
            compare_vectors(e_cc,
                            e_ec,
                            viscid.ec2cc,
                            catol=catol,
                            rtol=rtol,
                            make_plots=make_plots)

    #################
    # test out divfc
    # Note: Relative error on Div B is meaningless b/c the coordinates
    #       are not the same up to order (dx/4) I think. You can see this
    #       since (fcdiv - divb_trimmed) is both noisy and stripy
    if test_div:
        bnd = 0

        if mhd_type not in ("F", "FORTRAN"):
            b1 = f['b1'][ISLICE]
            divb = f['divB'][ISLICE]
            if bnd:
                trimmed = divb
            else:
                trimmed = divb['x=1:-1, y=1:-1, z=1:-1']
            b1mag = viscid.magnitude(viscid.fc2cc(b1, bnd=bnd))

            divb1 = viscid.div_fc(b1, bnd=bnd)

            viscid.set_in_region(trimmed,
                                 trimmed,
                                 alpha=0.0,
                                 beta=0.0,
                                 out=trimmed,
                                 mask=viscid.make_spherical_mask(trimmed,
                                                                 rmax=5.0))
            viscid.set_in_region(divb1,
                                 divb1,
                                 alpha=0.0,
                                 beta=0.0,
                                 out=divb1,
                                 mask=viscid.make_spherical_mask(divb1,
                                                                 rmax=5.0))

            reldiff = (divb1 - trimmed) / b1mag
            reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"]
            reldiff.name = divb1.name + " - " + trimmed.name
            reldiff.pretty_name = divb1.pretty_name + " - " + trimmed.pretty_name

            abs_max_rel_diff = np.nanmax(np.abs(reldiff))
            max_crd_diff = [0.0] * 3
            for i, d in enumerate('xyz'):
                max_crd_diff[i] = np.max(trimmed.get_crd(d) - divb1.get_crd(d))
            print("divB max absolute relative diff: {0:.3e} "
                  "(crds: X: {1[0]:.3e}, Y: {1[1]:.3e}, Z: {1[2]:.3e})"
                  "".format(abs_max_rel_diff, max_crd_diff))

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

            # Since the coordinates will be different by order dx^2 (i think),
            # there is no way to compare the divB from simulation with the
            # one we get here. However, they should be the same up to a few %, and
            # down to noise level with stripes of enhanced noise. These stripes
            # are the errors in the coordinate values (since the output only
            # gives us weird nc = averaged cc locations)
            #
            # if abs_max_rel_diff > rtol or np.any(np.abs(max_crd_diff) > catol):
            #     raise RuntimeError("Tolerance exceeded on divB calculation")

    if test_streamline:
        b_cc = f['b_cc']['x=-40f:12f, y=-15f:15f, z=-15f:15f']
        b_fc = f['b_fc']['x=-40f:12f, y=-15f:15f, z=-15f:15f']

        cotr = viscid.cotr.Cotr()
        r_mask = 3.0
        # set b_cc to dipole inside some sphere
        isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask)
        moment = cotr.get_dipole_moment(crd_system=b_cc)
        viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask)
        # set b_fc to dipole inside some sphere
        isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask)
        moment = cotr.get_dipole_moment(crd_system=b_fc)
        viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask)

        seeds = viscid.Volume([-10, 0, -5], [10, 0, 5], (16, 1, 3))
        sl_kwargs = dict(ibound=1.0, method=viscid.EULER1A)
        lines_cc, topo_cc = viscid.calc_streamlines(b_cc, seeds, **sl_kwargs)
        lines_fc, topo_fc = viscid.calc_streamlines(b_fc, seeds, **sl_kwargs)

        if make_plots:
            plt.figure(figsize=(10, 6))

            ax0 = plt.subplot(211)
            topo_cc_colors = viscid.topology2color(topo_cc)
            vlt.plot(f['pp']['y=0f'], logscale=True, earth=True, cmap='plasma')
            vlt.plot2d_lines(lines_cc, topo_cc_colors, symdir='y')

            ax0 = plt.subplot(212, sharex=ax0, sharey=ax0)
            topo_fc_colors = viscid.topology2color(topo_fc)
            vlt.plot(f['pp']['y=0f'], logscale=True, earth=True, cmap='plasma')
            vlt.plot2d_lines(lines_fc, topo_fc_colors, symdir='y')

            plt.xlim(-20, 10)
            plt.ylim(-10, 10)
            vlt.auto_adjust_subplots()
            vlt.show()

    if test_interp:
        # test interpolation with E . B / B
        b_cc = f['b_cc']
        b_fc = f['b_fc']
        e_cc = f['e_cc']
        e_ec = f['e_ec']

        cotr = viscid.cotr.Cotr()
        r_mask = 3.0
        # set b_cc to dipole inside some sphere
        isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask)
        moment = cotr.get_dipole_moment(crd_system=b_cc)
        viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask)
        # set b_fc to dipole inside some sphere
        isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask)
        moment = cotr.get_dipole_moment(crd_system=b_fc)
        viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask)
        # zero out e_cc inside some sphere
        viscid.set_in_region(e_cc,
                             e_cc,
                             alpha=0.0,
                             beta=0.0,
                             out=e_cc,
                             mask=viscid.make_spherical_mask(e_cc,
                                                             rmax=r_mask))
        # zero out e_ec inside some sphere
        viscid.set_in_region(e_ec,
                             e_ec,
                             alpha=0.0,
                             beta=0.0,
                             out=e_ec,
                             mask=viscid.make_spherical_mask(e_ec,
                                                             rmax=r_mask))

        tmp = viscid.empty([
            np.linspace(-10, 10, 64),
            np.linspace(-10, 10, 64),
            np.linspace(-10, 10, 64)
        ],
                           center="Cell")

        b_cc_interp = viscid.interp_linear(b_cc, tmp)
        b_fc_interp = viscid.interp_linear(b_fc, tmp)
        e_cc_interp = viscid.interp_linear(e_cc, tmp)
        e_ec_interp = viscid.interp_linear(e_ec, tmp)

        epar_cc = viscid.dot(e_cc_interp,
                             b_cc_interp) / viscid.magnitude(b_cc_interp)
        epar_ecfc = viscid.dot(e_ec_interp,
                               b_fc_interp) / viscid.magnitude(b_fc_interp)

        if make_plots:
            # plt.figure()
            # ax0 = plt.subplot(121)
            # vlt.plot(b_cc['x']['y=0f'], clim=(-40, 40))
            # plt.subplot(122, sharex=ax0, sharey=ax0)
            # vlt.plot(b_fc['x']['y=0f'], clim=(-40, 40))
            # vlt.show()

            plt.figure(figsize=(14, 5))
            ax0 = plt.subplot(131)
            vlt.plot(epar_cc['y=0f'], symmetric=True, cbarlabel="Epar CC")
            plt.subplot(132, sharex=ax0, sharey=ax0)
            vlt.plot(epar_ecfc['y=0f'], symmetric=True, cbarlabel="Epar ECFC")
            plt.subplot(133, sharex=ax0, sharey=ax0)
            vlt.plot(((epar_cc - epar_ecfc) / epar_cc)['y=0f'],
                     clim=(-10, 10),
                     cbarlabel="Rel Diff")
            vlt.auto_adjust_subplots()
            vlt.show()

    return 0
예제 #28
0
def main():
    mhd_type = "C"
    make_plots = 1
    test_fc = 1
    test_ec = 1
    test_div = 1
    test_interp = 1
    test_streamline = 1

    mhd_type = mhd_type.upper()
    if mhd_type.startswith("C"):
        if mhd_type in ("C",):
            f = viscid.load_file("$WORK/tmedium/*.3d.[-1].xdmf")
        elif mhd_type in ("C2", "C3"):
            f = viscid.load_file("$WORK/tmedium2/*.3d.[-1].xdmf")
        else:
            raise ValueError()
        catol = 1e-8
        rtol = 5e-6
    elif mhd_type in ("F", "FORTRAN"):
        f = viscid.load_file("$WORK/tmedium3/*.3df.[-1]")
        catol = 1e-8
        rtol = 7e-2
    else:
        raise ValueError()

    ISLICE = slice(None)
    # ISLICE = 'y=0j:0.15j'

    # #################
    # # test out fc2cc
    if test_fc:
        b = f['b'][ISLICE]
        b1 = f['b1'][ISLICE]

        compare_vectors(b, b1, viscid.fc2cc, catol=catol, rtol=rtol,
                        make_plots=make_plots)

    #################
    # test out ec2cc
    if test_ec:
        e_cc = f['e_cc'][ISLICE]
        e_ec = f['e_ec'][ISLICE]

        if mhd_type not in ("F", "FORTRAN"):
            compare_vectors(e_cc, e_ec, viscid.ec2cc, catol=catol, rtol=rtol,
                            make_plots=make_plots)

    #################
    # test out divfc
    # Note: Relative error on Div B is meaningless b/c the coordinates
    #       are not the same up to order (dx/4) I think. You can see this
    #       since (fcdiv - divb_trimmed) is both noisy and stripy
    if test_div:
        bnd = 0

        if mhd_type not in ("F", "FORTRAN"):
            b1 = f['b1'][ISLICE]
            divb = f['divB'][ISLICE]
            if bnd:
                trimmed = divb
            else:
                trimmed = divb['x=1:-1, y=1:-1, z=1:-1']
            b1mag = viscid.magnitude(viscid.fc2cc(b1, bnd=bnd))

            divb1 = viscid.div_fc(b1, bnd=bnd)

            viscid.set_in_region(trimmed, trimmed, alpha=0.0, beta=0.0, out=trimmed,
                                 mask=viscid.make_spherical_mask(trimmed, rmax=5.0))
            viscid.set_in_region(divb1, divb1, alpha=0.0, beta=0.0, out=divb1,
                                 mask=viscid.make_spherical_mask(divb1, rmax=5.0))

            reldiff = (divb1 - trimmed) / b1mag
            reldiff = reldiff["x=1:-1, y=1:-1, z=1:-1"]
            reldiff.name = divb1.name + " - " + trimmed.name
            reldiff.pretty_name = divb1.pretty_name + " - " + trimmed.pretty_name

            abs_max_rel_diff = np.nanmax(np.abs(reldiff))
            max_crd_diff = [0.0] * 3
            for i, d in enumerate('xyz'):
                max_crd_diff[i] = np.max(trimmed.get_crd(d) - divb1.get_crd(d))
            print("divB max absolute relative diff: {0:.3e} "
                  "(crds: X: {1[0]:.3e}, Y: {1[1]:.3e}, Z: {1[2]:.3e})"
                  "".format(abs_max_rel_diff, max_crd_diff))

            # plot differences?
            if make_plots:
                ax1 = plt.subplot(311)
                vlt.plot(divb['y=0j'], symmetric=True, earth=True)
                plt.subplot(312, sharex=ax1, sharey=ax1)
                vlt.plot(divb1['y=0j'], symmetric=True, earth=True)
                plt.subplot(313, sharex=ax1, sharey=ax1)
                vlt.plot(reldiff['y=0j'], symmetric=True, earth=True)
                vlt.show()

            # Since the coordinates will be different by order dx^2 (i think),
            # there is no way to compare the divB from simulation with the
            # one we get here. However, they should be the same up to a few %, and
            # down to noise level with stripes of enhanced noise. These stripes
            # are the errors in the coordinate values (since the output only
            # gives us weird nc = averaged cc locations)
            #
            # if abs_max_rel_diff > rtol or np.any(np.abs(max_crd_diff) > catol):
            #     raise RuntimeError("Tolerance exceeded on divB calculation")

    if test_streamline:
        b_cc = f['b_cc']['x=-40j:12j, y=-15j:15j, z=-15j:15j']
        b_fc = f['b_fc']['x=-40j:12j, y=-15j:15j, z=-15j:15j']

        cotr = viscid.cotr.Cotr()
        r_mask = 3.0
        # set b_cc to dipole inside some sphere
        isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask)
        moment = cotr.get_dipole_moment(crd_system=b_cc)
        viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask)
        # set b_fc to dipole inside some sphere
        isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask)
        moment = cotr.get_dipole_moment(crd_system=b_fc)
        viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask)

        seeds = viscid.Volume([-10, 0, -5], [10, 0, 5], (16, 1, 3))
        sl_kwargs = dict(ibound=1.0, method=viscid.EULER1A)
        lines_cc, topo_cc = viscid.calc_streamlines(b_cc, seeds, **sl_kwargs)
        lines_fc, topo_fc = viscid.calc_streamlines(b_fc, seeds, **sl_kwargs)

        if make_plots:
            plt.figure(figsize=(10, 6))

            ax0 = plt.subplot(211)
            topo_cc_colors = viscid.topology2color(topo_cc)
            vlt.plot(f['pp']['y=0j'], logscale=True, earth=True, cmap='plasma')
            vlt.plot2d_lines(lines_cc, topo_cc_colors, symdir='y')

            ax0 = plt.subplot(212, sharex=ax0, sharey=ax0)
            topo_fc_colors = viscid.topology2color(topo_fc)
            vlt.plot(f['pp']['y=0j'], logscale=True, earth=True, cmap='plasma')
            vlt.plot2d_lines(lines_fc, topo_fc_colors, symdir='y')

            plt.xlim(-20, 10)
            plt.ylim(-10, 10)
            vlt.auto_adjust_subplots()
            vlt.show()

    if test_interp:
        # test interpolation with E . B / B
        b_cc = f['b_cc']
        b_fc = f['b_fc']
        e_cc = f['e_cc']
        e_ec = f['e_ec']

        cotr = viscid.cotr.Cotr()
        r_mask = 3.0
        # set b_cc to dipole inside some sphere
        isphere_mask = viscid.make_spherical_mask(b_cc, rmax=r_mask)
        moment = cotr.get_dipole_moment(crd_system=b_cc)
        viscid.fill_dipole(b_cc, m=moment, mask=isphere_mask)
        # set b_fc to dipole inside some sphere
        isphere_mask = viscid.make_spherical_mask(b_fc, rmax=r_mask)
        moment = cotr.get_dipole_moment(crd_system=b_fc)
        viscid.fill_dipole(b_fc, m=moment, mask=isphere_mask)
        # zero out e_cc inside some sphere
        viscid.set_in_region(e_cc, e_cc, alpha=0.0, beta=0.0, out=e_cc,
                             mask=viscid.make_spherical_mask(e_cc, rmax=r_mask))
        # zero out e_ec inside some sphere
        viscid.set_in_region(e_ec, e_ec, alpha=0.0, beta=0.0, out=e_ec,
                             mask=viscid.make_spherical_mask(e_ec, rmax=r_mask))

        tmp = viscid.empty([np.linspace(-10, 10, 64), np.linspace(-10, 10, 64),
                            np.linspace(-10, 10, 64)], center="Cell")

        b_cc_interp = viscid.interp_linear(b_cc, tmp)
        b_fc_interp = viscid.interp_linear(b_fc, tmp)
        e_cc_interp = viscid.interp_linear(e_cc, tmp)
        e_ec_interp = viscid.interp_linear(e_ec, tmp)

        epar_cc = viscid.dot(e_cc_interp, b_cc_interp) / viscid.magnitude(b_cc_interp)
        epar_ecfc = viscid.dot(e_ec_interp, b_fc_interp) / viscid.magnitude(b_fc_interp)

        if make_plots:
            # plt.figure()
            # ax0 = plt.subplot(121)
            # vlt.plot(b_cc['x']['y=0j'], clim=(-40, 40))
            # plt.subplot(122, sharex=ax0, sharey=ax0)
            # vlt.plot(b_fc['x']['y=0j'], clim=(-40, 40))
            # vlt.show()

            plt.figure(figsize=(14, 5))
            ax0 = plt.subplot(131)
            vlt.plot(epar_cc['y=0j'], symmetric=True, cbarlabel="Epar CC")
            plt.subplot(132, sharex=ax0, sharey=ax0)
            vlt.plot(epar_ecfc['y=0j'], symmetric=True, cbarlabel="Epar ECFC")
            plt.subplot(133, sharex=ax0, sharey=ax0)
            vlt.plot(((epar_cc - epar_ecfc) / epar_cc)['y=0j'], clim=(-10, 10),
                     cbarlabel="Rel Diff")
            vlt.auto_adjust_subplots()
            vlt.show()

    return 0
예제 #29
0
def make_scalar_fld():
    x, y, z = make_grid()
    f0 = viscid.empty((x, y, z), dtype=DTYPE, center='node')
    f0.data = np.arange(np.prod(f0.shape)).astype(f0.dtype)
    seeds = viscid.Volume(xl=XL, xh=XH, n=N)
    return f0, seeds