Ejemplo n.º 1
0
def local_vector_points(B, x, y, z, dx=None, dy=None, dz=None):
    """Get B at 6 points surrounding X

    X = [x, y, z] with spacing [+/-dx, +/-dy, +/-dz]

    Args:
        B (VectorField): B field
        x (float, ndarray, list): x (single value)
        y (float, ndarray, list): y (single value)
        z (float, ndarray, list): z (single value)
        dx (float, optional): dx, one grid cell if None
        dy (float, optional): dy, one grid cell if None
        dz (float, optional): dz, one grid cell if None

    Returns:
        (bs, pts, dcrd)

        * bs (ndarary): shape (6, 3) where 0-3 -> Bx,By,Bz
          and 0-6 -> X-dx, X+dx, X-dy, X+dy, X-dz, X+dz
        * pts (ndarray): shape (6, 3); the location of the
          points of the bs, but this time, 0-3 -> x,y,z
        * dcrd (list): [dx, dy, dz]
    """
    assert has_cython  # if a problem, you need to build Viscid
    assert B.iscentered("Cell")

    x, y, z = [np.array(c).reshape(1, 1) for c in [x, y, z]]
    crds = B.get_crds("xyz")
    inds = [0] * len(crds)
    dcrd = [0] * len(crds)
    # This makes points in xyz order
    pts = np.tile([x, y, z], 6).reshape(3, -1).T
    for i, crd, loc, d in zip(count(), crds, [x, y, z], [dx, dy, dz]):
        inds[i] = cycalc.closest_ind(crd, loc)
        if d is None:
            dcrd[i] = crd[inds[i] + 1] - crd[inds[i]]
        else:
            dcrd[i] = d
        pts[2 * i + 1, i] += dcrd[i]
        pts[2 * i + 0, i] -= dcrd[i]
    bs = cycalc.interp_trilin(B, seed.Point(pts))
    # viscid.interact(banner="in local_vector_points")
    return bs, pts, dcrd
Ejemplo n.º 2
0
def local_vector_points(B, x, y, z, dx=None, dy=None, dz=None):
    """Get B at 6 points surrounding X

    X = [x, y, z] with spacing [+/-dx, +/-dy, +/-dz]

    Args:
        B (VectorField): B field
        x (float, ndarray, list): x (single value)
        y (float, ndarray, list): y (single value)
        z (float, ndarray, list): z (single value)
        dx (float, optional): dx, one grid cell if None
        dy (float, optional): dy, one grid cell if None
        dz (float, optional): dz, one grid cell if None

    Returns:
        (bs, pts, dcrd)

        * bs (ndarary): shape (6, 3) where 0-3 -> Bx,By,Bz
          and 0-6 -> X-dx, X+dx, X-dy, X+dy, X-dz, X+dz
        * pts (ndarray): shape (6, 3); the location of the
          points of the bs, but this time, 0-3 -> x,y,z
        * dcrd (list): [dx, dy, dz]
    """
    assert has_cython  # if a problem, you need to build Viscid
    assert B.iscentered("Cell")

    x, y, z = [np.array(c).reshape(1, 1) for c in [x, y, z]]
    crds = B.get_crds("xyz")
    inds = [0] * len(crds)
    dcrd = [0] * len(crds)
    # This makes points in xyz order
    pts = np.tile([x, y, z], 6).reshape(3, -1).T
    for i, crd, loc, d in zip(count(), crds, [x, y, z], [dx, dy, dz]):
        inds[i] = cycalc.closest_ind(crd, loc)
        if d is None:
            dcrd[i] = crd[inds[i] + 1] - crd[inds[i]]
        else:
            dcrd[i] = d
        pts[2 * i + 1, i] += dcrd[i]
        pts[2 * i + 0, i] -= dcrd[i]
    bs = cycalc.interp_trilin(B, seed.Point(pts))
    # viscid.interact(banner="in local_vector_points")
    return bs, pts, dcrd
Ejemplo n.º 3
0
def _follow_fluid_step(i, dt, grid, root_seeds, plot_function, stream_opts,
                       speed_scale):
    direction = int(dt / np.abs(dt))
    if direction >= 0:
        sl_direction = streamline.DIR_FORWARD
    else:
        sl_direction = streamline.DIR_BACKWARD

    logger.info("working on timestep {0} {1}".format(i, grid.time))
    v = grid["v"]
    logger.debug("finished reading V field")

    logger.debug("calculating new streamline positions")
    flow_lines = calc_streamlines(v, root_seeds,
                                  output=viscid.OUTPUT_STREAMLINES,
                                  stream_dir=sl_direction,
                                  **stream_opts)[0]

    logger.debug("done with that, now i'm plotting...")
    plot_function(i, grid, v, flow_lines, root_seeds)

    ############################################################
    # now recalculate the seed positions for the next timestep
    logger.debug("finding new seed positions...")
    root_pts = root_seeds.genr_points()
    valid_pt_inds = []
    for i in range(root_pts.shape[1]):
        valid_pt = True

        # get the index of the root point in teh 2d flow line array
        # dist = flow_lines[i] - root_pts[:, [i]]
        # root_ind = np.argmin(np.sum(dist**2, axis=0))
        # print("!!!", root_pts[:, i], "==", flow_lines[i][:, root_ind])
        # interpolate velocity onto teh flow line, and get speed too
        v_interp = cycalc.interp_trilin(v, seed.Point(flow_lines[i]))
        speed = np.sqrt(np.sum(v_interp * v_interp, axis=1))

        # this is a super slopy way to integrate velocity
        # keep marching along the flow line until we get to the next timestep
        t = 0.0
        ind = 0
        if direction < 0:
            flow_lines[i] = flow_lines[i][:, ::-1]
            speed = speed[::-1]

        while t < np.abs(dt):
            ind += 1
            if ind >= len(speed):
                # set valid_pt to True if you want to keep that point for
                # future time steps, but most likely if we're here, the seed
                # has gone out of our region of interest
                ind = len(speed) - 1
                valid_pt = False
                logger.info("OOPS: ran out of streamline, increase "
                            "max_length when tracing flow lines if this "
                            "is unexpected")
                break
            t += stream_opts["ds0"] / (speed_scale * speed[ind])

        root_pts[:, i] = flow_lines[i][:, ind]
        if valid_pt:
            valid_pt_inds.append(i)

    # remove seeds that have flown out of our region of interest
    # (aka, beyond the flow line we drew)
    root_pts = root_pts[:, valid_pt_inds]

    logger.debug("ok, done with all that :)")
    return root_pts
Ejemplo n.º 4
0
def main():
    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 = coordinate.wrap_crds("nonuniform_cartesian",
                                [('z', z), ('y', y), ('x', x)])
    bx = field.empty(crds, name="$B_x$", center="Node")
    by = field.empty(crds, name="$B_y$", center="Node")
    bz = field.empty(crds, name="$B_z$", center="Node")
    fld = field.empty(crds, name="B", nr_comps=3, center="Node",
                      layout="interlaced")
    X, Y, Z = crds.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

    bx[:] = 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)
    by[:] = 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)
    bz[:] = 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)
    fld[..., 0] = bx
    fld[..., 1] = by
    fld[..., 2] = bz

    fig = mlab.figure(size=(1150, 850),
                      bgcolor=(1.0, 1.0, 1.0),
                      fgcolor=(0.0, 0.0, 0.0))
    f1_src = vlab.add_field(bx)
    f2_src = vlab.add_field(by)
    f3_src = vlab.add_field(bz)
    mlab.pipeline.iso_surface(f1_src, contours=[0.0],
                              opacity=1.0, color=(1.0, 0.0, 0.0))
    mlab.pipeline.iso_surface(f2_src, contours=[0.0],
                              opacity=1.0, color=(0.0, 1.0, 0.0))
    mlab.pipeline.iso_surface(f3_src, contours=[0.0],
                              opacity=1.0, color=(0.0, 0.0, 1.0))
    mlab.axes()
    mlab.show()

    nullpt = cycalc.interp_trilin(fld, [(0.5, 0.5, 0.5)])
    print("f(0.5, 0.5, 0.5):", nullpt)

    _, axes = plt.subplots(4, 3, sharex=True, sharey=True)
    all_roots = []
    positive_roots = []
    ix = iy = iz = 0

    for di, d in enumerate([0, -1]):
        #### XY face
        a1 = bx[iz + d, iy, ix]
        b1 = bx[iz + d, iy, ix - 1] - a1
        c1 = bx[iz + d, iy - 1, ix] - a1
        d1 = bx[iz + d, iy - 1, ix - 1] - c1 - b1 - a1

        a2 = by[iz + d, iy, ix]
        b2 = by[iz + d, iy, ix - 1] - a2
        c2 = by[iz + d, iy - 1, ix] - a2
        d2 = by[iz + d, iy - 1, ix - 1] - c2 - b2 - a2

        a3 = bz[iz + d, iy, ix]
        b3 = bz[iz + d, iy, ix - 1] - a3
        c3 = bz[iz + d, iy - 1, ix] - a3
        d3 = bz[iz + d, iy - 1, ix - 1] - c3 - b3 - a3

        roots1, roots2 = find_roots_face(a1, b1, c1, d1, a2, b2, c2, d2)

        # for rt1, rt2 in zip(roots1, roots2):
        #     print("=")
        #     print("fx", a1 + b1 * rt1 + c1 * rt2 + d1 * rt1 * rt2)
        #     print("fy", a2 + b2 * rt1 + c2 * rt2 + d2 * rt1 * rt2)
        #     print("=")

        # find f3 at the root points
        f3 = np.empty_like(roots1)
        markers = [None] * len(f3)
        for i, rt1, rt2 in zip(count(), roots1, roots2):
            f3[i] = a3 + b3 * rt1 + c3 * rt2 + d3 * rt1 * rt2
            all_roots.append((rt1, rt2, d))  # switch order here
            if f3[i] >= 0.0:
                markers[i] = 'k^'
                positive_roots.append((rt1, rt2, d))  # switch order here
            else:
                markers[i] = 'w^'

        # rescale the roots to the original domain
        roots1 = (xh - xl) * roots1 + xl
        roots2 = (yh - yl) * roots2 + yl

        xp = np.linspace(0.0, 1.0, nx)

        vlt.plot(fld['x'], "z={0}i".format(d), ax=axes[0 + 2 * di, 0],
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(xl, xh, yl, yh))
        y1 = - (a1 + b1 * xp) / (c1 + d1 * xp)
        plt.plot(x, (yh - yl) * y1 + yl, 'k')
        for i, xrt, yrt in zip(count(), roots1, roots2):
            plt.plot(xrt, yrt, markers[i])

        vlt.plot(fld['y'], "z={0}i".format(d), ax=axes[1 + 2 * di, 0],
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(xl, xh, yl, yh))
        y2 = - (a2 + b2 * xp) / (c2 + d2 * xp)
        plt.plot(x, (yh - yl) * y2 + yl, 'k')
        for xrt, yrt in zip(roots1, roots2):
            plt.plot(xrt, yrt, markers[i])

        #### YZ face
        a1 = bx[iz, iy, ix + d]
        b1 = bx[iz, iy - 1, ix + d] - a1
        c1 = bx[iz - 1, iy, ix + d] - a1
        d1 = bx[iz - 1, iy - 1, ix + d] - c1 - b1 - a1

        a2 = by[iz, iy, ix + d]
        b2 = by[iz, iy - 1, ix + d] - a2
        c2 = by[iz - 1, iy, ix + d] - a2
        d2 = by[iz - 1, iy - 1, ix + d] - c2 - b2 - a2

        a3 = bz[iz, iy, ix + d]
        b3 = bz[iz, iy - 1, ix + d] - a3
        c3 = bz[iz - 1, iy, ix + d] - a3
        d3 = bz[iz - 1, iy - 1, ix + d] - c3 - b3 - a3

        roots1, roots2 = find_roots_face(a1, b1, c1, d1, a2, b2, c2, d2)

        # for rt1, rt2 in zip(roots1, roots2):
        #     print("=")
        #     print("fx", a1 + b1 * rt1 + c1 * rt2 + d1 * rt1 * rt2)
        #     print("fy", a2 + b2 * rt1 + c2 * rt2 + d2 * rt1 * rt2)
        #     print("=")

        # find f3 at the root points
        f3 = np.empty_like(roots1)
        markers = [None] * len(f3)
        for i, rt1, rt2 in zip(count(), roots1, roots2):
            f3[i] = a3 + b3 * rt1 + c3 * rt2 + d3 * rt1 * rt2
            all_roots.append((d, rt1, rt2))  # switch order here
            if f3[i] >= 0.0:
                markers[i] = 'k^'
                positive_roots.append((d, rt1, rt2))  # switch order here
            else:
                markers[i] = 'w^'

        # rescale the roots to the original domain
        roots1 = (yh - yl) * roots1 + yl
        roots2 = (zh - zl) * roots2 + zl

        yp = np.linspace(0.0, 1.0, ny)

        # plt.subplot(121)
        vlt.plot(fld['x'], "x={0}i".format(d), ax=axes[0 + 2 * di, 1],
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(yl, yh, zl, zh))
        z1 = - (a1 + b1 * yp) / (c1 + d1 * yp)
        plt.plot(y, (zh - zl) * z1 + zl, 'k')
        for i, yrt, zrt in zip(count(), roots1, roots2):
            plt.plot(yrt, zrt, markers[i])

        # plt.subplot(122)
        vlt.plot(fld['y'], "x={0}i".format(d), ax=axes[1 + 2 * di, 1],
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(yl, yh, zl, zh))
        z1 = - (a2 + b2 * yp) / (c2 + d2 * yp)
        plt.plot(y, (zh - zl) * z1 + zl, 'k')
        for i, yrt, zrt in zip(count(), roots1, roots2):
            plt.plot(yrt, zrt, markers[i])

        #### ZX face
        a1 = bx[iz, iy + d, ix]
        b1 = bx[iz - 1, iy + d, ix] - a1
        c1 = bx[iz, iy + d, ix - 1] - a1
        d1 = bx[iz - 1, iy + d, ix - 1] - c1 - b1 - a1

        a2 = by[iz, iy + d, ix]
        b2 = by[iz - 1, iy + d, ix] - a2
        c2 = by[iz, iy + d, ix - 1] - a2
        d2 = by[iz - 1, iy + d, ix - 1] - c2 - b2 - a2

        a3 = bz[iz, iy + d, ix]
        b3 = bz[iz - 1, iy + d, ix] - a3
        c3 = bz[iz, iy + d, ix - 1] - a3
        d3 = bz[iz - 1, iy + d, ix - 1] - c3 - b3 - a3

        roots1, roots2 = find_roots_face(a1, b1, c1, d1, a2, b2, c2, d2)

        # for rt1, rt2 in zip(roots1, roots2):
        #     print("=")
        #     print("fx", a1 + b1 * rt1 + c1 * rt2 + d1 * rt1 * rt2)
        #     print("fy", a2 + b2 * rt1 + c2 * rt2 + d2 * rt1 * rt2)
        #     print("=")

        # find f3 at the root points
        f3 = np.empty_like(roots1)
        markers = [None] * len(f3)
        for i, rt1, rt2 in zip(count(), roots1, roots2):
            f3[i] = a3 + b3 * rt1 + c3 * rt2 + d3 * rt1 * rt2
            all_roots.append((rt2, d, rt1))  # switch order here
            if f3[i] >= 0.0:
                markers[i] = 'k^'
                positive_roots.append((rt2, d, rt1))  # switch order here
            else:
                markers[i] = 'w^'

        # rescale the roots to the original domain
        roots1 = (zh - zl) * roots1 + zl
        roots2 = (xh - xl) * roots2 + xl

        zp = np.linspace(0.0, 1.0, nz)

        # plt.subplot(121)
        vlt.plot(fld['x'], "y={0}i".format(d), ax=axes[0 + 2 * di, 2],
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(xl, xh, zl, zh))
        x1 = - (a1 + b1 * zp) / (c1 + d1 * zp)
        plt.plot(z, (xh - xl) * x1 + xl, 'k')
        for i, zrt, xrt in zip(count(), roots1, roots2):
            plt.plot(xrt, zrt, markers[i])

        # plt.subplot(121)
        vlt.plot(fld['y'], "y={0}i".format(d), ax=axes[1 + 2 * di, 2],
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(xl, xh, zl, zh))
        x1 = - (a2 + b2 * zp) / (c2 + d2 * zp)
        plt.plot(z, (xh - xl) * x1 + xl, 'k')
        for i, zrt, xrt in zip(count(), roots1, roots2):
            plt.plot(xrt, zrt, markers[i])

    print("all:", len(all_roots), "positive:", len(positive_roots))
    if len(all_roots) % 2 == 1:
        print("something is fishy, there are an odd number of root points "
              "on the surface of your cube, there is probably a degenerate "
              "line or surface of nulls")
    print("Null Point?", (len(positive_roots) % 2 == 1))

    plt.show()
Ejemplo n.º 5
0
def _follow_fluid_step(i, dt, grid, root_seeds, plot_function, stream_opts,
                       speed_scale):
    direction = int(dt / np.abs(dt))
    if direction >= 0:
        sl_direction = streamline.DIR_FORWARD
    else:
        sl_direction = streamline.DIR_BACKWARD

    logger.info("working on timestep {0} {1}".format(i, grid.time))
    v = grid["v"]
    logger.debug("finished reading V field")

    logger.debug("calculating new streamline positions")
    flow_lines = calc_streamlines(v,
                                  root_seeds,
                                  output=viscid.OUTPUT_STREAMLINES,
                                  stream_dir=sl_direction,
                                  **stream_opts)[0]

    logger.debug("done with that, now i'm plotting...")
    plot_function(i, grid, v, flow_lines, root_seeds)

    ############################################################
    # now recalculate the seed positions for the next timestep
    logger.debug("finding new seed positions...")
    root_pts = root_seeds.genr_points()
    valid_pt_inds = []
    for i in range(root_pts.shape[1]):
        valid_pt = True

        # get the index of the root point in teh 2d flow line array
        # dist = flow_lines[i] - root_pts[:, [i]]
        # root_ind = np.argmin(np.sum(dist**2, axis=0))
        # print("!!!", root_pts[:, i], "==", flow_lines[i][:, root_ind])
        # interpolate velocity onto teh flow line, and get speed too
        v_interp = cycalc.interp_trilin(v, seed.Point(flow_lines[i]))
        speed = np.sqrt(np.sum(v_interp * v_interp, axis=1))

        # this is a super slopy way to integrate velocity
        # keep marching along the flow line until we get to the next timestep
        t = 0.0
        ind = 0
        if direction < 0:
            flow_lines[i] = flow_lines[i][:, ::-1]
            speed = speed[::-1]

        while t < np.abs(dt):
            ind += 1
            if ind >= len(speed):
                # set valid_pt to True if you want to keep that point for
                # future time steps, but most likely if we're here, the seed
                # has gone out of our region of interest
                ind = len(speed) - 1
                valid_pt = False
                logger.info("OOPS: ran out of streamline, increase "
                            "max_length when tracing flow lines if this "
                            "is unexpected")
                break
            t += stream_opts["ds0"] / (speed_scale * speed[ind])

        root_pts[:, i] = flow_lines[i][:, ind]
        if valid_pt:
            valid_pt_inds.append(i)

    # remove seeds that have flown out of our region of interest
    # (aka, beyond the flow line we drew)
    root_pts = root_pts[:, valid_pt_inds]

    logger.debug("ok, done with all that :)")
    return root_pts
Ejemplo n.º 6
0
def main():
    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 = coordinate.wrap_crds("nonuniform_cartesian", [('z', z), ('y', y),
                                                         ('x', x)])
    bx = field.empty(crds, name="$B_x$", center="Node")
    by = field.empty(crds, name="$B_y$", center="Node")
    bz = field.empty(crds, name="$B_z$", center="Node")
    fld = field.empty(crds,
                      name="B",
                      nr_comps=3,
                      center="Node",
                      layout="interlaced")
    X, Y, Z = crds.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

    bx[:] = 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)
    by[:] = 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)
    bz[:] = 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)
    fld[..., 0] = bx
    fld[..., 1] = by
    fld[..., 2] = bz

    fig = mlab.figure(size=(1150, 850),
                      bgcolor=(1.0, 1.0, 1.0),
                      fgcolor=(0.0, 0.0, 0.0))
    f1_src = vlab.add_field(bx)
    f2_src = vlab.add_field(by)
    f3_src = vlab.add_field(bz)
    mlab.pipeline.iso_surface(f1_src,
                              contours=[0.0],
                              opacity=1.0,
                              color=(1.0, 0.0, 0.0))
    mlab.pipeline.iso_surface(f2_src,
                              contours=[0.0],
                              opacity=1.0,
                              color=(0.0, 1.0, 0.0))
    mlab.pipeline.iso_surface(f3_src,
                              contours=[0.0],
                              opacity=1.0,
                              color=(0.0, 0.0, 1.0))
    mlab.axes()
    mlab.show()

    nullpt = cycalc.interp_trilin(fld, [(0.5, 0.5, 0.5)])
    print("f(0.5, 0.5, 0.5):", nullpt)

    ax1 = plt.subplot2grid((4, 3), (0, 0))
    all_roots = []
    positive_roots = []
    ix = iy = iz = 0

    for di, d in enumerate([0, -1]):
        #### XY face
        a1 = bx[iz + d, iy, ix]
        b1 = bx[iz + d, iy, ix - 1] - a1
        c1 = bx[iz + d, iy - 1, ix] - a1
        d1 = bx[iz + d, iy - 1, ix - 1] - c1 - b1 - a1

        a2 = by[iz + d, iy, ix]
        b2 = by[iz + d, iy, ix - 1] - a2
        c2 = by[iz + d, iy - 1, ix] - a2
        d2 = by[iz + d, iy - 1, ix - 1] - c2 - b2 - a2

        a3 = bz[iz + d, iy, ix]
        b3 = bz[iz + d, iy, ix - 1] - a3
        c3 = bz[iz + d, iy - 1, ix] - a3
        d3 = bz[iz + d, iy - 1, ix - 1] - c3 - b3 - a3

        roots1, roots2 = find_roots_face(a1, b1, c1, d1, a2, b2, c2, d2)

        # for rt1, rt2 in zip(roots1, roots2):
        #     print("=")
        #     print("fx", a1 + b1 * rt1 + c1 * rt2 + d1 * rt1 * rt2)
        #     print("fy", a2 + b2 * rt1 + c2 * rt2 + d2 * rt1 * rt2)
        #     print("=")

        # find f3 at the root points
        f3 = np.empty_like(roots1)
        markers = [None] * len(f3)
        for i, rt1, rt2 in zip(count(), roots1, roots2):
            f3[i] = a3 + b3 * rt1 + c3 * rt2 + d3 * rt1 * rt2
            all_roots.append((rt1, rt2, d))  # switch order here
            if f3[i] >= 0.0:
                markers[i] = 'k^'
                positive_roots.append((rt1, rt2, d))  # switch order here
            else:
                markers[i] = 'w^'

        # rescale the roots to the original domain
        roots1 = (xh - xl) * roots1 + xl
        roots2 = (yh - yl) * roots2 + yl

        xp = np.linspace(0.0, 1.0, nx)

        # plt.subplot(121)
        plt.subplot2grid((4, 3), (0 + 2 * di, 0), sharex=ax1, sharey=ax1)
        vlt.plot(fld['x'],
                 "z={0}i".format(d),
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(
                     xl, xh, yl, yh))
        y1 = -(a1 + b1 * xp) / (c1 + d1 * xp)
        plt.plot(x, (yh - yl) * y1 + yl, 'k')
        for i, xrt, yrt in zip(count(), roots1, roots2):
            plt.plot(xrt, yrt, markers[i])

        # plt.subplot(122)
        plt.subplot2grid((4, 3), (1 + 2 * di, 0), sharex=ax1, sharey=ax1)
        vlt.plot(fld['y'],
                 "z={0}i".format(d),
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(
                     xl, xh, yl, yh))
        y2 = -(a2 + b2 * xp) / (c2 + d2 * xp)
        plt.plot(x, (yh - yl) * y2 + yl, 'k')
        for xrt, yrt in zip(roots1, roots2):
            plt.plot(xrt, yrt, markers[i])

        #### YZ face
        a1 = bx[iz, iy, ix + d]
        b1 = bx[iz, iy - 1, ix + d] - a1
        c1 = bx[iz - 1, iy, ix + d] - a1
        d1 = bx[iz - 1, iy - 1, ix + d] - c1 - b1 - a1

        a2 = by[iz, iy, ix + d]
        b2 = by[iz, iy - 1, ix + d] - a2
        c2 = by[iz - 1, iy, ix + d] - a2
        d2 = by[iz - 1, iy - 1, ix + d] - c2 - b2 - a2

        a3 = bz[iz, iy, ix + d]
        b3 = bz[iz, iy - 1, ix + d] - a3
        c3 = bz[iz - 1, iy, ix + d] - a3
        d3 = bz[iz - 1, iy - 1, ix + d] - c3 - b3 - a3

        roots1, roots2 = find_roots_face(a1, b1, c1, d1, a2, b2, c2, d2)

        # for rt1, rt2 in zip(roots1, roots2):
        #     print("=")
        #     print("fx", a1 + b1 * rt1 + c1 * rt2 + d1 * rt1 * rt2)
        #     print("fy", a2 + b2 * rt1 + c2 * rt2 + d2 * rt1 * rt2)
        #     print("=")

        # find f3 at the root points
        f3 = np.empty_like(roots1)
        markers = [None] * len(f3)
        for i, rt1, rt2 in zip(count(), roots1, roots2):
            f3[i] = a3 + b3 * rt1 + c3 * rt2 + d3 * rt1 * rt2
            all_roots.append((d, rt1, rt2))  # switch order here
            if f3[i] >= 0.0:
                markers[i] = 'k^'
                positive_roots.append((d, rt1, rt2))  # switch order here
            else:
                markers[i] = 'w^'

        # rescale the roots to the original domain
        roots1 = (yh - yl) * roots1 + yl
        roots2 = (zh - zl) * roots2 + zl

        yp = np.linspace(0.0, 1.0, ny)

        # plt.subplot(121)
        plt.subplot2grid((4, 3), (0 + 2 * di, 1), sharex=ax1, sharey=ax1)
        vlt.plot(fld['x'],
                 "x={0}i".format(d),
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(
                     yl, yh, zl, zh))
        z1 = -(a1 + b1 * yp) / (c1 + d1 * yp)
        plt.plot(y, (zh - zl) * z1 + zl, 'k')
        for i, yrt, zrt in zip(count(), roots1, roots2):
            plt.plot(yrt, zrt, markers[i])

        # plt.subplot(122)
        plt.subplot2grid((4, 3), (1 + 2 * di, 1), sharex=ax1, sharey=ax1)
        vlt.plot(fld['y'],
                 "x={0}i".format(d),
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(
                     yl, yh, zl, zh))
        z1 = -(a2 + b2 * yp) / (c2 + d2 * yp)
        plt.plot(y, (zh - zl) * z1 + zl, 'k')
        for i, yrt, zrt in zip(count(), roots1, roots2):
            plt.plot(yrt, zrt, markers[i])

        #### ZX face
        a1 = bx[iz, iy + d, ix]
        b1 = bx[iz - 1, iy + d, ix] - a1
        c1 = bx[iz, iy + d, ix - 1] - a1
        d1 = bx[iz - 1, iy + d, ix - 1] - c1 - b1 - a1

        a2 = by[iz, iy + d, ix]
        b2 = by[iz - 1, iy + d, ix] - a2
        c2 = by[iz, iy + d, ix - 1] - a2
        d2 = by[iz - 1, iy + d, ix - 1] - c2 - b2 - a2

        a3 = bz[iz, iy + d, ix]
        b3 = bz[iz - 1, iy + d, ix] - a3
        c3 = bz[iz, iy + d, ix - 1] - a3
        d3 = bz[iz - 1, iy + d, ix - 1] - c3 - b3 - a3

        roots1, roots2 = find_roots_face(a1, b1, c1, d1, a2, b2, c2, d2)

        # for rt1, rt2 in zip(roots1, roots2):
        #     print("=")
        #     print("fx", a1 + b1 * rt1 + c1 * rt2 + d1 * rt1 * rt2)
        #     print("fy", a2 + b2 * rt1 + c2 * rt2 + d2 * rt1 * rt2)
        #     print("=")

        # find f3 at the root points
        f3 = np.empty_like(roots1)
        markers = [None] * len(f3)
        for i, rt1, rt2 in zip(count(), roots1, roots2):
            f3[i] = a3 + b3 * rt1 + c3 * rt2 + d3 * rt1 * rt2
            all_roots.append((rt2, d, rt1))  # switch order here
            if f3[i] >= 0.0:
                markers[i] = 'k^'
                positive_roots.append((rt2, d, rt1))  # switch order here
            else:
                markers[i] = 'w^'

        # rescale the roots to the original domain
        roots1 = (zh - zl) * roots1 + zl
        roots2 = (xh - xl) * roots2 + xl

        zp = np.linspace(0.0, 1.0, nz)

        # plt.subplot(121)
        plt.subplot2grid((4, 3), (0 + 2 * di, 2), sharex=ax1, sharey=ax1)
        vlt.plot(fld['x'],
                 "y={0}i".format(d),
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(
                     xl, xh, zl, zh))
        x1 = -(a1 + b1 * zp) / (c1 + d1 * zp)
        plt.plot(z, (xh - xl) * x1 + xl, 'k')
        for i, zrt, xrt in zip(count(), roots1, roots2):
            plt.plot(xrt, zrt, markers[i])

        # plt.subplot(121)
        plt.subplot2grid((4, 3), (1 + 2 * di, 2), sharex=ax1, sharey=ax1)
        vlt.plot(fld['y'],
                 "y={0}i".format(d),
                 plot_opts="x={0}_{1},y={2}_{3},lin_-10_10".format(
                     xl, xh, zl, zh))
        x1 = -(a2 + b2 * zp) / (c2 + d2 * zp)
        plt.plot(z, (xh - xl) * x1 + xl, 'k')
        for i, zrt, xrt in zip(count(), roots1, roots2):
            plt.plot(xrt, zrt, markers[i])

    print("all:", len(all_roots), "positive:", len(positive_roots))
    if len(all_roots) % 2 == 1:
        print("something is fishy, there are an odd number of root points "
              "on the surface of your cube, there is probably a degenerate "
              "line or surface of nulls")
    print("Null Point?", (len(positive_roots) % 2 == 1))

    plt.show()
Ejemplo n.º 7
0
def main():
    parser = argparse.ArgumentParser(description="Streamline a PSC file")
    parser.add_argument("-t", default="2000",
                        help="which time to plot (finds closest)")
    parser.add_argument('infile', nargs=1, help='input file')
    args = vutil.common_argparse(parser)

    # f = readers.load_file("pfd.020000.xdmf")
    # ... or ...
    # using this way of loading files, one probably wants just to give
    # pfd.xdmf to the command line
    f = readers.load_file(args.infile[0])
    f.activate_time(args.t)

    jz = f["jz"]
    # recreate hx as a field of 0 to keep streamlines from moving in
    # that direction
    hx = field.zeros_like(jz, name="hx")
    h1 = field.scalar_fields_to_vector([hx, f["hy"], f["hz"]], name="H",
                                       _force_layout="Interlaced",
                                       forget_source=True)
    e = field.scalar_fields_to_vector([f["ex"], f["ey"], f["ez"]], name="E",
                                      _force_layout="Interlaced",
                                      forget_source=True)

    # plot magnetic fields, just a sanity check
    # ax1 = plt.subplot(211)
    # mpl.plot(f["hy"], flip_plot=True)
    # ax2 = plt.subplot(212, sharex=ax1, sharey=ax1)
    # mpl.plot(f["hz"], flip_plot=True)
    # mpl.mplshow()

    # make a line of 30 seeds straight along the z axis (x, y, z ordered)
    seeds1 = seed.Line((0.0, 0.0, 2.0), (1022.0, 0.0, 0.0), 60)
    # set outer boundary limits for streamlines
    ds = 0.005  # spatial step along the stream line curve
    obound0 = np.array([1, -128, -1000], dtype=h1.dtype)
    obound1 = np.array([1023, 128, 1000], dtype=h1.dtype)
    # calc the streamlines
    lines1, topo1 = streamline.streamlines(h1, seeds1, ds0=ds, maxit=200000,
                                           obound0=obound0, obound1=obound1,
                                           ibound=0.0)
    # run with -v to see this
    logger.info("Topology flags: {0}".format(topo1))

    # rotate plot puts the z axis along the horizontal
    flip_plot = True
    mpl.plot(jz, flip_plot=flip_plot, plot_opts="lin_-.05_.05")
    # mpl.plot_streamlines2d(lines1, "x", flip_plot=flip_plot, color='k')
    plt.xlim([0, 1024])
    plt.ylim([-128, 128])
    plt.show()

    # interpolate e onto each point of the first field line of lines1
    e1 = cycalc.interp_trilin(e, seed.Point(lines1[0]))
    print(e1.shape, lines1[0].shape)
    plt.clf()
    plt.plot(np.linspace(0, ds * e1.shape[0], e1.shape[0]), e1[:, 0])
    plt.xlabel("length along field line")
    plt.ylabel("Ex")
    plt.show()

    return 0