Пример #1
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()
Пример #2
0
def _main():
    x = np.linspace(-1, 1, 128)
    y = z = np.linspace(-0.25, 0.25, 8)
    B = viscid.zeros((x, y, z), nr_comps=3, layout='interlaced', name="B")
    X, Y, Z = B.get_crds("xyz", shaped=True)  # pylint: disable=unused-variable
    xl, yl, zl = B.xl  # pylint: disable=unused-variable
    xh, yh, zh = B.xh  # pylint: disable=unused-variable
    xm, ym, zm = 0.5 * (B.xl + B.xh)  # pylint: disable=unused-variable

    B['x'] = 0.0  # np.sin(1.0 * np.pi * X / (xh - xl) + 0.5 * np.pi)
    B['y'] = np.sin(1.0 * np.pi * X / (xh - xl) + 0.5 * np.pi)
    B['z'] = np.sin(1.0 * np.pi * X / (xh - xl) - 1.0 * np.pi)
    B += 0.33 * np.random.random_sample(B.shape)

    # R = viscid.make_rotation_matrix((0, 0, 0), (1, 0, 0), (1, 0, 1))
    # B[...] = np.einsum("ij,lmnj->lmni", R, B)

    lmn = find_minvar_lmn(B, (xl, ym, zm), (xh, ym, zm), l_basis=None)
    # lmn = find_minvar_lmn(B, (xl, ym, zm), (xh, ym, zm), l_basis=(0, 0, 1))
    print("LMN matrix:\n", lmn, sep='')

    ##########
    from viscid.plot import mpl
    p0 = np.array((xm, ym, zm)).reshape((3,))
    pl = p0 + 0.25 * lmn[:, 0]
    pm = p0 + 0.25 * lmn[:, 1]
    pn = p0 + 0.25 * lmn[:, 2]

    print("p0", p0)
    print("pl", pl)
    print("pm", pm)
    print("pn", pn)

    mpl.subplot(211)
    mpl.plot2d_quiver(B['z=0f'])
    mpl.plt.plot([p0[0], pl[0]], [p0[1], pl[1]], color='r', ls='-')
    mpl.plt.plot([p0[0], pm[0]], [p0[1], pm[1]], color='c', ls='-')
    mpl.plt.plot([p0[0], pn[0]], [p0[1], pn[1]], color='b', ls='-')
    mpl.plt.ylabel("Y")

    mpl.subplot(212)
    mpl.plot2d_quiver(B['y=0f'])
    mpl.plt.plot([p0[0], pl[0]], [p0[2], pl[2]], color='r', ls='-')
    mpl.plt.plot([p0[0], pm[0]], [p0[2], pm[2]], color='c', ls='-')
    mpl.plt.plot([p0[0], pn[0]], [p0[2], pn[2]], color='b', ls='-')
    mpl.plt.xlabel("X")
    mpl.plt.ylabel("Z")

    mpl.show()
    ##########

    return 0
Пример #3
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
Пример #4
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()
Пример #5
0
def main():
    parser = argparse.ArgumentParser(description="Test divergence")
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser)
    # args.show = True

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

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

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

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

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

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

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

    return 0
Пример #6
0
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()
Пример #7
0
def main():
    mhd_type = "C3"
    make_plots = 1

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

    b = f['b_cc']
    b1 = f['b_fc']
    e_cc = f['e_cc']
    e_ec = f['e_ec']
    # divb =  f['divB']

    # viscid.interact()

    if True:
        bD = viscid.empty_like(b)
        bD.data = np.array(b.data)

        b1D = viscid.empty_like(b1)
        b1D.data = np.array(b1.data)

        mask5 = viscid.make_spherical_mask(bD, rmax=3.5)
        mask1_5 = viscid.make_spherical_mask(bD, rmax=1.5)
        viscid.fill_dipole(bD, mask=mask5)
        viscid.set_in_region(bD, bD, 0.0, 0.0, mask=mask1_5, out=bD)

        # compare_vectors(_b, bD, make_plots=True)
        mask5 = viscid.make_spherical_mask(b1D, rmax=3.5)
        mask1_5 = viscid.make_spherical_mask(b1D, rmax=1.5)
        viscid.fill_dipole(b1D, mask=mask5)
        viscid.set_in_region(b1D, b1D, 0.0, 0.0, mask=mask1_5, out=b1D)

        compare_vectors(bD["x=1:-1, y=1:-1, z=1:-1"], b1D.as_cell_centered(),
                        make_plots=True)

        # mpl.plt.clf()
        # dkwargs = dict(symmetric=True, earth=True, clim=(-1e2, 1e2))
        # ax1 = mpl.plt.subplot(311)
        # mpl.plot(viscid.div(b1)['y=0f'], **dkwargs)
        # mpl.plt.subplot(312, sharex=ax1, sharey=ax1)
        # mpl.plot(viscid.div(b)['y=0f'], **dkwargs)
        # mpl.plt.subplot(313, sharex=ax1, sharey=ax1)
        # mpl.plot(viscid.div(b1D)['y=0f'], **dkwargs)
        # mpl.show()

        bD = b1D = mask5 = mask1_5 = None

    # straight up interpolate b1 to cc crds and compare with b
    if True:
        b1_cc = viscid.interp_trilin(b1, b).as_flat()

        viscid.set_in_region(b, b, alpha=0.0, beta=0.0, out=b,
                             mask=viscid.make_spherical_mask(b, rmax=5.0))
        viscid.set_in_region(b1_cc, b1_cc, alpha=0.0, beta=0.0, out=b1_cc,
                             mask=viscid.make_spherical_mask(b1_cc, rmax=5.0))

        compare_vectors(b, b1_cc, make_plots=True)

    # make div?
    if True:
        # make seeds for 1.5x supersampling b1
        n = 128
        seeds = viscid.Volume((5.1, -0.02, -5.0), (12.0, 0.02, 5.0), (n, 3, n))
        # do interpolation onto new seeds
        b2 = viscid.interp_trilin(b1, seeds)

        div_b = viscid.div(b)
        div_b1 = viscid.div(b1)
        div_b2 = viscid.div(b2)

        viscid.set_in_region(div_b, div_b, alpha=0.0, beta=0.0, out=div_b,
                             mask=viscid.make_spherical_mask(div_b, rmax=5.0))
        viscid.set_in_region(div_b1, div_b1, alpha=0.0, beta=0.0, out=div_b1,
                             mask=viscid.make_spherical_mask(div_b1, rmax=5.0))
        viscid.set_in_region(div_b2, div_b2, alpha=0.0, beta=0.0, out=div_b2,
                             mask=viscid.make_spherical_mask(div_b2, rmax=5.0))
        viscid.set_in_region(divb, divb, alpha=0.0, beta=0.0, out=divb,
                             mask=viscid.make_spherical_mask(divb, rmax=5.0))

        mpl.plt.clf()
        ax1 = mpl.subplot(311)
        mpl.plot(div_b['y=0f'], symmetric=True, earth=True)
        mpl.subplot(312, sharex=ax1, sharey=ax1)
        # mpl.plot(div_b1['y=0f'], symmetric=True, earth=True)
        mpl.plot(div_b2['y=0f'], symmetric=True, earth=True)
        mpl.subplot(313, sharex=ax1, sharey=ax1)
        mpl.plot(divb['y=0f'], symmetric=True, earth=True)

        mpl.show()

    return 0
Пример #8
0
def main():
    parser = argparse.ArgumentParser(description="Test grad")
    parser.add_argument("--prof", action="store_true")
    parser.add_argument("--show", "--plot", action="store_true")
    args = vutil.common_argparse(parser)

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

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

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

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

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

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

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

    mpl.auto_adjust_subplots()

    mpl.plt.savefig(next_plot_fname(__file__))
    if args.show:
        mpl.show()
Пример #9
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()
Пример #10
0
def main():
    mhd_type = "C"
    make_plots = 1

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

    do_fill_dipole = True

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

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

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

        mask = None

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

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

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

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

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

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

    return 0
Пример #11
0
def topology_bitor_clusters(
    fld,
    min_depth=1,
    max_depth=10,
    multiple=True,
    plot=False,
    sep_val=streamline.TOPOLOGY_MS_SEPARATOR,
    mask_limit=0b1111,
    periodic="00",
    pt_bnds=(),
):
    """Find separator as intersection of all global topologies

    Neighbors are bitwise ORed until at least one value matches
    `sep_val` which is presumably (Close | Open N | Open S | SW).
    This happens between min_depth and max_depth times,
    where the resolution of each iteration is reduced by a factor
    of two, ie, worst case 2**(max_depth).

    Args:
        fld (Field): Topology (bitmask) as a field
        min_depth (int): Iterate at least this many times
        max_depth (int): Iterate at most this many times
        multiple (bool): passed to :py:func:`viscid.cluster`
        sep_val (int): Value of bitmask that indicates a separator
        plot (bool): Make a 2D plot of Fld and the sep candidates
        mask_limit (int): if > 0, then bitmask fld with mask_limit,
            i.e., fld = fld & mask_limit (bitwise and)
        periodic (sequence): indicate whether that direction is
            periodic, and if so, whether the coordinate arrays are
            overlapped or not. Values can be True, False, or '+'. '+'
            indicates that x[0] and x[-1] are not colocated, so assume
            they're dx apart where dx = x[-1] - x[-2].
        pt_bnd (sequence): Boundaries that come to a point, i.e., all
            values along that boundary are neighbors such as the poles
            of a sphere. Specified like "0-" for lower boundary of
            dimension 0 or "1+" for the upper boundary of dimension 1.

    Returns:
        ndarray: 2xN for N clusters of separator points in the same
        coordinates as `fld`
    """
    pd = [False if pi == "0" else bool(pi) for pi in periodic]
    fld = fld.slice_reduce(":")
    if mask_limit:
        fld = np.bitwise_and(fld, mask_limit)
    a = fld.data
    x, y = fld.get_crds()

    for i in range(max_depth):
        if pd[0]:
            a[(0, -1), :] |= a[(-1, 0), :]
        if pd[1]:
            a[:, (0, -1)] |= a[:, (-1, 0)]

        a = (
            a[:-1, :-1] | a[:-1, 1:] | a[1:, :-1] | a[1:, 1:]  # pylint: disable=bad-whitespace
        )  # pylint: disable=bad-whitespace
        x = 0.5 * (x[1:] + x[:-1])
        y = 0.5 * (y[1:] + y[:-1])

        # bitwise_or an entire bounary if all points are neighbors, like
        # at the poles of a sphere
        for bnd in pt_bnds:
            slc = [slice(None), slice(None)]
            slc[int(bnd[0])] = -1 if bnd[1] == "+" else 0
            a[slc] = np.bitwise_or.reduce(a[slc])

        indx, indy = np.where(a == sep_val)
        if i + 1 >= min_depth and len(indx):
            break

    pts = viscid.cluster(indx, indy, x, y, multiple=multiple, periodic=periodic)

    if plot:
        from viscid.plot import mpl

        mpl.clf()
        ax0 = mpl.subplot(121)
        mpl.plot(fld, title=True)

        mpl.subplot(122, sharex=ax0, sharey=ax0)
        or_fld = viscid.arrays2field(a, (x, y), name="OR")
        mpl.plot(or_fld, title=True)

        _x, _y = or_fld.get_crds()
        mpl.plt.plot(_x[indx], _y[indy], "ko")

        mpl.plt.plot(pts[0], pts[1], "y^")
        mpl.plt.show()

    return pts
Пример #12
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()