Ejemplo n.º 1
0
    def __init__(self, knots, s=4, name=NN):
        '''New L{HeightSmoothBiSpline} interpolator.

           @arg knots: The points with known height (C{LatLon}s).
           @kwarg s: The spline smoothing factor (C{4}).
           @kwarg name: Optional name for this height interpolator (C{str}).

           @raise HeightError: Insufficient number of B{C{knots}} or
                               an invalid B{C{knot}} or B{C{s}}.

           @raise ImportError: Package C{numpy} or C{scipy} not found
                               or not installed.

           @raise SciPyError: A C{SmoothSphereBivariateSpline} issue.

           @raise SciPyWarning: A C{SmoothSphereBivariateSpline} warning
                                as exception.
        '''
        _, spi = self._NumSciPy()

        s = Int_(s, name='smoothing', Error=HeightError, low=4)

        xs, ys, hs = self._xyhs3(knots)
        try:
            self._ev = spi.SmoothSphereBivariateSpline(ys,
                                                       xs,
                                                       hs,
                                                       eps=EPS,
                                                       s=s).ev
        except Exception as x:
            raise _SciPyIssue(x)

        if name:
            self.name = name
Ejemplo n.º 2
0
    def __init__(self, knots, s=4, name=''):
        '''New L{HeightSmoothBiSpline} interpolator.

           @param knots: The points with known height (C{LatLon}s).
           @keyword s: The spline smoothing factor (C{4}).
           @keyword name: Optional height interpolator name (C{str}).

           @raise HeightError: Insufficient number of B{C{knots}} or
                               invalid B{C{knot}} or B{C{s}}.

           @raise ImportError: Package C{numpy} or C{scipy} not found
                               or not installed.

           @raise SciPyError: A C{SmoothSphereBivariateSpline} issue.

           @raise SciPyWarning: A C{SmoothSphereBivariateSpline} warning
                                as exception.
        '''
        _, spi = self._NumSciPy()

        if s < 4:
            raise HeightError('%s too small: %s' % ('smoothing', s))

        xs, ys, hs = self._xyhs3(knots)
        try:
            self._ev = spi.SmoothSphereBivariateSpline(ys, xs, hs,
                                                       eps=EPS, s=s).ev
        except Exception as x:
            raise _SciPyIssue(x)

        if name:
            self.name = name
Ejemplo n.º 3
0
def test_interpolation(mesh):
    from scipy import interpolate

    lons, lats = mesh.lons, mesh.lats
    Z = np.exp(-lons**2 - lats**2)
    lon = 2.*np.pi*np.random.random(10)
    lat = np.arccos(2.*np.random.random(10) - 1.) - np.pi/2

    # Stripy
    zn1 = mesh.interpolate_nearest(lon, lat, Z)
    zl1 = mesh.interpolate_linear(lon, lat, Z)
    zc1 = mesh.interpolate_cubic(lon, lat, Z)

    # cKDTree
    tree = interpolate.NearestNDInterpolator((lons,lats), Z)
    zn2 = tree(lon, lat)

    # Least-squares spline
    tri = interpolate.LinearNDInterpolator((lons,lats), Z)
    zl2 = tri((lon, lat))


    # Cubic spline
    spl = interpolate.SmoothSphereBivariateSpline(lats+np.pi/2, lons, Z, s=1)
    zc2 = spl.ev(lat+np.pi/2,lon)

    print("squared residual in interpolation\n  \
     - nearest neighbour = {}\n  \
     - linear = {}\n  \
     - cubic  = {}".format(((zn1 - zn2)**2).max(), \
                           ((zl1 - zl2)**2).max(), \
                           ((zc1 - zc2)**2).max()))
Ejemplo n.º 4
0
def test_derivative(mesh):
    from scipy import interpolate

    # Create a field to test derivatives
    lons, lats = mesh.lons, mesh.lats + np.pi/2
    Z = np.exp(-lons**2 - lats**2)
    Zlons = -2*lons*Z
    Zlats = -2*lats*Z
    gradZ = np.hypot(Zlons, Zlats)

    # Stripy
    t = clock()
    Zx, Zy, Zz = mesh.gradient(Z, nit=10, tol=1e-10)
    t1 = clock() - t
    Zlons1, Zlats1 = mesh.transform_to_spherical(Zx, Zy, Zz)
    gradZ1 = np.hypot(Zlons1, Zlats1)

    # Spline
    spl = interpolate.SmoothSphereBivariateSpline(lats, lons, Z, s=1)
    t = clock()
    Zlons2 = spl.ev(lats, lons, dtheta=1)
    Zlats2 = spl.ev(lats, lons, dphi=1)
    t2 = clock() - t
    gradZ2 = np.hypot(Zlons2, Zlats2)

    res1 = ((gradZ1 - gradZ)**2).max()
    res2 = ((gradZ2 - gradZ)**2).max()
    print("squared error in first derivative\n  \
     - stripy = {} took {}s\n  \
     - spline = {} took {}s".format(res1, t1, res2, t2))
Ejemplo n.º 5
0
def sheet_from_cell_centers(points, noise=0, interp_s=1e-4):
    """Returns a Sheet object from the Voronoï tessalation
    of the cell centers.

    The strategy is to project the points on a sphere, get the Voronoï
    tessalation on this sphere and reproject the vertices on the
    original (implicit) surface through linear interpolation of the cell centers.

    Works for relatively smooth surfaces (at the very minimum star convex).

    Parameters
    ----------

    points : np.ndarray of shape (Nf, 3)
        the x, y, z coordinates of the cell centers
    noise : float, default 0.0
        addiditve normal noise stdev
    interp_s : float, default 1e-4
        interpolation smoothing factor (might need to set higher)

    Returns
    -------
    sheet : a :class:`Sheet` object with Nf faces


    """
    points = points.copy()
    if noise:
        points += np.random.normal(0, scale=noise, size=points.shape)
    points -= points.mean(axis=0)
    bbox = np.ptp(points, axis=0)
    points /= bbox

    rhos = np.linalg.norm(points, axis=1)
    thetas = np.arcsin(points[:, 2] / rhos)
    phis = np.arctan2(points[:, 0], points[:, 1])

    sphere_rad = rhos.max() * 1.1

    points_sphere = np.vstack(
        (
            sphere_rad * np.cos(thetas) * np.cos(phis),
            sphere_rad * np.cos(thetas) * np.sin(phis),
            sphere_rad * np.sin(thetas),
        )
    ).T
    points_sphere = np.concatenate(([[0, 0, 0]], points_sphere))

    vor3D = Voronoi(points_sphere)

    dsets = from_3d_voronoi(vor3D)
    eptm_ = Epithelium("v", dsets)

    eptm_ = single_cell(eptm_, 0)

    eptm = get_outer_sheet(eptm_)
    eptm.reset_index()
    eptm.reset_topo()
    eptm.vert_df["rho"] = np.linalg.norm(eptm.vert_df[eptm.coords], axis=1)
    mean_rho = eptm.vert_df["rho"].mean()

    SheetGeometry.scale(eptm, sphere_rad / mean_rho, ["x", "y", "z"])
    SheetGeometry.update_all(eptm)

    eptm.face_df["phi"] = np.arctan2(eptm.face_df.y, eptm.face_df.x)
    eptm.face_df["rho"] = np.linalg.norm(eptm.face_df[["x", "y", "z"]], axis=1)
    eptm.face_df["theta"] = np.arcsin(eptm.face_df.z / eptm.face_df["rho"])
    _itrp = interpolate.SmoothSphereBivariateSpline(
        thetas + np.pi / 2, phis + np.pi, rhos, s=interp_s
    )
    eptm.face_df["rho"] = _itrp(
        eptm.face_df["theta"] + np.pi / 2, eptm.face_df["phi"] + np.pi, grid=False
    )
    eptm.face_df["x"] = eptm.face_df.eval("rho * cos(theta) * cos(phi)")
    eptm.face_df["y"] = eptm.face_df.eval("rho * cos(theta) * sin(phi)")
    eptm.face_df["z"] = eptm.face_df.eval("rho * sin(theta)")

    eptm.edge_df[["fx", "fy", "fz"]] = eptm.upcast_face(eptm.face_df[["x", "y", "z"]])
    eptm.vert_df[["x", "y", "z"]] = eptm.edge_df.groupby("srce")[
        ["fx", "fy", "fz"]
    ].mean()
    for i, c in enumerate("xyz"):
        eptm.vert_df[c] *= bbox[i]

    SheetGeometry.update_all(eptm)

    eptm.sanitize(trim_borders=True)

    eptm.reset_index()
    eptm.reset_topo()
    SheetGeometry.update_all(eptm)
    null_length = eptm.edge_df.query("length == 0")

    while null_length.shape[0]:
        type1_transition(eptm, null_length.index[0])
        SheetGeometry.update_all(eptm)
        null_length = eptm.edge_df.query("length == 0")

    return eptm