Bases: BaseModule, RasterLayer
Base class for managing raster-based spatial modules in ABSESpy.
Inherits from both Module and RasterLayer to provide comprehensive spatial data management. Extends mesa-geo's RasterLayer with additional capabilities for: - Agent placement and management - Integration with xarray/rasterio for data I/O - Dynamic attribute handling - Spatial operations and analysis
Attributes:
| Name | Type | Description |
|---|---|---|
cell_properties |
set[str]
|
Set of accessible cell attributes (decorated by @raster_attribute). |
attributes |
set[str]
|
All accessible attributes including cell_properties. |
shape2d |
Coordinate
|
Raster dimensions as (height, width). |
shape3d |
Coordinate
|
Raster dimensions as (1, height, width) for rasterio compatibility. |
array_cells |
ndarray
|
NumPy array of PatchCell objects. |
coords |
Coordinate
|
Coordinate system dictionary with 'x' and 'y' arrays. |
random |
ListRandom
|
Random selection proxy for cells. |
mask |
ndarray
|
Boolean array indicating accessible cells. |
cells_lst |
ActorsList[PatchCell]
|
ActorsList containing all cells. |
plot |
ActorsList[PatchCell]
|
Visualization interface for the module. |
This constructor automatically determines the appropriate creation method based on the provided parameters. It supports creating a PatchModule from: - Resolution and shape - Copying an existing layer - xarray DataArray - Vector file or GeoDataFrame - Raster file
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
MainModelProtocol
|
Parent model instance. |
required |
name
|
Optional[str]
|
Module identifier. Defaults to lowercase class name. |
None
|
cell_cls
|
Type[PatchCell]
|
Class to use for creating cells. Defaults to PatchCell. |
PatchCell
|
shape
|
Optional[Coordinate]
|
Array shape (height, width) for creating a new module. |
None
|
resolution
|
Number | None | Tuple[Number, Number]
|
Spatial resolution when creating coordinates. |
1
|
source_layer
|
Optional[PatchModule]
|
Existing PatchModule to copy. |
None
|
xda
|
Optional[DataArray]
|
xarray DataArray containing raster data. |
None
|
attr_name
|
Optional[str]
|
Attribute name for the loaded raster data. |
None
|
apply_raster
|
bool
|
Whether to apply raster data to cells. |
False
|
masked
|
bool
|
Whether to use mask from the data. |
True
|
vector_file
|
Optional[Union[str, GeoDataFrame]]
|
Path to vector file or GeoDataFrame. |
None
|
raster_file
|
Optional[str]
|
Path to raster file. |
None
|
band
|
int
|
Band number to use from raster file. |
1
|
crs
|
Optional[Union[CRS, str]]
|
Coordinate Reference System. |
None
|
total_bounds
|
Optional[List[float]]
|
Spatial bounds [minx, miny, maxx, maxy]. |
None
|
width
|
Optional[int]
|
Width of the raster in cells. |
None
|
height
|
Optional[int]
|
Height of the raster in cells. |
None
|
**kwargs
|
Any
|
Additional arguments passed to RasterLayer initialization. |
{}
|
Source code in abses/space/patch.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
cell_properties
property
¶
The accessible attributes of cells stored in this layer.
All PatchCell methods decorated by raster_attribute should be appeared here.
shape2d
property
¶
Raster shape in 2D (height, width).
This is useful when working with 2d numpy.array.
shape3d
property
¶
Raster shape in 3D (1, heigh, width).
This is useful when working with rasterio band.
array_cells
cached
property
¶
Array of cells stored in this module.
Returns a 2D numpy array with dtype object containing PatchCell.
coords
property
¶
Coordinate system of the raster data.
This is useful when working with xarray.DataArray.
transform_coord ¶
Converts grid indices to real-world coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
int
|
Grid row index. |
required |
col
|
int
|
Grid column index. |
required |
Returns:
| Type | Description |
|---|---|
Coordinate
|
Tuple of (x, y) real-world coordinates. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If indices are out of bounds. |
Source code in abses/space/patch.py
dynamic_var ¶
Update and get dynamic variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attr_name
|
str
|
The dynamic variable to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
ndarray | DataArray
|
2D numpy.ndarray data of the variable. |
Source code in abses/space/patch.py
get_xarray ¶
Creates an xarray DataArray representation with spatial coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attr_name
|
Optional[str]
|
Attribute to retrieve. If None, returns all attributes. |
None
|
update
|
bool
|
If True, updates dynamic variables before retrieval. |
True
|
Returns:
| Type | Description |
|---|---|
DataArray
|
xarray.DataArray with spatial coordinates and CRS information. |
Source code in abses/space/patch.py
select ¶
Selects cells based on specified criteria.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
where
|
Optional[CellFilter | dict[str, Any]]
|
Selection filter. Can be: - None: Select all cells - str: Select by attribute name - numpy.ndarray: Boolean mask array - Shapely.Geometry: Select cells intersecting geometry - dict: Select by attribute-value pairs, e.g., {"state": 3} |
None
|
Returns:
| Type | Description |
|---|---|
ActorsList[PatchCell]
|
ActorsList containing selected cells. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If where parameter is of unsupported type. |
Example
Select cells with elevation > 100¶
high_cells = module.select(module.get_raster("elevation") > 100)
Select cells within polygon¶
cells = module.select(polygon)
Select cells by attribute dict¶
burned = module.select({"state": 3})
Source code in abses/space/patch.py
apply ¶
Apply a function to array cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ufunc
|
Callable[..., Any]
|
A function to apply. |
required |
*args
|
Any
|
Positional arguments to pass to the function. |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the function. |
{}
|
Returns:
| Type | Description |
|---|---|
ndarray
|
The result of the function applied to the array cells. |
Source code in abses/space/patch.py
coord_iter ¶
Iterate over coordinates and cells with precise typing.
Source code in abses/space/patch.py
apply_raster ¶
Applies raster data to cells as attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Raster
|
Input raster data. Can be: - numpy.ndarray: 2D array matching module shape - xarray.DataArray: With spatial coordinates - xarray.Dataset: With named variables |
required |
attr_name
|
Optional[str]
|
Name for the new attribute. Required for xarray.Dataset. |
None
|
**kwargs
|
Any
|
Additional options: cover_crs: Whether to override input data CRS resampling_method: Method for resampling ("nearest", etc.) flipud: Whether to flip data vertically |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If attr_name not provided for Dataset input. |
ValueError
|
If data shape doesn't match module shape. |
Example
Apply elevation data¶
module.apply_raster(elevation_array, attr_name="elevation")
Apply data from xarray¶
module.apply_raster(xda, resampling_method="bilinear")
Source code in abses/space/patch.py
get_raster ¶
Obtaining the Raster layer by attribute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attr_name
|
Optional[str]
|
The attribute to retrieve. If None (by default), retrieve all attributes as a 3D array. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A 3D array of attribute. |
Source code in abses/space/patch.py
reproject ¶
Reproject the xarray data to the same CRS as this layer.
Source code in abses/space/patch.py
get_neighboring_cells ¶
Gets neighboring cells around a position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pos
|
Coordinate
|
Center position (x, y). |
required |
moore
|
bool
|
If True, uses Moore neighborhood (8 neighbors). If False, uses von Neumann neighborhood (4 neighbors). |
required |
include_center
|
bool
|
Whether to include the center cell. |
False
|
radius
|
int
|
Neighborhood radius in cells. |
1
|
Returns:
| Type | Description |
|---|---|
ActorsList[PatchCell]
|
ActorsList containing neighboring cells. |
Example
Get Moore neighborhood with radius 2¶
neighbors = module.get_neighboring_cells((5,5), moore=True, radius=2)
Source code in abses/space/patch.py
get_neighboring_by_indices
cached
¶
Getting neighboring positions of the given coordinate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
Coordinate
|
The indices to get the neighborhood. |
required |
moore
|
bool
|
Whether to use Moore neighborhood. If False, use Von Neumann neighborhood. |
required |
include_center
|
bool
|
Whether to include the center cell. Default is False. |
False
|
radius
|
int
|
The radius of the neighborhood. Default is 1. |
1
|
annular
|
bool
|
Whether to use annular (ring) neighborhood. Default is False. |
False
|
Returns:
| Type | Description |
|---|---|
ActorsList[PatchCell]
|
An |
Source code in abses/space/patch.py
indices_out_of_bounds ¶
Determines whether position is off the grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pos
|
Coordinate
|
Position to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if position is off the grid, False otherwise. |
Source code in abses/space/patch.py
count_agents ¶
Count the number of agents of a specific type on each cell across the entire module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agent_type
|
Type[ActorProtocol] | None
|
The agent class to count (e.g., Sheep, Wolf). |
None
|
dtype
|
Literal['numpy', 'xarray']
|
Return type. Options: - "numpy": Returns 2D numpy array - "xarray": Returns xarray DataArray with spatial coordinates (default) |
'xarray'
|
Returns:
| Type | Description |
|---|---|
NDArray[int_] | DataArray
|
Agent counts as numpy array or xarray DataArray with shape (height, width). |
Examples:
>>> # Get as xarray with spatial coordinates (default)
>>> sheep_map = grassland.count_agents(Sheep)
>>> # Now has .rio methods and coordinates
>>> sheep_map.rio.crs
>>> sheep_map.plot()
>>>
>>> # Get as numpy array
>>> sheep_map = grassland.count_agents(Sheep, dtype="numpy")
Source code in abses/space/patch.py
apply_agents ¶
Apply a function or attribute access to the agent(s) on each cell.
This method vectorizes over the raster cells and, for each cell, operates on its linked agents. It supports three usage modes:
1) Single-agent access (capacity=1 typical):
- Provide attr (str) to fetch an attribute from the only agent.
- Or provide func(agent) to compute a value from the only agent.
If the cell is empty, returns default.
2) Aggregation over multiple agents per cell:
- Provide aggregator(actors: ActorsList) to reduce the cell's
agents into a single value (e.g., len(actors), sum(...)).
3) xarray output:
- Set dtype='xarray' to get an xr.DataArray with spatial coords
and CRS info baked in.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Optional[Callable[[Actor], Any]]
|
Function to apply to a single agent on each cell. |
None
|
attr
|
Optional[str]
|
Attribute name to fetch from a single agent on each cell. |
None
|
default
|
Any
|
Value to use when a cell has no agent (or attribute missing). |
nan
|
aggregator
|
Optional[Callable[[ActorsList[Actor]], Any]]
|
Function that reduces |
None
|
dtype
|
Literal['numpy', 'xarray']
|
Output type. |
'numpy'
|
name
|
Optional[str]
|
Optional name for the xarray DataArray. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray | DataArray
|
A 2D numpy array or xarray DataArray of computed values per cell. |
Notes
- If both
aggregatorand (func/attr) are provided,aggregatortakes precedence and receives the entire cellActorsList. - When using
attrorfuncand multiple agents exist on a cell, the first agent is used viaactors.item(default=None).
Source code in abses/space/patch.py
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 | |