Exemplo n.º 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()
Exemplo n.º 2
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()
Exemplo n.º 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
Exemplo n.º 4
0
def run_test_timeseries(f, main__file__, show=False):
    mpl.clf()

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

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

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

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

    mpl.plt.savefig(next_plot_fname(main__file__))
    if show:
        mpl.mplshow()
Exemplo n.º 5
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()
Exemplo n.º 6
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()
Exemplo n.º 7
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--notwo", dest='notwo', action="store_true")
    parser.add_argument("--nothree", dest='nothree', action="store_true")
    parser.add_argument("--show", "--plot", action="store_true")
    args = viscid.vutil.common_argparse(parser, default_verb=0)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        except ImportError:
            pass

    return 0
Exemplo n.º 8
0
def _get_sep_pts_bisect(
    fld,
    seed,
    trace_opts=None,
    min_depth=3,
    max_depth=7,
    plot=False,
    perimeter_check=perimeter_check_bitwise_or,
    make_3d=True,
    start_uneven=False,
    _base_quadrent="",
    _uneven_mask=0,
    _first_recurse=True,
):
    if len(_base_quadrent) == max_depth:
        return [_base_quadrent]  # causes pylint to complain
    if trace_opts is None:
        trace_opts = dict()

    nx, ny = seed.uv_shape
    (xlim, ylim) = seed.uv_extent

    if _first_recurse and start_uneven:
        _uneven_mask = UNEVEN_MASK

    if _first_recurse and plot:
        from viscid.plot import mvi
        from viscid.plot import mpl

        mpl.clf()
        _, all_topo = viscid.calc_streamlines(fld, seed, **trace_opts)
        mpl.plot(np.bitwise_and(all_topo, 15), show=False)
        verts, arr = seed.wrap_mesh(all_topo.data)
        mvi.mesh(verts[0], verts[1], verts[2], scalars=arr, opacity=0.75)

    # quadrents and lines are indexed as follows...
    # directions are counter clackwise around the quadrent with
    # lower index (which matters for lines which are shared among
    # more than one quadrent, aka, lines 1,2,6,7). Notice that even
    # numbered lines are horizontal, like the interstate system :)
    # -<--10-----<-8---
    # |       ^       ^
    # 11  2   9   3   7
    # \/      |       |
    # --<-2-----<-6----
    # |       ^       ^
    # 3   0   1   1   5
    # \/      |       |
    # ----0->-----4->--

    # find low(left), mid(center), and high(right) crds in x and y
    low_quad = "{0}{1:x}".format(_base_quadrent, 0 | _uneven_mask)
    high_quad = "{0}{1:x}".format(_base_quadrent, 3 | _uneven_mask)
    xl, xm, yl, ym = _quadrent_limits(low_quad, xlim, ylim)
    _, xh, _, yh = _quadrent_limits(high_quad, xlim, ylim)
    segsx, segsy = [None] * 12, [None] * 12
    topo = [None] * 12
    nxm, nym = nx // 2, ny // 2

    # make all the line segments
    segsx[0], segsy[0] = np.linspace(xl, xm, nxm), np.linspace(yl, yl, nxm)
    segsx[1], segsy[1] = np.linspace(xm, xm, nym), np.linspace(yl, ym, nym)
    segsx[2], segsy[2] = np.linspace(xm, xl, nxm), np.linspace(ym, ym, nxm)
    segsx[3], segsy[3] = np.linspace(xl, xl, nym), np.linspace(ym, yl, nym)

    segsx[4], segsy[4] = np.linspace(xm, xh, nxm), np.linspace(yl, yl, nxm)
    segsx[5], segsy[5] = np.linspace(xh, xh, nym), np.linspace(yl, ym, nym)
    segsx[6], segsy[6] = np.linspace(xh, xm, nxm), np.linspace(ym, ym, nxm)

    segsx[7], segsy[7] = np.linspace(xh, xh, nym), np.linspace(ym, yh, nym)
    segsx[8], segsy[8] = np.linspace(xh, xm, nxm), np.linspace(yh, yh, nxm)
    segsx[9], segsy[9] = np.linspace(xm, xm, nym), np.linspace(ym, yh, nym)

    segsx[10], segsy[10] = np.linspace(xm, xl, nxm), np.linspace(yh, yh, nxm)
    segsx[11], segsy[11] = np.linspace(xl, xl, nym), np.linspace(yh, ym, nym)

    allx = np.concatenate(segsx)
    ally = np.concatenate(segsy)

    # print("plot::", _base_quadrent, '|', _uneven_mask, '|', len(allx), len(ally))

    pts3d = seed.to_3d(seed.uv_to_local(np.array([allx, ally])))
    _, all_topo = viscid.calc_streamlines(fld, pts3d, **trace_opts)

    topo[0] = all_topo[: len(segsx[0])]
    cnt = len(topo[0])
    for i, segx in zip(count(1), segsx[1:]):
        topo[i] = all_topo[cnt : cnt + len(segx)]
        # print("??", i, cnt, cnt + len(segx), np.bitwise_and.reduce(topo[i]))
        cnt += len(topo[i])

    # assemble the lines into the four quadrents
    quad_topo = [None] * 4

    # all arrays snip off the last element since those are
    # duplicated by the next line... reversed arrays do the
    # snipping with -1:0:-1
    quad_topo[0] = np.concatenate([topo[0][:-1], topo[1][:-1], topo[2][:-1], topo[3][:-1]])

    quad_topo[1] = np.concatenate([topo[4][:-1], topo[5][:-1], topo[6][:-1], topo[1][-1:0:-1]])

    quad_topo[2] = np.concatenate([topo[2][-1:0:-1], topo[9][:-1], topo[10][:-1], topo[11][:-1]])

    quad_topo[3] = np.concatenate([topo[6][-1:0:-1], topo[7][:-1], topo[8][:-1], topo[9][-1:0:-1]])

    # now that the quad arrays are populated, decide which quadrents
    # still contain the separator (could be > 1)
    required_uneven_subquads = False
    ret = []
    for i in range(4):
        if perimeter_check(quad_topo[i]):
            next_quad = "{0}{1:x}".format(_base_quadrent, i | _uneven_mask)
            subquads = _get_sep_pts_bisect(
                fld,
                seed,
                trace_opts=trace_opts,
                min_depth=min_depth,
                max_depth=max_depth,
                plot=plot,
                _base_quadrent=next_quad,
                _uneven_mask=0,
                _first_recurse=False,
            )
            ret += subquads

    if len(ret) == 0:
        perimeter = np.concatenate(
            [
                topo[0][::-1],
                topo[4][::-1],
                topo[5][::-1],
                topo[7][::-1],
                topo[8][::-1],
                topo[10][::-1],
                topo[11][::-1],
                topo[3][::-1],
            ]
        )
        if _uneven_mask:
            if len(_base_quadrent) > min_depth:
                print("sep trace issue, but min depth reached: {0} > {1}" "".format(len(_base_quadrent), min_depth))
                ret = [_base_quadrent]
            else:
                print("sep trace issue, the separator ended prematurely")
        elif perimeter_check(perimeter):
            ret = _get_sep_pts_bisect(
                fld,
                seed,
                trace_opts=trace_opts,
                min_depth=min_depth,
                max_depth=max_depth,
                plot=plot,
                _base_quadrent=_base_quadrent,
                _uneven_mask=UNEVEN_MASK,
                _first_recurse=False,
            )
            required_uneven_subquads = True

    if plot and not required_uneven_subquads:
        from viscid.plot import mvi
        from viscid.plot import mpl

        _pts3d = seed.to_3d(seed.uv_to_local(np.array([allx, ally])))
        mvi.points3d(_pts3d[0], _pts3d[1], _pts3d[2], all_topo.data.reshape(-1), scale_mode="none", scale_factor=0.02)
        mpl.plt.scatter(
            allx, ally, color=np.bitwise_and(all_topo, 15), vmin=0, vmax=15, marker="o", edgecolor="y", s=40
        )

    if _first_recurse:
        # turn quadrent strings into locations
        xc = np.empty(len(ret))
        yc = np.empty(len(ret))
        for i, r in enumerate(ret):
            xc[i], yc[i] = _quadrent_center(r, xlim, ylim)
        pts_uv = np.array([xc, yc])
        if plot:
            from viscid.plot import mvi
            from viscid.plot import mpl

            mpl.plt.plot(pts_uv[0], pts_uv[1], "y*", ms=20, markeredgecolor="k", markeredgewidth=1.0)
            mpl.show(block=False)
            mvi.show(stop=True)
        # return seed.to_3d(seed.uv_to_local(pts_uv))
        # if pts_uv.size == 0:
        #     return None
        if make_3d:
            return seed.uv_to_3d(pts_uv)
        else:
            return pts_uv
    else:
        return ret
Exemplo n.º 9
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
Exemplo n.º 10
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()