API documentation for the grid module

The grid module is used to create the grid of cells underlying the simulation and to identify the neighbourhood connections of cells.

  • set up neighbourhoods. ? store as graph (networkx - might only need a really lightweight graph description).

  • import of geojson grids? Way to link structured landscape into cells. Can use data loading methods to assign values to grids? This would be a useful way of defining mappings though.

  • maybe look at libpysal if we end up needing more weights/spatial analysis stuff? https://pysal.org/libpysal/

Data:

GRID_REGISTRY

A registry for different grid geometries.

Classes:

Grid([grid_type, cell_area, cell_nx, ...])

Define the grid of cells used in a Virtual Ecosystem simulation.

Functions:

make_hex_grid(cell_area, cell_nx, cell_ny[, ...])

Create a hexagonal grid.

make_square_grid(cell_area, cell_nx, cell_ny)

Create a square grid.

register_grid(grid_type)

Add a grid type and creator function to the grid registry.

virtual_ecosystem.core.grid.GRID_REGISTRY: dict[str, Callable] = {'hexagon': <function make_hex_grid>, 'square': <function make_square_grid>}

A registry for different grid geometries.

This dictionary maps grid geometry types (square, hex, etc) to a function generating a grid of that type. Users can register their own grid types using the register_grid decorator.

virtual_ecosystem.core.grid.GRID_STRUCTURE_SIG

Type signature of the data structure to be returned from grid creator functions.

The first value is a list of integer cell ids, the second is a matching list of the polygons for each cell id. Although cell ids could be a numpy array, the numpy int types then need handling in arguments and json representation.

Methods:

__repr__()

Return repr(self).

count(value, /)

Return number of occurrences of value.

index(value[, start, stop])

Return first index of value.

class virtual_ecosystem.core.grid.Grid(grid_type: str = 'square', cell_area: float = 10000, cell_nx: int = 10, cell_ny: int = 10, xoff: float = 0, yoff: float = 0)

Define the grid of cells used in a Virtual Ecosystem simulation.

The simulation grid used in a Virtual Ecosystem simulation is assumed to be a projected coordinate system with linear dimensions in metres. Grid cell sizes are set using their area in square metres and users can specify offsets to align a simulation grid to a particular projected coordinate system. However, the Virtual Ecosystem codebase makes no attempt to manage or validate projection information: we assume that users maintain a common coordinate system across inputs.

Parameters:
  • grid_type – The grid type to be used, which must identify a grid creation function in the GRID_REGISTRY dictionary.

  • cell_area – The area of each grid cell, in square metres.

  • cell_nx – The number of cells in the grid along the x (easting) axis

  • cell_ny – The number of cells in the grid along the y (northing) axis

  • xoff – An offset for the grid x origin in metres

  • yoff – An offset for the grid y origin in metres

Methods:

__repr__()

Represent a CoreGrid as a string.

dump(outfile[, dp])

Export a grid as a GeoJSON file.

dumps([dp])

Export a grid as a GeoJSON string.

from_config(config)

Factory function to generate a Grid instance from a configuration dict.

get_distances(cell_from, cell_to)

Calculate euclidean distances between cell centroids.

map_xy_to_cell_id(x_coords, y_coords)

Map a set of coordinates onto grid cells.

map_xy_to_cell_indexing(x_coords, y_coords, ...)

Returns indexing to map xy coordinates a single cell_id axis.

populate_distances()

Populate the complete cell distance matrix for the grid.

set_neighbours([edges, vertices, distance])

Populate the neighbour list for a Grid object.

Attributes:

bounds

A GeometryCollection providing the bounds of the cell polygons.

cell_area

The area of the grid cells

cell_id

A list of unique integer ids for each cell.

cell_nx

The number of cells in the grid in the X dimension

cell_ny

The number of cells in the grid in the Y dimension

centroids

A list of the centroid of each cell as shapely.geometry.Point objects, in cell_id order.

grid_type

The grid type used to create the instance

ncells

The total number of cells in the grid.

neighbours

Return the neighbours property.

polygons

A list of of the cell polygon geometries, as shapely.geometry.Polygon objects, in cell_id order

xoff

An offset for the cell X coordinates

yoff

An offset for the cell Y coordinates

__repr__() str

Represent a CoreGrid as a string.

bounds: GeometryCollection

A GeometryCollection providing the bounds of the cell polygons.

cell_area

The area of the grid cells

cell_id: list[int]

A list of unique integer ids for each cell.

cell_nx

The number of cells in the grid in the X dimension

cell_ny

The number of cells in the grid in the Y dimension

centroids: ndarray

A list of the centroid of each cell as shapely.geometry.Point objects, in cell_id order.

dump(outfile: str, dp: int = 2, **kwargs: Any) None

Export a grid as a GeoJSON file.

The virtual_ecosystem.core.Grid object assumes an unspecified projected coordinate system. As a result, GeoJSON files created by this export method do not strictly obey the GeoJSON specification (https://www.rfc-editor.org/rfc/rfc7946), which requires WGS84 coordinates to describe locations.

Parameters:
  • outfile – A path used to export GeoJSON data.

  • dp – The decimal place precision for exported coordinates

  • kwargs – Arguments to json.dump

dumps(dp: int = 2, **kwargs: Any) str

Export a grid as a GeoJSON string.

The virtual_ecosystem.core.Grid object assumes an unspecified projected coordinate system. As a result, GeoJSON files created by this export method do not strictly obey the GeoJSON specification (https://www.rfc-editor.org/rfc/rfc7946), which requires WGS84 coordinates to describe locations.

Parameters:
  • dp – The decimal place precision for exported coordinates

  • kwargs – Arguments to json.dumps

classmethod from_config(config: Config) Grid

Factory function to generate a Grid instance from a configuration dict.

Parameters:

config – A validated Virtual Ecosystem model configuration object.

get_distances(cell_from: int | Sequence[int] | None, cell_to: int | Sequence[int] | None) ndarray

Calculate euclidean distances between cell centroids.

This method returns a two dimensional np.array containing the Euclidean distances between two sets of cell ids.

Parameters:
  • cell_from – Either a single integer cell_id or a list of ids.

  • cell_to – Either a single integer cell_id or a list of ids.

Returns:

A 2D np.array of Euclidean distances

grid_type

The grid type used to create the instance

map_xy_to_cell_id(x_coords: ndarray, y_coords: ndarray) list[list[int]]

Map a set of coordinates onto grid cells.

This function loops over points defined by pairs of x and y coordinates and maps the coordinates onto the cell_ids of the grid. The method also checks to see that each point intersects one and only one of the cell polygons defined in the grid. Points that intersect no cells fall outside the grid polygons and points that intersect more than one cell fall ambiguously on cell borders.

Parameters:
  • x_coords – A numpy array of x coordinates of points that should occur within grid cells.

  • y_coords – A similar and equal-length array providing y coordinates.

Returns:

A list of lists showing the cell ids that map onto each point. The list for a given point can be empty - when the point falls in no cell - or of length > 1 when a point falls on adjoining cell boundaries.

map_xy_to_cell_indexing(x_coords: ndarray, y_coords: ndarray, x_idx: ndarray | None, y_idx: ndarray | None) tuple[ndarray, ndarray]

Returns indexing to map xy coordinates a single cell_id axis.

This function maps the provided one-dimensional set of x and y points onto the grid (using ~virtual_ecosystem.core.grid.Grid.map_xy_to_cell_id) and then checks that the mapped points provide a one-to-one mapping onto the grid cells.

The function then returns a pair of arrays that give indices on the original x and y data to extract data along a single cell id axis. Because the inputs are expected to be flattened onto a single dimension, the function also accepts x and y index values that allow the cells to be mapped back into original dimensions. If these are not provided, the coordinates are are assumed to have come from a one-dimensional structure and so these indices are simple sequences along x_coords and y_coords.

Parameters:
  • x_coords – A numpy array of x coordinates of points that should occur within grid cells.

  • y_coords – A similar and equal-length array providing y coordinates.

  • x_idx – A numpy array providing original indices along the x-axis

  • y_idx – A numpy array providing original indices along the y-axis

Returns:

A list giving the integer cell id for each pair of points.

ncells: int

The total number of cells in the grid.

property neighbours: list[ndarray[Any, dtype[int64]]]

Return the neighbours property.

polygons: list[Polygon]

A list of of the cell polygon geometries, as shapely.geometry.Polygon objects, in cell_id order

populate_distances() None

Populate the complete cell distance matrix for the grid.

This stores the full distance matrix in the Grid instance, which is then used for quick lookup by the get_distance method. However for large grids, this requires a lot of memory, and so calculating distances on demand may be more reasonable.

set_neighbours(edges: bool = True, vertices: bool = False, distance: float | None = None) None

Populate the neighbour list for a Grid object.

This method generates a list giving the neighbours of each cell in the grid. The edges and vertices arguments are used to include neighbouring cells that share edges or vertices with a focal cell. Alternatively, a distance in metres from the focal cell centroid can be used to include neighbouring cells within that distance.

Parameters:
  • edges – Include cells with shared edges as neighbours.

  • vertices – Include cells with shared vertices as neighbours.

  • distance – A distance in metres.

xoff

An offset for the cell X coordinates

yoff

An offset for the cell Y coordinates

virtual_ecosystem.core.grid.make_hex_grid(cell_area: float, cell_nx: int, cell_ny: int, xoff: float = 0, yoff: float = 0) tuple[list[int], list[Polygon]]

Create a hexagonal grid.

Parameters:
  • cell_area – The area of each hexagon cell in m2.

  • cell_nx – The number of grid cells in the X direction.

  • cell_ny – The number of grid cells in the Y direction.

  • xoff – An offset to use for the grid origin in the X direction in metres.

  • yoff – An offset to use for the grid origin in the Y direction in metres.

Returns:

Equal-length tuples of integer polygon ids and Polygon objects

virtual_ecosystem.core.grid.make_square_grid(cell_area: float, cell_nx: int, cell_ny: int, xoff: float = 0, yoff: float = 0) tuple[list[int], list[Polygon]]

Create a square grid.

Parameters:
  • cell_area – The area of each hexagon cell in m2

  • cell_nx – The number of grid cells in the X direction.

  • cell_ny – The number of grid cells in the Y direction.

  • xoff – An offset to use for the grid origin in the X direction in metres.

  • yoff – An offset to use for the grid origin in the Y direction in metres.

Returns:

Equal-length tuples of integer polygon ids and Polygon objects

virtual_ecosystem.core.grid.register_grid(grid_type: str) Callable

Add a grid type and creator function to the grid registry.

This decorator is used to add a function creating a grid layout to the registry of accepted grids. The function must return a numpy array of integer polygon ids and an equal length list of Polygon objects, following the GRID_STRUCTURE_SIG signature.

The grid_type argument is used to identify the grid creation function to be used by the Grid class and in configuration files.

Parameters:

grid_type – A name to be used to identify the grid creation function.