Example #1
0
def interpolate_onto_grid(xy_vec, rasters, mx, my):
    # Do the interpolation.
    lndi, nndi = None, None
    new_rasters = []
    for raster in rasters:
        if lndi is None:
            lndi = LinearNDInterpolator(xy_vec, raster)
            nndi = NearestNDInterpolator(xy_vec, raster)
        else:
            lndi = LinearNDInterpolator(lndi.tri, raster)
            nndi.values = raster
        new_raster = lndi(mx, my)
        new_raster[np.isnan(new_raster)] = nndi(mx[np.isnan(new_raster)],
                                                my[np.isnan(new_raster)])
        new_rasters.append(new_raster)
    return new_rasters
Example #2
0
def interpolate_xarray_linear(xpoints,
                              ypoints,
                              values,
                              shape,
                              chunks=CHUNK_SIZE):
    """Interpolate linearly, generating a dask array."""
    from scipy.interpolate.interpnd import (LinearNDInterpolator,
                                            _ndim_coords_from_arrays)

    if isinstance(chunks, (list, tuple)):
        vchunks, hchunks = chunks
    else:
        vchunks, hchunks = chunks, chunks

    points = _ndim_coords_from_arrays(
        np.vstack((np.asarray(ypoints), np.asarray(xpoints))).T)

    interpolator = LinearNDInterpolator(points, values)

    grid_x, grid_y = da.meshgrid(da.arange(shape[1], chunks=hchunks),
                                 da.arange(shape[0], chunks=vchunks))

    # workaround for non-thread-safe first call of the interpolator:
    interpolator((0, 0))
    res = da.map_blocks(intp, grid_x, grid_y, interpolator=interpolator)

    return DataArray(res, dims=('y', 'x'))
def interp_disp(disp):
    # Based on monodepth/utils/evaluation_utils.py
    J, I = np.meshgrid(np.arange(disp.shape[1]), np.arange(disp.shape[0]))
    IJ = np.vstack([I.flatten(), J.flatten()]).T
    d = disp[IJ[:, 0], IJ[:, 1]]
    ij = IJ[d != 0, :]
    d = d[d != 0]
    intp = LinearNDInterpolator(ij, d, fill_value=0.)
    disp_i = intp(IJ).reshape(disp.shape)
    return disp_i
def get_environment_func(seconds, current_df):
    # Создадим функцию интерполяции данных
    day = 1 + floor(seconds / 86400)
    if day > CACHE_INTERPOLATOR['last_day']:
        logger.info('Интерполируем течения')
        day_mask = current_df['time'] == day
        xyz = np.array(current_df.loc[day_mask, ['x', 'y', 'depth']])
        current_velocity = np.array(current_df.loc[day_mask, ['uo', 'vo']])
        interpolator = LinearNDInterpolator(xyz, current_velocity)
        CACHE_INTERPOLATOR['last_interpolator'] = interpolator
        CACHE_INTERPOLATOR['last_day'] = day
    else:
        interpolator = CACHE_INTERPOLATOR['last_interpolator']
    return interpolator
Example #5
0
    def execute(self):
        foundation_func = LinearNDInterpolator(self.depth[:, 0:2],
                                               self.depth[:, 2])
        self.foundations = array([
            foundation_func(self.wt_positions[i, 0], self.wt_positions[i, 1])
            for i in range(self.wt_positions.shape[0])
        ])
        #dist = DistFromBorders()(wt_positions=self.wt_positions, borders=self.borders).dist
        min_depth = self.depth[:, 2].min()
        self.foundations[isnan(self.foundations)] = min_depth

        if self.scaling == 0.0:
            # Using the baseline for scaling
            self.scaling = sum(self.foundations)

        self.foundation_length = sum(self.foundations) / self.scaling
Example #6
0
def griddata(points, values, xi, method='linear', fill_value=np.nan, tol=1e-6):
    """modified griddata plus tol arg"""
    points = _ndim_coords_from_arrays(points)

    if points.ndim < 2:
        ndim = points.ndim
    else:
        ndim = points.shape[-1]

    if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
        from interpolate import interp1d
        points = points.ravel()
        if isinstance(xi, tuple):
            if len(xi) != 1:
                raise ValueError("invalid number of dimensions in xi")
            xi, = xi
        # Sort points/values together, necessary as input for interp1d
        idx = np.argsort(points)
        points = points[idx]
        values = values[idx]
        ip = interp1d(points,
                      values,
                      kind=method,
                      axis=0,
                      bounds_error=False,
                      fill_value=fill_value)
        return ip(xi)
    elif method == 'nearest':
        ip = NearestNDInterpolator(points, values)
        return ip(xi)
    elif method == 'linear':
        ip = LinearNDInterpolator(points, values, fill_value=fill_value)
        return ip(xi)
    elif method == 'cubic' and ndim == 2:
        ip = CloughTocher2DInterpolator(points,
                                        values,
                                        fill_value=fill_value,
                                        tol=tol)
        return ip(xi)
    else:
        raise ValueError("Unknown interpolation method %r for "
                         "%d dimensional data" % (method, ndim))
Example #7
0
def grid_interpolate_deconstructed(tri, values, grid_points, method='linear'):
    """
    Underlying methods from scipy grid_data broken out to pass in the tri
    values returned from qhull.Delaunay. This is done to improve the speed
    of using grid_data

    Args:
        tri:            values returned from qhull.Delaunay
        values:         values at HRRR stations generally
        grid_points:    tuple of vectors for X,Y coords of grid stations
        method:         either linear or cubic

    Returns:
        result of interpolation to gridded points
    """

    if method == 'cubic':
        return CloughTocher2DInterpolator(tri, values)(grid_points)
    elif method == 'linear':
        return LinearNDInterpolator(tri, values)(grid_points)
Example #8
0
 def _linear(self, dist, ix, n_interp, xi):
     return LinearNDInterpolator(self.points[ix],
                                 self.values[ix])(np.array([xi[n_interp]]))