rect_grid

class gridkit.rect_grid.RectGrid(*args, dx=None, dy=None, size=None, area=None, side_length=None, offset=(0, 0), rotation=0, **kwargs)[source]

Bases: BaseGrid

Abstraction that represents an infinite grid with square cell shape.

Initialization parameters

dx: float

The spacing between two cell centroids in horizontal direction. Has to be supplied together with dx. Cannot be supplied together with area, ‘side_length’ or size.

dy: float

The spacing between two cell centroids in vertical direction Has to be supplied together with dy. Cannot be supplied together with area, ‘side_length’ or size.

size: float

The spacing between two cell centroids in horizontal and vertical direction. Cannot be supplied together with area, ‘side_length’ or dx`&`dy.

area: float

The area of a cell. Cannot be supplied together with size, ‘side_length’ or dx`&`dy.

side_length: float

The lenght of the cell sides, i.e. the height and width of the cell. Cannot be supplied together with size, ‘area’ or dx`&`dy.

offset: Tuple(float, float) (optional)

The offset in dx and dy. Shifts the whole grid by the specified amount. The shift is always reduced to be maximum one cell size. If the supplied shift is larger, a shift will be performed such that the new center is a multiple of dx or dy away. Default: (0,0)

rotation: float

The counter-clockwise rotation of the grid around the origin in degrees.

crs: pyproj.CRS (optional)

The coordinate reference system of the grid. 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. Default: None

property definition

The parameters that define the infinite grid. Passing these parameters into a new object instance will create a perfectly aligned grid. Note that Bounded Grids are defined by the bounds and data. Therefore, the properties returned by this property do describe the grid but cannot be used to create a new Bounded Grid object instance.

Returns:

A dictionary outlying the parameters that define the grid

Return type:

dict

property side_length

The lenght of the side of a cell. The length is the same as that of RectGrid.cell_width(). In the case that cell_width and cell_height are different, only cell_widht is returned and cell_height is ignored. A warning is raised if that happens. It is advised to use :meth”.RectGrid.cell_width and :meth”.RectGrid.cell_width when dealing with RectGrids. This function is only implemented to keep the API aligned with the other grid types.

property dx: float

The cellsize in x-direction

property dy: float

The cellsize in y-direction

property size: float

The length of the cell sides, if all sides are of the same length. The returned size is ‘None’ if RectGrid.dx() and RectGrid.dy() are not the same length.

See also

BaseGrid.size()

to_bounded(bounds, fill_value=nan)[source]

Create a bounded version of this grid where the data in the bounds is filled with the supplied fill_value

Parameters:
  • bounds (tuple) – The bounds of the area of interest in (minx, miny, maxx, maxy). The bounds need to be aligned to the grid. See BaseGrid.align_bounds()

  • fill_value (numpy.dtype (optional)) – The value to assign to the newly created array that fills the supplied bounds. Default: numpy.nan

Returns:

A bounded version of the current grid where the data is filled with fill_value.

Return type:

BoundedHexGrid or BoundedRectGrid

relative_neighbours(depth=1, connect_corners=False, include_selected=False, index=None)[source]

The relative indices of the neighbouring cells.

Parameters:
  • depth (int Default: 1) – Determines the number of neighbours that are returned. If depth=1 the direct neighbours are returned. If depth=2 the direct neighbours are returned, as well as the neighbours of these neighbours. depth=3 returns yet another layer of neighbours, and so forth.

  • include_selected (bool Default: False) – Whether to include the specified cell in the return array. Even though the specified cell can never be a neighbour of itself, this can be useful when for example a weighted average of the neighbours is desired in which case the cell itself often should also be included.

  • connect_corners (bool Default: False) – Whether to consider cells that touch corners but not sides as neighbours. If connect_corners is True, the 4 cells directly touching the cell are considered neighbours. If connect_corners is True, the 8 cells surrounding the cell are considered neighbours. This escalates in combination with depth where indices in a square shape around the cell are returned when connect_corners is True, and indices in a diamond shape around the cell are returned when connect_corners is False.

  • index (numpy.ndarray) – The index is mostly relevant for hexagonal grids. For a square grid the relative neighbours are independent on the location on the grid. Here it is only used for the return length. If 10 cells are supplied to index, the relative neighbours are returned 10 times. This is to keep a consistent api between the two classes.

Examples

The direct neighbours of a cell can be returned by using depth=1, which is the default. For square grids, the number of returned neighbours depends on whether connect_corners is True or False:

>>> from gridkit.rect_grid import RectGrid
>>> grid = RectGrid(dx=2, dy=3)
>>> grid.relative_neighbours().index
array([[ 0,  1],
       [-1,  0],
       [ 1,  0],
       [ 0, -1]])
>>> grid.relative_neighbours(connect_corners=True).index
array([[-1,  1],
       [ 0,  1],
       [ 1,  1],
       [-1,  0],
       [ 1,  0],
       [-1, -1],
       [ 0, -1],
       [ 1, -1]])

By specifying depth we can include indirect neighbours from further away. The number of neighbours increases with depth by a factor of depth*4 or depth*8 depending on connect_corners being True or False. So the 3rd element in the list will be 1*4 + 2*4 + 3*4 = 24 if connect_corners is False. And it will be 1*8 + 2*8 + 3*8 = 48 if connect_corners is True.

>>> [len(grid.relative_neighbours(depth=depth)) for depth in range(1,5)]
[4, 12, 24, 36]
>>> [len(grid.relative_neighbours(depth=depth, connect_corners=True)) for depth in range(1,5)]
[8, 24, 48, 80]

The specified cell can be included if include_selected is set to True:

>>> grid.relative_neighbours(include_selected=True).index
array([[ 0,  1],
       [-1,  0],
       [ 0,  0],
       [ 1,  0],
       [ 0, -1]])
centroid(index=None)[source]

Coordinates at the center of the cell(s) specified by index.

Warning

The two values that make up an index are expected to be integers, and will be cast as such.

Parameters:

index (tuple) – Index of the cell of which the centroid is to be calculated. The index consists of two integers specifying the nth cell in x- and y-direction. Mutliple indices can be specified at once in the form of a list of indices or an Nx2 ndarray.

Returns:

The longitude and latitude of the center of each cell. Axes order if multiple indices are specified: (points, xy), else (xy).

Return type:

numpy.ndarray

Raises:

ValueError – No index parameter was supplied. index can only be None in classes that contain data.

Examples

Cell centers of single index are returned as an array with one dimention:

>>> grid = RectGrid(dx=4, dy=1)
>>> grid.centroid((0, 0))
array([2. , 0.5])
>>> grid.centroid((-1, -1))
array([-2. , -0.5])

Multiple cell indices can be supplied as a list of tuples or as an equivalent ndarray:

>>> grid.centroid([(0, 0), (-1, -1)])
array([[ 2. ,  0.5],
       [-2. , -0.5]])
>>> ids = numpy.array([[0, 0], [-1, -1]])
>>> grid.centroid(ids)
array([[ 2. ,  0.5],
       [-2. , -0.5]])

Note that the center coordinate of the cell is also dependent on the grid’s offset:

>>> grid = RectGrid(dx=4, dy=1, offset = (1, 0.5))
>>> grid.centroid((0, 0))
array([3., 1.])
cells_near_point(point)[source]

Nearest 4 cells around a point. This includes the cell the point is contained within, as well as two direct neighbours of this cell and one diagonal neighbor. What neigbors of the containing are slected, depends on where in the cell the point is located.

Parameters:

point (:class”tuple) – Coordinate of the point around which the cells are to be selected. The point consists of two floats specifying x- and y-coordinates, respectively. Mutliple poins can be specified at once in the form of a list of points or an Nx2 ndarray.

Returns:

The indices of the 4 nearest cells in order (top-left, top-right, bottom-left, bottom-right). If a single point is supplied, the four indices are returned as 1d arrays of length 2. If multiple points are supplied, the four indices are returned as Nx2 ndarrays.

Return type:

tuple

Examples

Nearby cell indices are returned as a tuple:

>>> grid = RectGrid(dx=4, dy=1)
>>> grid.cells_near_point((0, 0)).index
array([[-1,  0],
       [ 0,  0],
       [-1, -1],
       [ 0, -1]])
>>> grid.cells_near_point((3, 0.75)).index
array([[0, 1],
       [1, 1],
       [0, 0],
       [1, 0]])

If multiple points are supplied, a tuple with ndarrays is returned:

>>> points = [(0, 0), (3, 0.75), (3, 0)]
>>> nearby_cells = grid.cells_near_point(points)
>>> nearby_cells.index
array([[[-1,  0],
        [ 0,  0],
        [-1, -1],
        [ 0, -1]],

       [[ 0,  1],
        [ 1,  1],
        [ 0,  0],
        [ 1,  0]],

       [[ 0,  0],
        [ 1,  0],
        [ 0, -1],
        [ 1, -1]]])
cell_at_point(point)[source]

Index of the cell containing the supplied point(s).

Parameters:

point (tuple) – Coordinate of the point for which the containing cell is to be found. The point consists of two floats specifying x- and y-coordinates, respectively. Mutliple poins can be specified at once in the form of a list of points or an Nx2 ndarray.

Returns:

The index of the cell containing the point(s). If a single point is supplied, the index is returned as a 1d array of length 2. If multiple points are supplied, the indices are returned as Nx2 ndarrays.

Return type:

numpy.ndarray

Examples

>>> grid = RectGrid(dx=4, dy=1)
>>> grid.cell_at_point((1, 0)).index
array([0, 0])

Offsets, shift the grid with respect to the coordinate system, and thus can influnce what cell contains the point:

>>> grid = RectGrid(dx=4, dy=1, offset=(2,0))
>>> grid.cell_at_point((1, 0)).index
array([-1,  0])

Multiple points can be specified as a list of points or an ndarray:

>>> grid = RectGrid(dx=4, dy=1)
>>> points = [(3, 0), (-0.5, -0.5), (5, 0)]
>>> grid.cell_at_point(points).index
array([[ 0,  0],
       [-1, -1],
       [ 1,  0]])
>>> points = numpy.array(points)
>>> grid.cell_at_point(points).index
array([[ 0,  0],
       [-1, -1],
       [ 1,  0]])
cell_corners(index: GridIndex = None) ndarray[source]

Coordinates of the cell corners as specified by index.

Parameters:

index (GridIndex) – The indices of the cells of interest. Each id contains an x and y value.

Returns:

An array of coordinates in (x,y) specifying each of the corners. The returned array will be of the same shape as the input index, but with an extra axis containing the corners. The last axis is always of size 2 (x,y). The second to last axis is the length of the corners. The other axis are in the shape of the supplied index.

Return type:

numpy.ndarray

to_crs(crs, location=(0, 0), adjust_rotation=False)[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 GeometryArray 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.

  • location ((float, float) (default: (0,0))) –

    The location at which to perform the conversion. When transforming to a new coordinate system, it matters at which location the transformation is performed. The chosen location will be used to determinde the cell size of the new grid. If you are unsure what location to use, pich the center of the area you are interested in.

    Warning

    The location is defined in the original CRS, not in the CRS supplied as the argument to this function call.

  • adjust_rotation (bool (default: False)) – If False, the grid in the new crs has the same rotation as the original grid. Since coordinate transformations often warp and rotate the grid, the original rotation is often not a good fit anymore. If True, set the new rotation to match the orientation of the grid at location after coordinate transformation.

Returns:

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

Return type:

RectGrid

cells_in_bounds(bounds, return_cell_count: bool = False)[source]

Cells contained within a bounding box.

Parameters:
  • bounds (tuple)

  • return_cell_count (bool) – Return a tuple containing the nr of cells in x and y direction inside the provided bounds

Returns:

The indices of the cells contained in the bounds

Return type:

GridIndex

subdivide(factor: int)[source]

Create a new grid that is factor times smaller than the existing grid and aligns perfectly with it.

If factor is one, the side lengths of the new cells will be of the same size as the side lengths of the original cells, which means that the two grids will be exactly the same. If factor is two, the new cell sides will be half the size of the original cell sides. The number of cells grows quadratically with factor. A factor of 2 results in 4 cells that fit in the original, a factor of 3 results in 9 cells that fit in the original, etc..

Parameters:

factor (int) – An integer (whole number) indicating how many times smaller the new gridsize will be. It refers to the side of a grid cell. If factor is 1, the new grid will have cell sides of the same length as the cell sides of the original. If factor is 2, the side of the grid cell will be half the cell side length of the original.

Returns:

A new grid that is factor times smaller then the original grid.

Return type:

RectGrid

property parent_grid_class
update(dx=None, dy=None, size=None, area=None, offset=None, rotation=None, crs=None, **kwargs)[source]

Modify attributes of the existing grid and return a copy. The original grid remains un-mutated.

Parameters:
  • dx (float) – The new horizontal spacing between two cell centroids, i.e. the new width of the cells

  • dy (float) – The new vertical spacing between two cell centroids, i.e. the new height of the cells

  • size (float) – The new size of the length of the cells (dx and dy)

  • area (float) – The area of a cell. Cannot be supplied together with size or dx`&`dy.

  • offset (Tuple[float, float]) – The new offset of the origin of the grid

  • rotation (float) – The new counter-clockwise rotation of the grid in degrees. Can be negative for clockwise rotation.

  • 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.

Returns:

A modified copy of the current grid

Return type:

RectGrid

class gridkit.rect_grid.BoundedRectGrid(data, *args, bounds=None, **kwargs)[source]

Bases: BoundedGrid, RectGrid

Initialization parameters

data: numpy.ndarray

A 2D ndarray containing the data

bounds: :class:Tuple(float, float, float, float)

The extend of the data in minx, miny, maxx, maxy.

crs: pyproj.CRS (optional)

The coordinate reference system of the grid. 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. Default: None

property nr_cells

Number of cells

Returns:

The total number of cells in the grid

Return type:

int

property lon

Array of long values

Returns:

1D-Array of size width, containing the longitudinal values from left to right

Return type:

numpy.ndarray

property lat

Array of lat values

Returns:

1D-Array of size height, containing the latitudinal values from top to bottom

Return type:

numpy.ndarray

centroid(index=None)[source]

Centroids of all cells

Returns:

Multidimensional array containing the longitude and latitude of the center of each cell respectively, in (width, height, lonlat)

Return type:

numpy.ndarray

intersecting_cells(other)[source]
crop(new_bounds, bounds_crs=None, buffer_cells=0)[source]

Cut out a slice of data contained within the supplied bounds.

Parameters:
  • new_bounds (Tuple(minx, miny, maxx, maxy)) – The bounds defining the area to crop, in (minx, miny, maxx, maxy).

  • bounds_crs (pyproj.CRS (optional)) – The bounds defining the extent of the cropped data. The value can be anything accepted by pyproj.CRS.from_user_input().

Returns:

A BoundedGrid containing the data included in the cropped area contained within the bounds.

Return type:

class: BoundedGrid

cell_corners(index: ndarray | None = None) ndarray[source]

Coordinates of the cell corners as specified by index.

Parameters:

index (GridIndex) – The indices of the cells of interest. Each id contains an x and y value.

Returns:

An array of coordinates in (x,y) specifying each of the corners. The returned array will be of the same shape as the input index, but with an extra axis containing the corners. The last axis is always of size 2 (x,y). The second to last axis is the length of the corners. The other axis are in the shape of the supplied index.

Return type:

numpy.ndarray

to_shapely(index=None, as_multipolygon: bool = False)[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.

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 BoundedGrid.resample().

Returns:

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

Return type:

BoundedRectGrid

numpy_id_to_grid_id(np_index)[source]
argmax(*args, **kwargs)
argmin(*args, **kwargs)
grid_id_to_numpy_id(index)[source]
max(*args, **kwargs)
mean(*args, **kwargs)
median(*args, **kwargs)
min(*args, **kwargs)
std(*args, **kwargs)
sum(*args, **kwargs)
anchor(target_loc: Tuple[float, float], cell_element: Literal['centroid', 'corner'] = 'centroid', resample_method='nearest')[source]

Position a specified part of a grid cell at a specified location. This shifts (the origin of) the grid such that the specified cell_element is positioned at the specified target_loc. This is useful for example to align two grids by anchoring them to the same location. The data values for the new grid will need to be resampled since it has been shifted.

Parameters:
  • target_loc (Tuple[float, float]) – The coordinates of the point at which to anchor the grid in (x,y)

  • cell_element (Literal["centroid", "corner"] - Default: "centroid") – The part of the cell that is to be positioned at the specified target_loc. Currently only “centroid” and “corner” are supported. When “centroid” is specified, the cell is centered around the target_loc. When “corner” is specified, a nearby cell_corner is placed onto the target_loc.

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

Returns:

The shifted and resampled grid

Return type:

BoundedGrid

interp_nodata(*args, **kwargs)[source]

Please refer to interp_nodata().