Model definition¶
The model_definition package of libcbm can be used to define a CBM-like model using python code.
Code Docs¶
- libcbm.model.model_definition.model.initialize(pool_config: list[str], flux_config: list[dict]) Iterator[CBMModel] ¶
Initialize a CBMModel for spinup or stepping
- Parameters:
pool_config (list[str]) – list of string pool identifiers.
flux_config (list[dict]) – list of flux indicator dictionary structures.
Example Pools:
["Input", "Merchantable", "OtherC"]
Example Flux indicators:
[ { "name": "NPP", "process": "Growth", "source_pools": [ "Input", ], "sink_pools": [ "Merchantable", "Foliage", "Other", "FineRoot", "CoarseRoot" ] }, { "name": "DOMEmissions", "process": "Decay", "source_pools": [ "AboveGroundVeryFast", "BelowGroundVeryFast", "AboveGroundFast", "BelowGroundFast", "MediumSoil", "AboveGroundSlow", "BelowGroundSlow", "StemSnag", "BranchSnag", ], "sink_pools": [ "CO2" ] } ]
- Yields:
Iterator[CBMModel] – instance of CBMModel
- class libcbm.model.model_definition.model.CBMModel(model_handle: ModelHandle, pool_config: list[str], flux_config: list[dict], op_processes: dict[str, int])¶
An abstraction of a Carbon budget model
- compute(cbm_vars: ModelVariables, operations: list[Operation])¶
Compute a batch of C dynamics
- Parameters:
cbm_vars (ModelVariables) – cbm variables and state
operations (list[Operation]) – a list of Operation objects as allocated by create_operation
op_process_ids (list[int]) – list of integers
- class libcbm.model.model_definition.model_matrix_ops.ModelMatrixOps(model_handel: ModelHandle, pool_names: list[str], op_process_ids: dict[str, int])¶
class for managing C flow matrices using a formatted dataframe storage scheme.
- create_operation(name: str, op_process_name: str, op_data: DataFrame, requires_reindexing: bool = True, init_value: int = 1, default_matrix_index: int | None = None)¶
- Create a C flow operation using a dataframe formatted so that each
row is an index C flow matrix.
- Parameters:
name (str) – The operations unique name. If an existing operation is stored in this instance it will be overwritten.
op_process_name (str) – The op process name used to categorize resulting C fluxes
op_data (pd.DataFrame) – the formatted dataframe containing indexed rows of matrices
requires_reindexing (bool, optional) – If set to True each time
get_operation()
is called the matrices are re-indexed according to the current simulation state. This is needed for example if timestep varying values are involved in the index. Defaults to True.init_value (int, optional) – The default value set on the diagonal of each matrix. Diagonal values specified in the parameters will overwrite this default. Defaults to 1.
default_matrix_index (Union[int, None], optional) – If simulation values are not found within the specified op_data, the specified 0 based index will be used as a default fill-value. If this value is not specified, such missing values will instead result in an error being raised. Defaults to None.
- get_operations(op_names: list[str], model_variables: ModelVariables) list[Operation] ¶
Get C flow operations for computation of C flows on the current model state stored in model_variables.
- Parameters:
op_names (list[str]) – the sequential names of the stored operations to apply (duplicates allowed)
model_variables (ModelVariables) – the current model state: pools, flux, state etc.
- Returns:
a list of C flow operations to apply
- Return type:
list[Operation]
- class libcbm.model.model_definition.model_handle.ModelHandle(wrapper: LibCBMWrapper, pools: dict[str, int], flux_indicators: list[dict])¶
Class to facilitate optimizied pool flux operations.
This is essentially a layer for simplifying the python interface to libcbm matrix processing
- compute(pools: DataFrame, flux: DataFrame, enabled: Series, operations: list[Operation]) None ¶
compute a batch of Operations
- Parameters:
pools (DataFrame) – the pools dataframe, which is updated by this function
flux (DataFrame) – the flux dataframe, which is assigned specific pool flows
enabled (Series) – a boolean series indicating that particular stands are subject to the batch of operations (when 1) or not (when 0). If zero, the corresponding pool and flux values will not be modified.
operations (list[libcbm_operation.Operation]) – the list of Operations.
- create_operation(matrices: list, fmt: str, process_id: int, matrix_index: ndarray, init_value: int = 1) Operation ¶
Create a libcbm Operation
repeating_coordinates description:
can be used to repeat the same matrix coordinates across multiple stands, with varying matrix values.
The lists of are of type [str, str, np.ndaray]
The length of each array is the number of stands
example repeating_coordinates:
[ [pool_a, pool_b, [flow_ab_0, flow_ab_1, ... flow_ab_N]], [pool_c, pool_a, [flow_ca_0, flow_ca_1, ... flow_ca_N]], ... ]
matrix_list description:
Used for cases when coordinates vary for matrices. This is a list of matrices in sparse coordinate format (COO)
example matrix_list:
[ [ [pool_a, pool_b, flow_ab], [pool_a, pool_c, flow_ac], ... ], [ [pool_b, pool_b, flow_bb], [pool_a, pool_c, flow_ac], ... ], ... ]
- Parameters:
matrices (list) – a list of matrix values. The required format is dependant on the fmt parameter.
fmt (str) – matrix value format. Can be either of: “repeating_coordinates” or “matrix_list”
process_id (int) – flux tracking category id. Fluxes associated with this Operation will fall under this category.
matrix_index (np.ndarray) – an array whose length is the same as the number of stands being simulated. Each value in the array is the index to one of the matrices defined in the matrix_list parameter.
init_value (int, optional) – The default value set on the diagonal of each matrix. Diagonal values specified in the matrices parameters will overwrite this default. Defaults to 1.
- Raises:
ValueError – an unknown value for fmt was specified.
- Returns:
initialized Operation object
- Return type:
libcbm_operation.Operation
- class libcbm.model.model_definition.model_variables.ModelVariables(data: dict[str, DataFrame])¶
Container for multiple named dataframes. Dataframes are assumed to be row-index-aligined
- static from_pandas(frames: dict[str, DataFrame]) ModelVariables ¶
Assemble a ModelVariables instance from a collection of pandas DataFrames
- get_collection() dict[str, DataFrame] ¶
Get a dictionary containing named references to the dataframes stored in this collection
- to_pandas() dict[str, DataFrame] ¶
return the dataframes in this collection as a dictionary of named pandas dataframes. This may result in a copy if the underlying dataframe storage backend is not pandas
- class libcbm.model.model_definition.output_processor.ModelOutputProcessor¶
Stores results by timestep using the libcbm.storage.dataframe.DataFrame abstraction. This is not strictly required for running, as the simulation state variables are accessible via standard interfaces such as pandas and numpy.
Note the numpy and pandas DataFrame backends will store information in memory limiting the scalability of this method.
- append_results(t: int, results: ModelVariables)¶
Append results to the output processor. Values from the specified results will be concatenated with previous timestep results.
Two columns will be added to the internally stored dataframes to identify rows: identifier and timestep.
- Parameters:
t (int) – the timestep
results (ModelVariables) – collection of cbm variables and state for the timestep.
- get_results() ModelVariables ¶
Return the collection of accumulated results
- Returns:
collection of dataframes holding results.
- Return type:
dict[str, DataFrame]
- class libcbm.model.model_definition.spinup_engine.SpinupState(value)¶
The possible spinup states for stands during spinup
- libcbm.model.model_definition.spinup_engine.advance_spinup_state(spinup_state: Series, age: Series, delay_step: Series, final_age: Series, delay: Series, return_interval: Series, rotation_num: Series, min_rotations: Series, max_rotations: Series, last_rotation_slow: Series, this_rotation_slow: Series, enabled: Series) ndarray ¶
Run the vectorized spinup finite state machine. Passed values are not modified by this function.
- Parameters:
spinup_state (Series) – The current spinup state value. See
SpinupState
age (Series) – The age.
delay_step (Series) – The spinup delay step, when in the Delay state
final_age (Series) – The final age at the end of spinup, which is also known as the inventory age in CBM
delay (Series) – The number of delay steps to perform in spinup.
return_interval (Series) – The number of years between historical disturbance rotations.
rotation_num (Series) – The number of rotations already performed
min_rotations (Series) – The minimum number of rotations to perform
max_rotations (Series) – The maximum number of rotations to perform
last_rotation_slow (Series) – The sum of Slow C pools at the end of the last rotation, prior to historical disturbance.
this_rotation_slow (Series) – The current sum of Slow C pools.
enabled (Series) – A boolean flag indicating the corresponding stands are finished spinup (when 0), or spinup is ongoing (when 1)
- Returns:
The array of updated SpinupState.
- Return type:
np.ndarray