spatiocoexistence package¶
SpatioCoexistence: A package for and individual-based forest model and corresponding analysis tools
- class spatiocoexistence.Model[source]¶
Bases:
objectThis is the individual-based model class. This class is used to create, run, analyse and optimize models.
- No-index:
Initialize the model
- Parameters:
parameters – Parameters to configure the model. Either they are supplied via a file or dictionary. Otherwise they will be set to default values.
initial_inventory – Initial inventory data or path to file containing it.
reference_inventory – Reference inventory to compare the simulated inventory to. For optimization and analysis purposes.
threads – The number of CPU-threads to be used to run the model.
- __init__(parameters=None, initial_inventory=None, reference_inventory=None, threads=1)[source]¶
Initialize the model
- Parameters:
parameters (Path | dict[str, Any] | None) – Parameters to configure the model. Either they are supplied via a file or dictionary. Otherwise they will be set to default values.
initial_inventory (ndarray | Path | Inventory | None) – Initial inventory data or path to file containing it.
reference_inventory (ndarray | Path | None) – Reference inventory to compare the simulated inventory to. For optimization and analysis purposes.
threads (int) – The number of CPU-threads to be used to run the model.
- growth()[source]¶
Apply growth process to the current inventory, updating dbh values in place.
- Return type:
ndarray
- mortality()[source]¶
Apply mortality process to the current inventory and return indices of dead individuals. Dead individuals are removed from the inventory.
- Returns:
Array of indices that were dead (before removal).
- Return type:
- optimize_parameters(start_params, lower, upper, rhobeg, rhoend, param_names, methods_to_evaluate, stat_indices=None, n_init=50, n_iter=10, iter_steps=5, reference_inventory=None, maxfun=None, verbose=False, objfun_has_noise=True)[source]¶
The optimizer uses the PYBOBYQA algorithm to fit arbitrary statistics to the model parameters using the log likelihood function.
- Parameters:
start_params (ndarray) – Initial guess for parameters.
lower (ndarray) – Lower bounds for parameters.
upper (ndarray) – Upper bounds for parameters.
param_names (list[str]) – Names of parameters to optimize (order matches start_params).
methods_to_evaluate (Sequence[tuple[Callable[[...], Any], Callable[[...], Any] | property]]) – Functions to calculate the statistics that shall be matched. Each tuple: (statistic function, kwargs for function).
stat_indices (list[slice | list[int]] | None) – For each stat_func, which indices of the values to use (default: use all).
n_init (int) – Initial run steps.
n_iter (int) – Number of iterations for averaging.
iter_steps (int) – Steps per iteration.
maxfun (int | None) – Maximum number of objective evaluations (defaults to a small value for speed).
verbose (bool) – If True, print intermediate diagnostics.
objfun_has_noise (bool) – Pass-through to PYBOBYQA’s objfun_has_noise.
- Returns:
The result of the PYBOBYQA algorithm
- Return type:
Any
- property parameters: dict¶
Access a copy of the current model parameters (backend source of truth).
- plot(reference_plot=False, threshold=50, filter=1.0, scale=7.5, figsize=(22, 10))[source]¶
Plot the current state of the model.
- Parameters:
title – The title of the plot.
reference_plot (bool) – If True, the reference inventory is plotted.
threshold (int) – Minimum abundance of conspecifics ToDo.
filter (float) – Filter out all trees below that size for inventory plot.
- recruitment()[source]¶
Apply recruitment process, add the recruits to the inventory. And return an Inventory of the new recruits.
ToDo test it.
- Return type:
- run_with_plotting(n_steps=1000, plot_interval=50, threshold=50, figsize=(24, 12))[source]¶
Run the simulation with plotting enabled to see the development of the forest inventory in real time.
ToDo: Extract this function to plotting.
- Parameters:
n_steps (int) – Amount of steps to be simulated.
plot_interval (int) – The interval at which the inventories shall be plotted.
threshold (int) – Minimum abundance of conspecifics ToDo.
figsize – The size of the plot.
- class spatiocoexistence.Inventory[source]¶
Bases:
objectThis inventory class stores forest data from the simulation and the ForestGEO network. Instance methods offer statistics for analyzing the data directly. Some statistics require crowding indices, which is why they are calculated if they are not provided in the data. :no-index:
- property CI_C¶
Conspecific crowding index (unweighted).
- property CI_CS¶
Conspecific crowding index.
- property CI_CS_d¶
Conspecific crowding index (distance-weighted).
- property CI_C_d¶
Conspecific crowding index (distance-weighted, unweighted).
- property CI_H¶
Heterospecific crowding index (unweighted).
- property CI_HS¶
Heterospecific crowding index.
- property CI_HS_d¶
Heterospecific crowding index (distance-weighted).
- property CI_H_d¶
Heterospecific crowding index (distance-weighted, unweighted).
- count_reproductives(reproductive_size)[source]¶
Count the number of reproductive trees.
All individuals are checked to be alive and larger or equally large than reproductive_size.
- Parameters:
reproductive_size (float) – The size upon which an individual can reproduce.
- Returns:
Amount of reproductives per species, indices of reproductive trees.
- Return type:
tuple[ndarray[int32], ndarray[int32]]
- count_saplings(reproductive_size)[source]¶
Count the number of saplings.
All individuals are checked to be alive and smaller than reproductive_size.
- Parameters:
reproductive_size (float) – The size upon which an individual can reproduce.
- Returns:
The total amount of saplings.
- Return type:
int
- property data: ndarray¶
The full structured numpy array representing the inventory. Read-only: do not assign directly, use field setters or methods.
- property dbh¶
Diameter at breast height (np.ndarray, dtype float64). This property can be updated/set. Setting it will automatically recalculate all crowding indices.
- extend_inventory(other)[source]¶
Extend the current inventory by appending another inventory’s data.
This method concatenates all fields from the other inventory to the current one and recalculates all crowding indices for the combined dataset.
- Parameters:
other (Inventory | ndarray) – Another Inventory object or structured numpy array to append.
- Raises:
TypeError – If other is not an Inventory or compatible structured array.
ValueError – If the data structures are incompatible.
- classmethod from_data(data, radius=10.0)[source]¶
Create an Inventory instance from existing data, a file path, or another Inventory.
If an Inventory is provided, its data and radius are copied. If a Path is provided, the file is read and validated. If a numpy array is provided, it is validated for correct structure and types.
- Parameters:
data (ndarray | Path | Inventory) – Structured numpy array, file path, or Inventory to initialize from.
radius (float) – Neighborhood radius for crowding indices (default: 10.0).
returns – A new Inventory instance initialized from the provided data.
- classmethod from_random(n_species, dim_x, dim_y, radius=10.0, num_threads=1)[source]¶
Create an Inventory instance from randomly spread trees. These trees will have the same density as trees in the BCI plot.
- Parameters:
n_species (int) – Number of different species to include in the inventory.
dim_x (float) – Width of the plot area.
dim_y (float) – Height of the plot area.
radius (float) – Neighborhood radius for crowding indices (default: 10.0).
num_threads (int) – Number of threads to use for inventory creation (default: 1).
- Returns:
A new Inventory instance with randomly generated data.
- get_BA_and_k()[source]¶
Calculates summary statistics for BA and k using inventory data.
BA stands for basal area, and k represents aggregation. ff is for comparing a focal species with conspecifics. fh is for comparing a focal species with heterospecifics.
- Returns:
Tuple of arrays (BA_ff, BA_fh, n_BA_ff, n_BA_fh, k_ff, k_fh, abundance_con, abundance_het).
- Return type:
tuple
- get_CI_CS_distribution(bins)[source]¶
Get distribution counts for conspecific crowding index (CI_CS).
- Parameters:
bins (ndarray) – Array of bin edges for distribution.
- Returns:
Distribution of CI_CS.
- Return type:
ndarray
- get_CI_HS_distribution(bins)[source]¶
Get distribution counts for heterospecific crowding index (CI_HS).
- Parameters:
bins (ndarray) – Array of bin edges for distribution.
- Returns:
Distribution of CI_HS.
- Return type:
ndarray
- get_SAD_distribution(bins)[source]¶
Get distribution counts for species abundance distribution (SAD).
- Parameters:
bins (ndarray) – Array of bin edges for abundance classes.
- Returns:
Distribution of SAD.
- Return type:
ndarray
- get_recruitment_distribution(bins)[source]¶
Get distribution counts for recruitment probabilities.
- Parameters:
bins (ndarray) – Array of bin edges for distribution.
- Returns:
Distribution of recruitment probabilities.
- Return type:
ndarray
- get_reduced_growth_distribution(bins, beta_gr=0.084)[source]¶
Get distribution counts for reduced growth values.
- Parameters:
bins (ndarray) – Array of bin edges for distribution.
beta_gr (float) – Growth reduction parameter.
- Returns:
Distribution of reduced growth.
- Return type:
ndarray
- get_survival_distribution(bins)[source]¶
Get distribution counts for survival probabilities.
- Parameters:
bins (ndarray) – Array of bin edges for distribution.
- Returns:
Distribution of survival probabilities.
- Return type:
ndarray
- plot(threshold=50, filter=1.0, scale=7.5, figsize=(22, 10))[source]¶
Plot the current state of the inventory.
- Parameters:
title – The title of the plot.
threshold (int) – Minimum abundance of conspecifics ToDo.
filter (float) – Filter out all trees below that size for inventory plot.
figsize – Figure size tuple (width, height).
- plot_map(filter=1.0, scale=7.5, figsize=None, mask=None)[source]¶
Plot only the spatial map of the inventory (trees as scatter plot).
- Parameters:
title – The title of the plot.
filter (float) – Minimum DBH of trees to be plotted.
scale (float) – Scaling factor for point size based on DBH.
figsize (tuple | None) – Figure size tuple (width, height).
mask (ndarray | None) – Boolean mask to filter which individuals to plot (optional).
- reduced_growth(beta_gr=None)[source]¶
Calculate the reduced growth using the formula from Cython. Reduced means, to only account for the exponential part of the growth function.
- Parameters:
beta_gr (float | None) – Growth reduction parameter.
- Returns:
Array of reduced growth values.
- Return type:
NDArray[np.float64]
- reduced_recruitment()[source]¶
Calculate the recruitment probability using the formula from recruitment in cython. Reduced means, to only account for the exponential part of the recruitment probability.
- Returns:
Array of recruitment probabilities.
- Return type:
ndarray[tuple[Any, …], dtype[float64]]
- property species¶
Species IDs (np.ndarray, dtype int64). This property can be updated/set. Setting it will automatically recalculate all crowding indices.
- species_abundance()[source]¶
Count the amount of individuals per species.
- Returns:
Array of individual counts per species.
- Return type:
ndarray[int32]
- species_abundance_distribution(abundance_class)[source]¶
Get the amount of species per abundance class.
- Parameters:
abundance_class (ndarray) – Array of abundance class boundaries (bins).
- Returns:
Distribution of species counts per abundance class.
- Return type:
tuple
- property status¶
Status codes (np.ndarray, dtype int32). This property can be updated/set. Setting it will automatically recalculate all crowding indices.
- survival(reduced=True)[source]¶
Calculate the reduced survival probabilities using the formula from mortality in cython. Reduced means, to only account for the exponential part of the survival probability.
- Parameters:
reduced (bool) – If True, calculate reduced survival; if False, apply background mortality.
- Returns:
Array of survival probabilities.
- Return type:
NDArray[np.float64]
- property x¶
X-coordinates of individuals (np.ndarray, dtype float64). This property can be updated/set. Setting it will automatically recalculate all crowding indices.
- property y¶
Y-coordinates of individuals (np.ndarray, dtype float64). This property can be updated/set. Setting it will automatically recalculate all crowding indices.
- spatiocoexistence.crowding_indices(x, y, species, status, radius, cell_size=0.0, dbh=None, focals=None, domain_x=0.0, domain_y=0.0, num_threads=8)¶
Python wrapper for calculating crowding indices using the Cython backend. If dbh is supplied, indices are weighted by basal area (BA). If trees are closer than 0.5 metres, they are treated as if 0.5 metres apart. Periodic boundary conditions are assumed. If focal individuals are supplied, only these are considered.
- Parameters:
x (const double[:]) – x-coordinates of individuals.
y (const double[:]) – y-coordinates of individuals.
species (const long[:]) – Species IDs.
status (const int[:]) – Status codes.
radius (const double) – Neighborhood radius.
cell_size (double) – Grid cell size (optional).
dbh (const double[:]) – Diameter at breast height (optional).
focals (const long[:]) – Indices of focal individuals (optional).
domain_x (double) – Domain size in x (optional).
domain_y (double) – Domain size in y (optional).
num_threads (int) – Number of threads for parallel computation (optional).
- Returns:
Tuple of arrays (CI_CS, CI_HS, CI_CS_dead, CI_HS_dead).
- Return type:
tuple[array, array, array, array]