예제 #1
0
파일: affine.py 프로젝트: dcs4cop/xcube
def affine_transform_dataset(
        dataset: xr.Dataset,
        source_gm: GridMapping,
        target_gm: GridMapping,
        var_configs: Mapping[Hashable, Mapping[str, Any]] = None
) -> xr.Dataset:
    """
    Resample dataset according to an affine transformation.

    :param dataset: The source dataset
    :param source_gm: Source grid mapping of *dataset*.
        Must be regular. Must have same CRS as *target_gm*.
    :param target_gm: Target grid mapping.
        Must be regular. Must have same CRS as *source_gm*.
    :param var_configs: Optional resampling configurations
        for individual variables.
    :return: The resampled target dataset.
    """
    if source_gm.crs != target_gm.crs:
        raise ValueError(f'CRS of source_gm and target_gm must be equal,'
                         f' was "{source_gm.crs.name}"'
                         f' and "{target_gm.crs.name}"')
    GridMapping.assert_regular(source_gm, name='source_gm')
    GridMapping.assert_regular(target_gm, name='target_gm')
    resampled_dataset = resample_dataset(
        dataset=dataset,
        matrix=target_gm.ij_transform_to(source_gm),
        size=target_gm.size,
        tile_size=target_gm.tile_size,
        xy_dim_names=source_gm.xy_dim_names,
        var_configs=var_configs
    )
    has_bounds = any(dataset[var_name].attrs.get('bounds')
                     for var_name in source_gm.xy_var_names)
    new_coords = target_gm.to_coords(
        xy_var_names=source_gm.xy_var_names,
        xy_dim_names=source_gm.xy_dim_names,
        exclude_bounds=not has_bounds
    )
    return resampled_dataset.assign_coords(new_coords)
예제 #2
0
파일: rectify.py 프로젝트: dcs4cop/xcube
def rectify_dataset(source_ds: xr.Dataset,
                    *,
                    var_names: Union[str, Sequence[str]] = None,
                    source_gm: GridMapping = None,
                    xy_var_names: Tuple[str, str] = None,
                    target_gm: GridMapping = None,
                    tile_size: Union[int, Tuple[int, int]] = None,
                    is_j_axis_up: bool = None,
                    output_ij_names: Tuple[str, str] = None,
                    compute_subset: bool = True,
                    uv_delta: float = 1e-3) -> Optional[xr.Dataset]:
    """
    Reproject dataset *source_ds* using its per-pixel
    x,y coordinates or the given *source_gm*.

    The function expects *source_ds* or the given
    *source_gm* to have either one- or two-dimensional
    coordinate variables that provide spatial x,y coordinates
    for every data variable with the same spatial dimensions.

    For example, a dataset may comprise variables with
    spatial dimensions ``var(..., y_dim, x_dim)``,
    then one the function expects coordinates to be provided
    in two forms:

    1. One-dimensional ``x_var(x_dim)``
       and ``y_var(y_dim)`` (coordinate) variables.
    2. Two-dimensional ``x_var(y_dim, x_dim)``
       and ``y_var(y_dim, x_dim)`` (coordinate) variables.

    If *target_gm* is given and it defines a tile size
    or *tile_size* is given, and the number of tiles is
    greater than one in the output's x- or y-direction, then the
    returned dataset will be composed of lazy, chunked dask
    arrays. Otherwise the returned dataset will be composed
    of ordinary numpy arrays.

    :param source_ds: Source dataset grid mapping.
    :param var_names: Optional variable name or sequence of
        variable names.
    :param source_gm: Target dataset grid mapping.
    :param xy_var_names: Optional tuple of the x- and y-coordinate
        variables in *source_ds*. Ignored if *source_gm* is given.
    :param target_gm: Optional output geometry. If not given,
        output geometry will be computed to spatially fit *dataset*
        and to retain its spatial resolution.
    :param tile_size: Optional tile size for the output.
    :param is_j_axis_up: Whether y coordinates are increasing with
        positive image j axis.
    :param output_ij_names: If given, a tuple of variable names in
        which to store the computed source pixel coordinates in
        the returned output.
    :param compute_subset: Whether to compute a spatial subset
        from *dataset* using *output_geom*. If set, the function
        may return ``None`` in case there is no overlap.
    :param uv_delta: A normalized value that is used to determine
        whether x,y coordinates in the output are contained
        in the triangles defined by the input x,y coordinates.
        The higher this value, the more inaccurate the rectification
        will be.
    :return: a reprojected dataset, or None if the requested output
        does not intersect with *dataset*.
    """
    if source_gm is None:
        source_gm = GridMapping.from_dataset(source_ds,
                                             xy_var_names=xy_var_names)

    src_attrs = dict(source_ds.attrs)

    if target_gm is None:
        target_gm = source_gm.to_regular(tile_size=tile_size)
    elif compute_subset:
        source_ds_subset = select_spatial_subset(
            source_ds,
            xy_bbox=target_gm.xy_bbox,
            ij_border=1,
            xy_border=0.5 * (target_gm.x_res + target_gm.y_res),
            grid_mapping=source_gm)
        if source_ds_subset is None:
            return None
        if source_ds_subset is not source_ds:
            # TODO: GridMapping.from_dataset() may be expensive.
            #   Find a more effective way.
            source_gm = GridMapping.from_dataset(source_ds_subset)
            source_ds = source_ds_subset

    # if src_geo_coding.xy_var_names != output_geom.xy_var_names:
    #     output_geom = output_geom.derive(
    #           xy_var_names=src_geo_coding.xy_var_names
    #     )
    # if src_geo_coding.xy_dim_names != output_geom.xy_dim_names:
    #     output_geom = output_geom.derive(
    #           xy_dim_names=src_geo_coding.xy_dim_names
    #     )

    if tile_size is not None or is_j_axis_up is not None:
        target_gm = target_gm.derive(tile_size=tile_size,
                                     is_j_axis_up=is_j_axis_up)

    src_vars = _select_variables(source_ds, source_gm, var_names)

    if target_gm.is_tiled:
        compute_dst_src_ij_images = _compute_ij_images_xarray_dask
        compute_dst_var_image = _compute_var_image_xarray_dask
    else:
        compute_dst_src_ij_images = _compute_ij_images_xarray_numpy
        compute_dst_var_image = _compute_var_image_xarray_numpy

    dst_src_ij_array = compute_dst_src_ij_images(source_gm, target_gm,
                                                 uv_delta)

    dst_x_dim, dst_y_dim = target_gm.xy_dim_names
    dst_dims = dst_y_dim, dst_x_dim
    dst_ds_coords = target_gm.to_coords()
    dst_vars = dict()
    for src_var_name, src_var in src_vars.items():
        dst_var_dims = src_var.dims[0:-2] + dst_dims
        dst_var_coords = {
            d: src_var.coords[d]
            for d in dst_var_dims if d in src_var.coords
        }
        dst_var_coords.update(
            {d: dst_ds_coords[d]
             for d in dst_var_dims if d in dst_ds_coords})
        dst_var_array = compute_dst_var_image(src_var,
                                              dst_src_ij_array,
                                              fill_value=np.nan)
        dst_var = xr.DataArray(dst_var_array,
                               dims=dst_var_dims,
                               coords=dst_var_coords,
                               attrs=src_var.attrs)
        dst_vars[src_var_name] = dst_var

    if output_ij_names:
        output_i_name, output_j_name = output_ij_names
        dst_ij_coords = {
            d: dst_ds_coords[d]
            for d in dst_dims if d in dst_ds_coords
        }
        dst_vars[output_i_name] = xr.DataArray(dst_src_ij_array[0],
                                               dims=dst_dims,
                                               coords=dst_ij_coords)
        dst_vars[output_j_name] = xr.DataArray(dst_src_ij_array[1],
                                               dims=dst_dims,
                                               coords=dst_ij_coords)

    return xr.Dataset(dst_vars, coords=dst_ds_coords, attrs=src_attrs)