Raster Layers#

class RasterBase(width, height, crs, total_bounds)[source]#

Base class for raster layers.

Initialize a raster base layer.

Parameters:
  • width – Width of the raster base layer.

  • height – Height of the raster base layer.

  • crs – Coordinate reference system of the raster base layer.

  • total_bounds – Bounds of the raster base layer in [min_x, min_y, max_x, max_y] format.

property width: int#

Return the width of the raster base layer.

Returns:

Width of the raster base layer.

Return type:

int

property height: int#

Return the height of the raster base layer.

Returns:

Height of the raster base layer.

Return type:

int

property total_bounds: ndarray | None#

Return the bounds of the raster layer in [min_x, min_y, max_x, max_y] format.

Returns:

Bounds of the raster layer in [min_x, min_y, max_x, max_y] format.

Return type:

np.ndarray | None

property transform: Affine#

Return the affine transformation of the raster base layer.

Returns:

Affine transformation of the raster base layer.

Return type:

Affine

property resolution: tuple[float, float]#

Returns the (width, height) of a cell in the units of CRS.

Returns:

Width and height of a cell in the units of CRS.

Return type:

Tuple[float, float]

to_crs(crs, inplace=False) RasterBase | None[source]#

Transform the object to a new coordinate reference system.

Parameters:
  • crs – The coordinate reference system to transform to.

  • inplace – Whether to transform the object in place or return a new object. Defaults to False.

Returns:

The transformed object if not inplace.

Return type:

GeoBase | None

out_of_bounds(pos: tuple[int, int]) bool[source]#

Determines whether position is off the grid.

Parameters:

pos (Coordinate) – Position to check.

Returns:

True if position is off the grid, False otherwise.

Return type:

bool

property crs: CRS | None#

Return the coordinate reference system of the object.

class Cell(model, pos=None, indices=None, *, rowcol=None, xy=None)[source]#

Cells are containers of raster attributes, and are building blocks of RasterLayer.

Deprecated:

Cell.indices is deprecated. Use Cell.rowcol instead.

Initialize a cell.

Parameters:
  • pos – Grid position of the cell in (grid_x, grid_y) format. Origin is at lower left corner of the grid

  • indices – (Deprecated) Indices of the cell in (row, col) format. Origin is at upper left corner of the grid. Use rowcol instead.

  • rowcol – Indices of the cell in (row, col) format. Origin is at upper left corner of the grid

  • xy – Geographic/projected (x, y) coordinates of the cell center in the CRS.

property pos: tuple[int, int] | None#

Grid position in (grid_x, grid_y) format with origin at lower left of the grid.

property indices: tuple[int, int] | None#

Deprecated alias of rowcol.

property rowcol: tuple[int, int] | None#

Raster indices in (row, col) format with origin at upper left of the grid.

property xy: tuple[float, float] | ndarray[tuple[Any, ...], dtype[float]] | None#

Geographic/projected (x, y) coordinates of the cell center in the CRS.

step()[source]#

A single step of the agent.

advance() None#
classmethod create_agents(model: Model, n: int, *args, **kwargs) AgentSet[T]#

Create N agents.

Args:

model: the model to which the agents belong args: arguments to pass onto agent instances

each arg is either a single object or a sequence of length n

n: the number of agents to create kwargs: keyword arguments to pass onto agent instances

each keyword arg is either a single object or a sequence of length n

Returns:

AgentSet containing the agents created.

classmethod from_dataframe(model: Model, df: pd.DataFrame, **kwargs) AgentSet[T]#

Create agents from a pandas DataFrame.

Each row of the DataFrame represents one agent. The DataFrame columns are mapped to the agent’s constructor as keyword arguments. Additional keyword arguments (**kwargs) can be used to set constant attributes for all agents.

Args:

model: The model instance. df: The pandas DataFrame. Each row represents an agent. **kwargs: Constant values to pass to every agent’s constructor.

Only non-sequence data is allowed in kwargs to avoid ambiguity with DataFrame columns.

Returns:

AgentSet containing the agents created.

Note:

If you need to pass variable data or sequences, add them as columns to the DataFrame before calling this method.

property random: Random#

Return a seeded stdlib rng.

remove() None#

Remove and delete the agent from the model.

Notes:

If you need to do additional cleanup when removing an agent by for example removing it from a space, consider extending this method in your own agent class.

property rng: Generator#

Return a seeded np.random rng.

property scenario#

Return the scenario associated with the model.

class RasterLayer(width, height, crs, total_bounds, model, cell_cls: type[Cell] = Cell)[source]#

Some methods in RasterLayer are copied from mesa.space.Grid, including:

__getitem__ __iter__ coord_iter iter_neighborhood get_neighborhood iter_neighbors get_neighbors # copied and renamed to get_neighboring_cells out_of_bounds # copied into RasterBase iter_cell_list_contents get_cell_list_contents

Methods from mesa.space.Grid that are not copied over:

torus_adj neighbor_iter move_agent place_agent _place_agent remove_agent is_cell_empty move_to_empty find_empty exists_empty_cells

Another difference is that mesa.space.Grid has self.grid: List[List[Agent | None]], whereas it is self.cells: List[List[Cell]] here in RasterLayer.

Initialize a raster base layer.

Parameters:
  • width – Width of the raster base layer.

  • height – Height of the raster base layer.

  • crs – Coordinate reference system of the raster base layer.

  • total_bounds – Bounds of the raster base layer in [min_x, min_y, max_x, max_y] format.

cells: list[list[Cell]]#
property attributes: set[str]#

Return the attributes of the cells in the raster layer.

Returns:

Attributes of the cells in the raster layer.

Return type:

Set[str]

coord_iter() Iterator[tuple[Cell, int, int]][source]#

An iterator that returns coordinates as well as cell contents.

apply_raster(data: ndarray, attr_name: str | Sequence[str] | None = None) None[source]#

Apply raster data to the cells.

Parameters:
  • data (np.ndarray) – 3D numpy array with shape (bands, height, width).

  • attr_name (str | Sequence[str] | None) – Attribute name(s) to be added to the cells. For multi-band rasters, pass a list of names with length equal to the number of bands, or a single base name to be suffixed per band. If None, names are generated. Default is None.

Raises:

ValueError – If the shape of the data does not match the raster.

get_raster(attr_name: str | Sequence[str] | None = None) ndarray[source]#

Return the values of given attribute.

Parameters:

attr_name (str | Sequence[str] | None) – Name(s) of attributes to be returned. If None, returns all attributes. Default is None.

Returns:

The values of given attribute(s) as a numpy array with shape (bands, height, width).

Return type:

np.ndarray

iter_neighborhood(pos: tuple[int, int], moore: bool, include_center: bool = False, radius: int = 1) Iterator[tuple[int, int]][source]#

Return an iterator over cell coordinates that are in the neighborhood of a certain point.

Parameters:
  • pos (Coordinate) – Grid coordinate tuple (grid_x, grid_y) for the neighborhood to get. Origin is at lower left corner of the grid.

  • moore (bool) – Whether to use Moore neighborhood or not. If True, return Moore neighborhood (including diagonals). If False, return Von Neumann neighborhood (exclude diagonals).

  • include_center (bool) – If True, return the (grid_x, grid_y) cell as well. Otherwise, return surrounding cells only. Default is False.

  • radius (int) – Radius, in cells, of the neighborhood. Default is 1.

Returns:

An iterator over cell coordinates that are in the neighborhood. For example with radius 1, it will return list with number of elements equals at most 9 (8) if Moore, 5 (4) if Von Neumann (if not including the center).

Return type:

Iterator[Coordinate]

property crs: CRS | None#

Return the coordinate reference system of the object.

property height: int#

Return the height of the raster base layer.

Returns:

Height of the raster base layer.

Return type:

int

iter_neighbors(pos: tuple[int, int], moore: bool, include_center: bool = False, radius: int = 1) Iterator[Cell][source]#

Return an iterator over neighbors to a certain point.

Parameters:
  • pos (Coordinate) – Grid coordinate tuple (grid_x, grid_y) for the neighborhood to get. Origin is at lower left corner of the grid.

  • moore (bool) – Whether to use Moore neighborhood or not. If True, return Moore neighborhood (including diagonals). If False, return Von Neumann neighborhood (exclude diagonals).

  • include_center (bool) – If True, return the (grid_x, grid_y) cell as well. Otherwise, return surrounding cells only. Default is False.

  • radius (int) – Radius, in cells, of the neighborhood. Default is 1.

Returns:

An iterator of cells that are in the neighborhood; at most 9 (8) if Moore, 5 (4) if Von Neumann (if not including the center).

Return type:

Iterator[Cell]

out_of_bounds(pos: tuple[int, int]) bool#

Determines whether position is off the grid.

Parameters:

pos (Coordinate) – Position to check.

Returns:

True if position is off the grid, False otherwise.

Return type:

bool

property resolution: tuple[float, float]#

Returns the (width, height) of a cell in the units of CRS.

Returns:

Width and height of a cell in the units of CRS.

Return type:

Tuple[float, float]

property total_bounds: ndarray | None#

Return the bounds of the raster layer in [min_x, min_y, max_x, max_y] format.

Returns:

Bounds of the raster layer in [min_x, min_y, max_x, max_y] format.

Return type:

np.ndarray | None

property transform: Affine#

Return the affine transformation of the raster base layer.

Returns:

Affine transformation of the raster base layer.

Return type:

Affine

property width: int#

Return the width of the raster base layer.

Returns:

Width of the raster base layer.

Return type:

int

iter_cell_list_contents(positions) Any#
get_cell_list_contents(positions) Any#
get_neighborhood(pos: tuple[int, int], moore: bool, include_center: bool = False, radius: int = 1) list[tuple[int, int]][source]#

Return a list of cell coordinates that are in the neighborhood of a certain point.

Parameters:
  • pos (Coordinate) – Grid coordinate tuple (grid_x, grid_y) for the neighborhood to get. Origin is at lower left corner of the grid.

  • moore (bool) – Whether to use Moore neighborhood or not. If True, return Moore neighborhood (including diagonals). If False, return Von Neumann neighborhood (exclude diagonals).

  • include_center (bool) – If True, return the (grid_x, grid_y) cell as well. Otherwise, return surrounding cells only. Default is False.

  • radius (int) – Radius, in cells, of the neighborhood. Default is 1.

Returns:

A list of cell coordinates that are in the neighborhood. For example with radius 1, it will return list with number of elements equals at most 9 (8) if Moore, 5 (4) if Von Neumann (if not including the center).

Return type:

List[Coordinate]

get_neighboring_cells(pos: tuple[int, int], moore: bool, include_center: bool = False, radius: int = 1) list[Cell][source]#
to_crs(crs, inplace=False) RasterLayer | None[source]#

Transform the raster layer to a new coordinate reference system.

Parameters:
  • crs – The coordinate reference system to transform to.

  • inplace – Whether to transform the raster layer in place or return a new raster layer. Defaults to False.

Returns:

The transformed raster layer if not inplace.

Return type:

RasterLayer | None

to_image(colormap) ImageLayer[source]#

Returns an ImageLayer colored by the provided colormap.

classmethod from_file(raster_file: str, model: Model, cell_cls: type[Cell] = Cell, attr_name: str | Sequence[str] | None = None, rio_opener: Callable | None = None) RasterLayer[source]#

Creates a RasterLayer from a raster file.

Parameters:
  • raster_file (str) – Path to the raster file.

  • cell_cls (Type[Cell]) – The class of the cells in the layer.

  • attr_name (str | Sequence[str] | None) – Attribute name(s) to use for the cell values. For multi-band rasters, pass a list of names with length equal to the number of bands, or a single base name to be suffixed per band. If None, names are generated. Default is None.

  • rio_opener (Callable | None) – A callable passed to Rasterio open() function.

to_file(raster_file: str, attr_name: str | Sequence[str] | None = None, driver: str = 'GTiff') None[source]#

Writes a raster layer to a file.

Parameters:
  • raster_file (str) – The path to the raster file to write to.

  • attr_name (str | Sequence[str] | None) – The name(s) of attributes to write to the raster. If None, all attributes are written. Default is None.

  • driver (str) – The GDAL driver to use for writing the raster file. Default is ‘GTiff’. See GDAL docs at https://gdal.org/drivers/raster/index.html.

class ImageLayer(values, crs, total_bounds)[source]#

Initializes an ImageLayer.

Parameters:
  • values – The values of the image layer.

  • crs – The coordinate reference system of the image layer.

  • total_bounds – The bounds of the image layer in [min_x, min_y, max_x, max_y] format.

property crs: CRS | None#

Return the coordinate reference system of the object.

property height: int#

Return the height of the raster base layer.

Returns:

Height of the raster base layer.

Return type:

int

out_of_bounds(pos: tuple[int, int]) bool#

Determines whether position is off the grid.

Parameters:

pos (Coordinate) – Position to check.

Returns:

True if position is off the grid, False otherwise.

Return type:

bool

property resolution: tuple[float, float]#

Returns the (width, height) of a cell in the units of CRS.

Returns:

Width and height of a cell in the units of CRS.

Return type:

Tuple[float, float]

property total_bounds: ndarray | None#

Return the bounds of the raster layer in [min_x, min_y, max_x, max_y] format.

Returns:

Bounds of the raster layer in [min_x, min_y, max_x, max_y] format.

Return type:

np.ndarray | None

property transform: Affine#

Return the affine transformation of the raster base layer.

Returns:

Affine transformation of the raster base layer.

Return type:

Affine

property width: int#

Return the width of the raster base layer.

Returns:

Width of the raster base layer.

Return type:

int

property values: ndarray#

Returns the values of the image layer.

Returns:

The values of the image layer.

Return type:

np.ndarray

to_crs(crs, inplace=False) ImageLayer | None[source]#

Transform the image layer to a new coordinate reference system.

Parameters:
  • crs – The coordinate reference system to transform to.

  • inplace – Whether to transform the image layer in place or return a new image layer. Defaults to False.

Returns:

The transformed image layer if not inplace.

Return type:

ImageLayer | None

classmethod from_file(image_file) ImageLayer[source]#

Creates an ImageLayer from an image file.

Parameters:

image_file – The path to the image file.

Returns:

The ImageLayer.

Return type:

ImageLayer