tile

gridkit.tile.get_value_dtype(value)[source]
class gridkit.tile.Tile(grid: BaseGrid, start_id: Tuple[int, int] | GridIndex, nx: int, ny: int)[source]

Bases: object

A Tile describes a set of cells defined by the start_id, which is the cell that defines the bottom-left corner of the tile, and nx and ny, which are the number of cells in the x and y directions, respectively.

Each tile is associated with a particular grid and the Tile refers to a selection of grid indices on that grid. The associated grid can be accessed using the .grid property.

Note

nx and ny can be seen as ‘right’ and ‘up’, respectively, when the rotation of the grid is zero. If the grid is rotated, the tile rotates with it (naturally). This means that for a grid that is rotated 90 degrees, nx refers to the number of cells up, and ny refers to the number of cells to the left.

Init parameters

grid: BaseGrid

The TriGrid, RectGrid or HexGrid the tile is associated with

start_id: Union[Tuple[int, int], GridIndex]

The starting cell of the Tile. The starting cell defines the bottom-left corner of the Tile if the associated grid is not rotated.

nx: int

The number of cells in x direction, starting from the start_id

ny: int

The number of cells in y direction, starting from the start_id

static from_pyo3_tile(grid, pyo3_tile)[source]
to_data_tile(data, nodata_value=None)[source]
to_data_tile_with_value(fill_value, nodata_value=None)[source]
property start_id

The starting cell of the Tile. The starting cell defines the bottom-left corner of the Tile if the associated grid is not rotated.

property nx

The number of cells in x direction, starting from the start_id

property ny

The number of cells in y direction, starting from the start_id

corner_ids()[source]

The ids at the corners of the Tile

Returns:

The GridIndex that contains the ids of the cells at the corners of the Tile in order: top-left, top-right, bottom-right, bottom-left (assuming the assicaited grid is not rotated)

Return type:

GridIndex

corners()[source]

The coordinates at the corners of the Tile in order: top-left, top-right, bottom-right, bottom-left (assuming the assicaited grid is not rotated)

Returns:

A two-dimensional array that contais the x and y coordinates of the corners

Return type:

numpy.ndarray

property indices

The ids of all cells in the Tile.

Returns:

The GridIndex that contains the indices in the Tile

Return type:

GridIndex

property mpl_extent: tuple

Raster Bounds

Returns:

The extent of the data as defined expected by matplotlib in (left, right, bottom, top) or equivalently (min-x, max-x, min-y, max-y)

Return type:

tuple

intersects(other)[source]

Only checks bounds, not grid type, alignment etc.

centroid(index=None)[source]
overlap(other)[source]
to_shapely(index=None, as_multipolygon=None)[source]

Refer to parent method BaseGrid.to_shapely()

Difference with parent method:

index is optional. If index is None (default) the cells containing data are used as the index argument.

tile_id_to_grid_id(tile_id=None, oob_value=9223372036854775807)[source]

Convert the index referring to a cell from the tile reference frame to that of the grid. The tile id follows the numpy convention and is in the form [[y0, y1, y2], [x0, x1, x2]]. The grid id is int the form [(x0, y0), (x1,y1), (x2, y2)]. The tile id will start at the top-left at [0,0]. The grid id starts at the bottom left, but depending on where in the world the tile is placed it can have any starting value.

Parameters:
  • tile_id (Tuple) – The tile index in the format: ((y0, y1, y2), (x0, x1, x2)). If None, return a GridIndex that includes all cells in the tile.

  • oob_value (int) – The value to assign to indices not in the tile. Default: maximum numpy.in64 value.

Returns:

The index referring to the same cell but in grid coordinates instead of tile coordinates

Return type:

GridIndex

Examples

Let’s first start by creating a data_tile that we can sample using either grid ids or tile ids.

>>> import numpy
>>> from gridkit import RectGrid, Tile
>>> grid = RectGrid(size=5)
>>> nx = ny = 4
>>> tile = Tile(grid, start_id=(2,3), nx=nx, ny=ny)
>>> data = numpy.arange(ny*nx).reshape(ny,nx) # Note that numpy indexes in the form (y,x)
>>> data_tile = tile.to_data_tile(data=data)
>>> print(data_tile.to_numpy())
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
>>> tile_ids = ((1,2,3), (2,1,0))
>>> grid_ids = data_tile.tile_id_to_grid_id(tile_ids)
>>> print(grid_ids.index)
[[4 5]
 [3 4]
 [2 3]]

Note the differnce in value due to the tile’s start_id of (2,3), as well as the difference in array shape.

The method tile_id_to_grid_id exists on both Tile and DataTile objects. The tile and data_tile here are at the same location on the grid, the difference is just that the data_tile has data. Doing the id conversion should yield the same result in both cases.

The value obtained from data_tile.value using the grid_id should be the same as obtaining the value from data_tile.to_numpy() using the tile_ids. You can shorthand this by just indexing directly on the data_tile.

>>> assert grid_ids == tile.tile_id_to_grid_id(tile_ids)
>>> print(data_tile[tile_ids])
[ 6  9 12]
>>> print(data_tile.value(grid_ids))
[ 6  9 12]

We should of course be able to get the tile_ids back using Tile.grid_id_to_tile_id():

>>> reverted_tile_ids = tile.grid_id_to_tile_id(grid_ids)
>>> print(reverted_tile_ids)
(array([1, 2, 3]), array([2, 1, 0]))
>>> numpy.testing.assert_allclose(tile_ids, reverted_tile_ids)

# We get a tuple of numpy arrays back instead of a tuple of tuples, # but numerically they are the same as the tuple we started with. # Tile.grid_id_to_tile_id() always returns a tuple of arrays but # Tile.tile_id_to_grid_id() accepts a tuple of lists, tuple of tuples or tuple of arrays.

grid_id_to_tile_id(index=None, oob_value=9223372036854775807)[source]

Convert the index referring to a cell from the grid reference frame to that of the tile. The tile id follows the numpy convention and is in the form [[y0, y1, y2], [x0, x1, x2]]. The grid id is int the form [(x0, y0), (x1,y1), (x2, y2)]. The tile id will start at the top-left at [0,0]. The grid id starts at the bottom left, but depending on where in the world the tile is placed it can have any starting value.

Parameters:
  • index (GridIndex) – The grid index in the form [(x0, y0), (x1,y1), (x2, y2)]. If None, return the tile indices for each cell. Note that they are in raveled form.

  • oob_value (int) – The value to assign to indices not in the tile. Default: maximum numpy.in64 value.

Returns:

The index referring to the same cell but in tile coordinates instead of tile coordinates

Return type:

GridIndex

Examples

For an elaborate example showing going from tile_id to grid_id and back, see Tile.tile_id_to_grid_id()

class gridkit.tile.DataTile(tile: Tile, data: ndarray, nodata_value=None)[source]

Bases: Tile

from_bounds_as_rect(bounds=None, nodata_value=None)[source]

Create a DataTile given a 2D numpy array on a rectangular grid. The location of the data is defined by the bounds paramter. The grid attributes such as the cell size are infered from the restrictions created by the dimensions of the data and the space available in the bounds.

This approach assumes the bounding box, and by extension the created DataTile, is not rotated.

Parameters:
  • data (class:numpy.ndarray) – A 2D array with the data for the DataTile

  • bounds (tuple(minx, miny, maxx, maxy)) – The bounding box describing the location of the edges of the data in (minx, miny, maxx, maxy). If None, the dimensions of the data array will be used, resulting in a dx and dy of 1 and the lower left corner of the Tile at the origin: (0,0).

  • nodata_value – A cell with this value is considered to be empty. If None, a default will be chosen based on the dtype of the data array.

Returns:

class – A DataTile containing the suplied data

Return type:

.DataTile

classmethod from_interpolated_points(grid, points, values, method='linear', nodata_value=nan)[source]

Create a DataTile based on the supplied grid that encapsulates the supplied points and assignes values to cells based on interpolated values. The size and location of the Tile are determined by the extent of the supplied points.

Note

This function is significantly slower than DataTile.interpolate()

Parameters:
  • grid (class:.BaseGrid) – The grid on which to interpolate the data

  • points (numpy.ndarray) – A 2d numpy array containing the points in the form [[x1,y1], [x2,y2]]

  • values (numpy.ndarray) – The values corresponding to the supplied points, used as input for interpolation

  • method (str) – The interpolation method to be used. Options are (“nearest”, “linear”, “cubic”). Default: “linear”.

Returns:

A DataTile based on the supplied grid where the data is interpolated between the supplied points.

Return type:

DataTile

property dtype
astype(dtype, nodata_value=None)[source]
property nodata_value
is_nodata(values)[source]
property nodata_cells
static from_pyo3_data_tile(grid, pyo3_data_tile)[source]
to_numpy()[source]
update(data=None, grid=None, start_id=None, nx=None, ny=None, nodata_value=None)[source]
get_tile()[source]

A Tile object with the same properties as this DataTile, but without the data attached.

corner_ids()[source]

The ids at the corners of the Tile

Returns:

The GridIndex that contains the ids of the cells at the corners of the Tile in order: top-left, top-right, bottom-right, bottom-left (assuming the assicaited grid is not rotated)

Return type:

GridIndex

crop(crop_tile)[source]
value(index=None, oob_value=None)[source]
intersects(other)[source]

Only checks bounds, not grid type, alignment etc.

interpolate(sample_points, method: Literal['nearest', 'bilinear', 'inverse_distance'] = 'nearest', **interp_kwargs)[source]

Interpolate the value at the location of sample_points.

Points that are outside of the bounds of the tile are assigned self.nodata_value, or ‘NaN’ if no nodata value is set.

Parameters:
  • sample_points (numpy.ndarray) – The coordinates of the points at which to sample the data

  • method (str, ‘nearest’, ‘bilinear’, optional) – The interpolation method used to determine the value at the supplied sample_points. Supported methods: - “nearest”, for nearest neigbour interpolation, effectively sampling the value of the data cell containing the point - “bilinear”, linear interpolation using the four cells surrounding the point - “inverse_distance”, weighted inverse distance using the 4,3,6 nearby cells surrounding the point for Rect, Hex and Rect grid respectively. Default: “nearest”

  • **interp_kwargs (dict) – The keyword argument passed to the interpolation function corresponding to the specified method

Returns:

The interpolated values at the supplied points

Return type:

numpy.ndarray

resample(alignment_grid, method='nearest', **interp_kwargs)[source]

Resample the grid onto another grid. This will take the locations of the grid cells of the other grid (here called alignment_grid) and determine the value on these location based on the values of the original grid (self).

The steps are as follows:
  1. Transform the bounds of the original data to the CRS of the alignment grid (if not already the same) No transformation is done if any of the grids has no CRS set.

  2. Find the cells of the alignment grid within these transformed bounds

  3. Find the cells of the original grid that are nearby each of the centroids of the cells found in 2. How many nearby cells are selected depends on the selected method

  4. Interpolate the values using the supplied method at each of the centroids of the alignment grid cells selected in 2.

  5. Create a new bounded grid using the attributes of the alignment grid

Parameters:
  • alignment_grid (BaseGrid) –

    The grid with the desired attributes on which to resample. For the new data tile with the interpolated values, a tile extent will be chosen that closely matches the tile with the original data. If a Tile is provided, this step is skipped and the data is interpolated onto the cells of the tile as provided.

    Tip

    If the two grids don’t align very well, you can play with the offset of the alignment grid to try to make it match the orignal grid a bit better. You could for example anchor a cell corner of the alignment grid to the corner of the tile like so: my_data_tile.resample(my_grid.anchor(my_data_tile.corners()[0], cell_element="corner"))

  • method (str, ‘nearest’, ‘bilinear’, ‘inverse_distance’, optional) – The interpolation method used to determine the value at the supplied sample_points. Supported methods: - “nearest”, for nearest neigbour interpolation, effectively sampling the value of the data cell containing the point - “bilinear”, linear interpolation using the 4,3,6 nearby cells surrounding the point for Rect, Hex and Rect grid respectively. - “inverse_distance”, weighted inverse distance using the 4,3,6 nearby cells surrounding the point for Rect, Hex and Rect grid respectively. Default: “nearest”

  • **interp_kwargs (dict) – The keyword argument passed to the interpolation function corresponding to the specified method

Returns:

The interpolated values at the supplied points

Return type:

BoundedGrid

to_crs(crs, resample_method='nearest')[source]

Transforms the Coordinate Reference System (CRS) from the current CRS to the desired CRS. This will modify the cell size and the bounds accordingly.

The crs attribute on the current grid must be set.

Parameters:
  • crs (Union[int, str, pyproj.CRS]) – The value can be anything accepted by pyproj.CRS.from_user_input(), such as an epsg integer (eg 4326), an authority string (eg “EPSG:4326”) or a WKT string.

  • resample_method (str) – The resampling method to be used for DataTile.resample().

Returns:

A copy of the grid with modified cell spacing and bounds to match the specified CRS

Return type:

BoundedRectGrid

max()[source]

Get the maximum value in the data tile, disregarding the nodata_value.

min()[source]

Get the maximum value in the data tile, disregarding the nodata_value.

mean()[source]

Get the maximum value in the data tile, disregarding the nodata_value.

sum()[source]

Get the sum of all values in the data tile, disregarding the nodata_value.

median()[source]

Get the median value of the data tile, disregarding the nodata_value.

percentile(percentile)[source]

Get the percentile of the data tile at the specified value, disregarding the nodata_value.

std()[source]

Get the standard deviation of the data in the tile, disregarding the nodata_value.

gridkit.tile.combine_tiles(tiles)[source]

Create a tile that covers all supplied tiles.

Parameters:

tiles (List[Tile]) – A list of tiles around which the combined tile will be created.

Returns:

A Tile that covers the supplied Tiles

Return type:

Tile

gridkit.tile.count_tiles(tiles)[source]

Count how many times a cell occurs in a tile for the list of tiles provided. Regions where many tiles overlap will have a high count, regions where few tiles overlap will have low count.

Parameters:

tiles (List[Tile] or List[DataTile]) – The tiles from which the overlap count will be determined. For each Tile that is supplied in the list, all cells in the tile contribute to the count. For each DataTile that is supplied in the list, the cells with a value equal to the nodata_value of the DataTile are ignored for the count.

Returns:

A data tile where each value indicates by how many tiles this cell was covered.

Return type:

DataTile

gridkit.tile.sum_data_tiles(data_tiles: List)[source]

Add the DataTiles in the data_tiles list. Nodata_values will be ignored. Each cell will then contain the sum of the value that cell accross the supplied DataTiles.

Parameters:

data_tiles (List[Tile] or List[DataTile]) – A list of DataTiles to add together.

Returns:

A data tile with the values of the provided data_tiles added together

Return type:

DataTile

gridkit.tile.average_data_tiles(data_tiles: List)[source]

Average the DataTiles in the data_tiles list. Nodata_values will be ignored. Each cell will then contain the mean or average value of that cell accross the supplied DataTiles.

Parameters:

data_tiles (List[Tile] or List[DataTile]) – A list of DataTiles to average.

Returns:

A data tile with the averaged values of the provided data_tiles

Return type:

DataTile