libcbm core functionality¶
Dataframe abstraction¶
libcbm has an abstraction layer for dataframes for isolating interactions with external libraries such as numpy, pandas and dask. Internally libcbm functionality calls this abstraction layer rather than the 3rd party libraries directly.
Dataframe¶
- class libcbm.storage.dataframe.DataFrame¶
DataFrame is a wrapper for one of several underlying storage types which presents a limited interface for internal usage by libcbm
- abstract add_column(series: Series, index: int) None ¶
Add a column to the dataframe based on the provided named series.
- abstract at(index: int) dict ¶
get the row at the specified 0 based sequential index as a row dictionary
- abstract property backend_type: BackendType¶
get the backend storage type
- abstract property columns: list[str]¶
get the list of column names
- abstract evaluate_filter(expression: str) Series ¶
Use a filter expression to produce a true/false series
- Parameters:
expression (str) – the boolean expression in terms of dataframe column names and constant values
- Returns:
a boolean series
- Return type:
- abstract filter(arg: Series) DataFrame ¶
filter this dataframe with a boolean series of length n_rows. Rows corresponding to true in the specified series are returned as a new dataframe.
- abstract map(arg: dict) DataFrame ¶
Apply the specified mapping dictionary on every element of this dataframe to project a new dataframe with updated values. The results has the same number of rows, columns and same column names. If any value in this dataframe is not present in the supplied dictionary an error will be raised.
- abstract multiply(series: Series) DataFrame ¶
Multiply this dataframe elementwise by the specified series along the row axis. An error is raised if the series length is not the same as the number of rows in this dataframe. Returns new DataFrame
- abstract property n_cols: int¶
return the number of columns in this dataframe
- abstract property n_rows: int¶
return the number of rows in this dataframe
- abstract sort_values(by: str, ascending: bool = True) DataFrame ¶
Return a sorted version of this dataframe
- Parameters:
by (str) – a single column name to sort by
ascending (bool, optional) – sort ascending (when True) or descending (when false) by the column name. Defaults to True.
- Returns:
a sorted dataframe
- Return type:
- abstract take(indices: Series) DataFrame ¶
Create a new dataframe where the new dataframe’s rows are the row indicies in the indicies argument.
- abstract to_numpy(make_c_contiguous=True) ndarray ¶
Return a reference to the data stored in the dataframe as a numpy array if possible. Intended to be used with uniformly-typed, numeric dataframes only, and unintended effects, or errors may be raised if this is not the case.
- abstract to_pandas() DataFrame ¶
return the data in this dataframe as a pandas dataframe.
- abstract zero()¶
Set all values in this dataframe to zero
- libcbm.storage.dataframe.concat_data_frame(data: list[DataFrame], backend_type: BackendType | None = None) DataFrame ¶
Concatenate dataframes along the row axis.
- Parameters:
data (list[DataFrame]) – dataframes to concatenate
backend_type (BackendType, optional) – backend storage type of the resulting dataframe. If unspecified the backend type of the first DataFrame in data is used. Defaults to None.
- Returns:
concatenated dataframe
- Return type:
- libcbm.storage.dataframe.concat_series(series: list[Series], backend_type: BackendType | None = None) Series ¶
Concatenate series into a single series.
- Parameters:
series (list[Series]) – list of series to concatenate
backend_type (BackendType, optional) – backend storage type of the resulting series. If unspecified the backend type of the first Series in data is used. Defaults to None. Defaults to None.
- Returns:
concatenated series
- Return type:
- libcbm.storage.dataframe.convert_dataframe_backend(df: DataFrame, backend_type: BackendType) DataFrame ¶
Change the backend storage type of an existing DataFrame object.
If the backend type of the specified dataframe is the same as the specified backend type, the dataframe is simply returned.
- Parameters:
df (DataFrame) – a DataFrame object
backend_type (BackendType) – the backend type
- Raises:
NotImplementedError – the specified backend_type has not been implemented.
- Returns:
the converted DataFrame
- Return type:
- libcbm.storage.dataframe.convert_series_backend(series: Series, backend_type: BackendType) Series ¶
Change the backend storage type of an existing Series object.
If the backend type of the specified series is the same as the specified backend type, the series is simply returned.
- Parameters:
series (Series) – a Series object
backend_type (BackendType) – the backend type
- Raises:
NotImplementedError – the specified backend_type has not been implemented.
- Returns:
The converted series
- Return type:
- libcbm.storage.dataframe.from_numpy(data: dict[str, ndarray]) DataFrame ¶
Create a DataFrame object from a dictionary of name, numpy array pairs.
Each array is expected to be single dimension and of the same length.
- Parameters:
data (dict[str, np.ndarray]) – name array pairs
- Returns:
the Dataframe instance
- Return type:
- libcbm.storage.dataframe.from_pandas(df: DataFrame) DataFrame ¶
Create a DataFrame object with a pandas dataframe
- Parameters:
df (pd.DataFrame) – a pandas dataframe
- Returns:
a DataFrame instance
- Return type:
- libcbm.storage.dataframe.from_series_dict(data: dict[str, Series | SeriesDef], nrows: int, back_end: BackendType) DataFrame ¶
Initialize a dataframe object from a dictionary of named Series or SeriesDef objects. The dictionary keys are used as the columns in the resulting dataframe.
- Parameters:
data (dict[str, Union[Series, SeriesDef]]) – dictionary of named Series or SeriesDef objects.
nrows (int) – the number of rows
back_end (BackendType) – backend storage type of the resulting dataframe
- Returns:
initialized dataframe
- Return type:
- libcbm.storage.dataframe.from_series_list(data: list[Series | SeriesDef], nrows: int, back_end: BackendType) DataFrame ¶
initialize a dataframe from a list of Series or SeriesDef objects
- Parameters:
nrows (int) – number of rows, this parameter is used when SeriesDef object are provided, and otherwise ignored.
back_end (BackendType) – backend storage type of the resulting dataframe
- Returns:
dataframe object
- Return type:
- libcbm.storage.dataframe.get_uniform_backend(data: list[DataFrame | Series], backend_type: BackendType | None = None) tuple[BackendType, list[DataFrame | Series]] ¶
Convert the backend type of all specified dataframes, or series. Also used to assert backend type uniformity of collections of these objects.
- Parameters:
data (list[Union[DataFrame, Series]]) – list of DataFrame or Series objects to convert or on which assert uniformity.
backend_type (BackendType, optional) – the required backend type of the output. This must be specified if the provided items in data are non-uniform. Defaults to None.
- Raises:
ValueError – backend_type was not specified, and the provided dataframe or series objects were non-uniform.
- Returns:
_description_
- Return type:
tuple[BackendType, list[Union[DataFrame, Series]]]
- libcbm.storage.dataframe.indices_nonzero(series: Series) Series ¶
return a series of the 0 based sequential index of non-zero values in the specfied series
- libcbm.storage.dataframe.is_null(series: Series) Series ¶
returns an Series of True where any value in the specified series is null, None, or NaN, and otherwise False
- libcbm.storage.dataframe.logical_and(s1: Series, s2: Series, backend_type: BackendType | None = None) Series ¶
take the elementwise logical and of 2 series
- Parameters:
s1 (Series) – arg1 of the logical and
s2 (Series) – arg2 of the logical and
backend_type (BackendType, optional) – backend type of the result. If not specified the backend type of the first arg is used. Defaults to None.
- Returns:
result
- Return type:
- libcbm.storage.dataframe.logical_not(series: Series) Series ¶
Take the logical not of the specified series
- libcbm.storage.dataframe.logical_or(s1: Series, s2: Series, backend_type: BackendType | None = None) Series ¶
take the elementwise logical or of 2 series
- Parameters:
s1 (Series) – arg1 of the logical or
s2 (Series) – arg2 of the logical or
backend_type (BackendType, optional) – backend type of the result. If not specified the backend type of the first arg is used. Defaults to None.
- Returns:
result
- Return type:
- libcbm.storage.dataframe.make_boolean_series(init: bool, size: int, backend_type: BackendType.numpy) Series ¶
Make an initialized boolean series
- Parameters:
init (bool) – True or False, the entire Series is assigned this value.
size (int) – length of the resulting series
backend_type (BackendType) – backend type of the result. If not specified then BackendType.numpy is used. Defaults to None.
- Returns:
the boolean series
- Return type:
- libcbm.storage.dataframe.numeric_dataframe(cols: list[str], nrows: int, back_end: BackendType, init: float = 0.0) DataFrame ¶
Make an initialized numeric-only dataframe
- Parameters:
cols (list[str]) – column names
nrows (int) – number of rows
back_end (BackendType) – backend storage type of the resulting dataframe
init (float, optional) – initialization value. Defaults to 0.0.
- Returns:
initialized numeric dataframe
- Return type:
Series¶
- class libcbm.storage.series.Series¶
Series is a wrapper for one of several underlying storage types which presents a limited interface for internal usage by libcbm.
- abstract all() bool ¶
return True if all values in this series are non-zero
- Returns:
True if all elements are non-zero and otherwise false
- Return type:
bool
- abstract any() bool ¶
return True if at least one value in this series is non-zero
- Returns:
- true if one or more element is non-zero, and
otherwise false
- Return type:
bool
- abstract as_type(type_name: str) Series ¶
Return a copied series with all elements converted to the specified type. A ValueError is raised if it is not possible to convert any element contained in this series to the specified type
- Parameters:
type_name (str) – the type to convert to
- Returns:
the type converted series
- Return type:
- abstract assign(value: Series | Any, indices: Series | None = None)¶
Assign a single value, or a Series to a subset or to the entirety of this series
- abstract at(idx: int) Any ¶
Gets the value at the specified sequential index
- Parameters:
idx (int) – the index
- Returns:
The value at the index
- Return type:
Any
- abstract property backend_type: BackendType¶
gets the BackendType of this series
- Returns:
the backend type of the series
- Return type:
- abstract cumsum() Series ¶
Compute the cumulative sums of the series. Return value is of equal length as this series.
- Returns:
the cumulative sum
- Return type:
- abstract property data: ndarray | Series¶
get a reference to the underlying storage.
- Returns:
reference to the series storage
- Return type:
Union[np.ndarray, pd.Series]
- abstract filter(arg: Series) Series ¶
Return a new series of the elements corresponding to the true values in the specified arg
- abstract indices_nonzero() Series ¶
Get the indices of values that are non-zero in this series
- Returns:
- integer series that is the index of each non zero
value in this series.
- Return type:
- abstract is_null() Series ¶
Returns true where items in this series are None, or nan
- Returns:
- boolean series indicating positions of None or nan in this
series
- Return type:
- abstract property length: int¶
Return the number of elements in this series
- Returns:
the number of elements in the series
- Return type:
int
- abstract map(arg: dict) Series ¶
Map the values in this series using the specified dictionary. The value of the returned series is the dictionary value corresponding to the dictionary key found in the input series. If any element in this series is not defined in the specified dictionary, a ValueError is raised.
- Parameters:
arg (dict) – a dictionary of map values
- Returns:
the mapped series
- Return type:
- abstract max() int | float ¶
Return the maximum value in the series
- Returns:
the maximum value in the series
- Return type:
Union[int, float]
- abstract min() int | float ¶
Return the minimum value in the series
- Returns:
the minimum value in the series
- Return type:
Union[int, float]
- abstract property name: str¶
get or set the series name
- Returns:
series name
- Return type:
str
- abstract sum() int | float ¶
get the sum of the series
- Returns:
the series sum
- Return type:
Union[int, float]
- abstract take(indices: Series) Series ¶
Return the elements of this series at the specified indices (returns a copy)
- abstract to_list() list ¶
returns a copy of the values in this series as a list
- Returns:
the series as a python list
- Return type:
list
- abstract to_numpy() ndarray ¶
Get the series values as a numpy array. This is a reference to the underlying memory where possible. The following summarize this:
* pandas backend: a reference is returned * numpy backend (mixed column types): a reference is returned * numpy backend (2d matrix storage): a copy is returned
- Returns:
- the series values as a numpy array, either as a
reference or copy
- Return type:
np.ndarray
- abstract to_numpy_ptr() pointer ¶
Get a ctypes pointer to this series underlying numpy array. In the case of numpy backend 2d matrix storage, a pointer to a copy of the series value is returned.
- Returns:
a ctypes pointer for the numpy array
- Return type:
ctypes.pointer
- class libcbm.storage.series.SeriesDef(name: str, init: Any, dtype: str)¶
Information/Factory class to allocate initialized series for Series and DataFrame construction
- make_series(len: int, back_end: BackendType) Series ¶
make a series
- Parameters:
len (int) – the number of elements
back_end (BackendType) – the backend type
- Returns:
initialized series
- Return type:
- libcbm.storage.series.allocate(name: str, len: int, init: Any, dtype: str, back_end: BackendType) Series ¶
Allocate a series
- Parameters:
name (str) – series name
len (int) – number of elements
init (Any) – value to assign all elements
dtype (str) – data type
back_end (BackendType) – backend type
- Returns:
initialzed Series
- Return type:
- libcbm.storage.series.from_list(name: str, data: list) Series ¶
method to allocate a numpy-backed series from a python list, intended primarily for unit and integration testing purposes
- Parameters:
name (str) – name of the series
data (list) – series data
- Returns:
a series
- Return type:
- libcbm.storage.series.from_numpy(name: str, data: ndarray) Series ¶
Initialize a series with a numpy array
- Parameters:
name (str) – the name of the resulting series
data (np.ndarray) – the series data
- Returns:
the initialized series
- Return type:
- libcbm.storage.series.from_pandas(series: Series, name: str | None = None) Series ¶
Initialize a series with a pandas Series.
- Parameters:
series (pd.Series) – the pandas Series
name (str, optional) – The name of the resulting series. If unspecified and the specified pandas series has a defined name that is used in the result. Defaults to None.
- Returns:
the initialized series
- Return type:
- libcbm.storage.series.range(name: str, start: int, stop: int, step: int, dtype: str, back_end: BackendType) Series ¶
Create a series using a range of values using the same methodolgy as numpy.arange
- Parameters:
name (str) – the name of the series
start (int) – start of interval
stop (int) – end of interval
step (int) – spacing between values
dtype (str) – data type
back_end (BackendType) – backend storage type
- Returns:
initialize series with range of values
- Return type:
Backends¶
- class libcbm.storage.backends.BackendType(value)¶
Enumeration of the supported dataFrame, series backend types in libcbm
- numpy = 1¶
the numpy backend type
- pandas = 2¶
the pandas backend type
- libcbm.storage.backends.get_backend(backend_type: BackendType)¶
get the implementation of a backend type
- Parameters:
backend_type (BackendType) – one of the supported types
- Raises:
NotImplementedError – the specified value is not supported or implemented
- Returns:
the backend
- Return type:
module
C++ library wrapper functions¶
The libcbm core functions are pool and flux functions that are generally useful for CBM-like models.
- class libcbm.wrapper.libcbm_ctypes.LibCBM_ctypes(dll_path: str)¶
Wrapper for the core low level functions in the libcbm C/C++ library
- Parameters:
dll_path (str) – path to the compiled LibCBM dll on Windows, or compiled LibCBM .so file for Linux
- class libcbm.wrapper.libcbm_error.LibCBM_Error¶
Wrapper for low level C/C++ LibCBM structure of the same name. Stores string error message when they occur in library functions.
- getError() int ¶
Gets the error code from an error returned by a library function. If no error occurred this is zero.
- getErrorMessage() str ¶
Gets the error message from an error returned by a library function. If no error occurred this is an empty string.
- class libcbm.wrapper.libcbm_handle.LibCBMHandle(dll_path: str, config: str)¶
Initialize a libcbm handle with the specified pools, and flux indicators.
- Parameters:
dll_path (str) – path to the libcbm compiled library
config (str) –
a json formatted string containing configuration for libcbm pools and flux definitions.
The number of pools, and flux indicators defined here, corresponds to other data dimensions used during the lifetime of this instance:
The number of pools here defines the number of columns in the pool value matrix used by several other libCBM functions
The number of flux_indicators here defines the number of columns in the flux indicator matrix in the ComputeFlux method.
The number of pools here defines the number of rows, and the number of columns of all matrices allocated by the
AllocateOp()
function.
Example:
{ "pools": [ {"id": 1, "index": 0, "name": "pool_1"}, {"id": 2, "index": 1, "name": "pool_2"}, ... {"id": n, "index": n-1, "name": "pool_n"}], "flux_indicators": [ { "id": 1, "index": 0, "process_id": 1, "source_pools": [1, 2] "sink_pools": [3] }, { "id": 2, "index": 1, "process_id": 1, "source_pools": [1, 2] "sink_pools": [3] }, ... ] }
Pool/Flux Indicators configuration rules:
ids may be any integer, but are constrained to be unique within the set of pools.
indexes must be the ordered set of integers from 0 to n_pools - 1.
For flux indicator source_pools and sink_pools, list values correspond to id values in the collection of pools
- call(func_name: str, *args)¶
Call a libcbm C/C++ function. The specified args are passed as the arguments to the named function.
- Parameters:
func_name (str) – The name of the libcbm function
- Raises:
RuntimeError – if an error is detected in the low level library it is re-raised here.
- Returns:
- returns the value returned by the specified low level
function.
- Return type:
variant
- class libcbm.wrapper.libcbm_matrix.LibCBM_Matrix_Base(matrix: ndarray, matrix_np_type: dtype, matrix_c_type: type)¶
Wrapper for low level C/C++ LibCBM structures LibCBM_Matrix and LibCBM_Matrix_Int. Used to pass a 2 dimensional numpy matrix or single valued array as raw memory to LibCBM.
- Parameters:
matrix (numpy.ndarray) – a 2 dimensional numpy array, or single value
matrix_np_type (numpy.dtype) – the numpy dtype
matrix_c_type (type) – the ctypes type
- Raises:
ValueError – matrix must have either 2 dimensions or be a scalar
ValueError – matrix must be of the correct type
- class libcbm.wrapper.libcbm_matrix.LibCBM_Matrix(matrix: ndarray)¶
64 bit float specialization of
libcbm.wrapper.libcbm_matrix.LibCBM_Matrix_Base
- Parameters:
matrix (numpy.ndarray) – a 2 dimensional numpy array, or single value
- class libcbm.wrapper.libcbm_matrix.LibCBM_Matrix_Int(matrix: ndarray)¶
32 bit int specialization of
libcbm.wrapper.libcbm_matrix.LibCBM_Matrix_Base
- Parameters:
matrix (numpy.ndarray) – a 2 dimensional numpy array, or single value
- class libcbm.wrapper.libcbm_wrapper.LibCBMWrapper(handle: LibCBMHandle)¶
Exposes low level ctypes wrapper to regular python, for the core libcbm functions.
- Args (LibCBMHandle): handle
for the underlying dll/so compiled library
- allocate_op(size: int) int ¶
Allocates storage for matrices, returning an id for the allocated block.
- Parameters:
size (int) – The number of elements in the allocated matrix block index, which corresponds to the number of stands that can be processed with this matrix block
- Raises:
AssertionError – raised if the Initialize method was not called prior to this method.
RuntimeError – if an error is detected in libCBM, it will be re-raised with an appropriate error message.
- Returns:
the id for an allocated block of matrices
- Return type:
int
- compute_flux(ops: list, op_processes: list, pools: DataFrame, flux: DataFrame, enabled: Series | None = None)¶
Computes and tracks flows between pool values for all stands.
Performs the same operation as compute_pools, except that the fluxes are tracked in the specified flux parameter, according to the flux_indicators configuration passed to the LibCBM initialize method.
- Raises:
ValueError – raised when parameters passed to this function are not valid.
- Parameters:
ops (list) – list of matrix block ids as allocated by the allocate_op function.
op_processes (list) – list of integers of length n_ops. Ids referencing flux indicator process_id definition in the Initialize method.
pools (DataFrame) – dataframe containing matrix of shape n_stands by n_pools. The values in this matrix are updated by this function.
flux (DataFrame) – dataframe containing matrix of shape n_stands by n_flux_indicators. The values in this matrix are updated by this function according to the definition of flux indicators in the configuration and the flows that occur in the specified operations.
enabled (Series, optional) – optional int or bool vector of length n_stands. If specified, enables or disables flows for each stand, based on the value at each stand index. A value of 0 indicates a disabled stand index, and any other value is an enabled stand index. If None, all flows are assumed to be enabled. Defaults to None.
- compute_pools(ops: list, pools: DataFrame, enabled: Series | None = None)¶
Computes flows between pool values for all stands.
Each value in the ops parameter is an id to a matrix block, and is also conceptually a list of matrixes of length n stands.
Performs the following computation:
for op in ops: for s in len(n_stands): M = op.get_matrix(s) pools[s,:] = np.matmul(pools[s,:], M)
Where get_matrix is pseudocode for an internal function returning the matrix for the op, stand index combination.
- Parameters:
ops (list) – list of matrix block ids as allocated by the
allocate_op()
function.pools (DataFrame) – matrix of shape n_stands by n_pools. The values in this matrix are updated by this function.
enabled (Series) – optional int vector of length n_stands. If specified, enables or disables flows for each stand, based on the value at each stand index. A value of 0 indicates a disabled stand index, and any other value is an enabled stand index. If None, all flows are assumed to be enabled. Defaults to None.
- free_op(op_id: int)¶
Deallocates a matrix block that was allocated by the allocate_op method.
- Parameters:
op_id (int) – The id for an allocated block of matrices.
- set_op(op_id: int, matrices: list[ndarray], matrix_index: ndarray, init: int = 0)¶
Assigns values to an allocated block of matrices.
Example:
n_stands = 3 op_id = allocate_op(n_stands) matrix_0 = np.array([ [0, 1, 0.5], [0, 0, 1.0], [1, 1, 1.0] ]) matrix_1 = np.array([ [1, 0, 0.5], [0, 0, 1.0], [1, 1, 0.5] ]) matrices = [matrix_0, matrix_1] matrix_index = [0,1,0] SetOp(op_id, matrices, matrix_index)
In this example, a pair of matrices are passed. Here the matrices are of dimension N by N where N is defined by the call to
Initialize()
.matrix_0:
p
p0
p1
…
pN
p0
1.0
0.5
0.0
0.0
p1
0.0
1.0
0.0
0.0
…
0.0
0.0
0.0
0.0
pN
0.0
0.0
0.0
0.0
matrix_1:
p
p0
p1
…
pN
p0
1.0
0.0
0.0
0.0
p1
0.5
0.5
0.0
0.0
…
0.0
0.0
0.0
0.0
pN
0.0
0.0
0.0
0.0
The matrices are indexed according to the following table:
Stand_index
Matrix_index
0
0
1
1
2
0
- related functions:
allocate_op()
,
- Parameters:
op_id (int) – The id for an allocated block of matrices
matrices (list) – a list of n by 3 ndarray matrices which are coordinate format triplet values (row,column,value). All defined row/column combinations are set with the value, and all other matrix cells are assumed to be 0.
matrix_index (ndarray) – an array of length n stands where the value is an index to a matrix in the specified list of matrices provided to this function.
init (int) – if set to 0 matrices are initialized with zeros, and if 1 the matrix diagonals are initialized to 1 (identity) prior to assigning matrix values. Other values will result in an error.
- related functions:
- set_op_repeating(op_id: int, coordinates: ndarray, values: ndarray, matrix_index: ndarray, init: int = 0)¶
Assigns the specified values associated with repeating coordinates to an allocated block of matrices. Note the full set of coordinates are not required, and this layout is efficient for sparse coordinate-values.
The parameter init first initializes any value not specified in the value/coordinates with the init value, this defaults to zero.
Example Data Layout:
coordinates = [ [0, 1], [0, 2], [1, 2] ] values = [ [0.20, 0.40, 0.10], [0.23, 0.42, 0.73], [0.12, 0.99, 0.13] ] matrix_index = [0, 1, 1, 2, 0]
Result of example (dense matrix form):
stand0_matrix = [ [0.00, 0.20, 0.40], [0.00, 0.00, 0.10], [0.00, 0.00, 0.00], ] stand1_matrix = [ [0.00, 0.23, 0.42], [0.00, 0.00, 0.73], [0.00, 0.00, 0.00], ] stand2_matrix = [ [0.00, 0.23, 0.42], [0.00, 0.00, 0.73], [0.00, 0.00, 0.00], ] stand3_matrix = [ [0.00, 0.12, 0.99], [0.00, 0.00, 0.13], [0.00, 0.00, 0.00], ] stand4_matrix = [ [0.00, 0.20, 0.40], [0.00, 0.00, 0.10], [0.00, 0.00, 0.00], ]
- Parameters:
op_id (int) – The id for an allocated block of matrices
coordinates (numpy.ndarray) – matrix of integer coordinates corresponding to each column of the values. Shape (n_coordinate, 2)
values (numpy.ndarray) – matrix of float values for each matrix to assign. Shape (n_matrices, n_coordinate).
matrix_index (ndarray) – an array of length n stands where the value is an index to a row in the specifies values matrix
init (int) – if set to 0 matrices are initialized with zeros, and if 1 the matrix diagonals are initialized to 1 (identity) prior to assigning matrix values. Other values will result in an error.
CBM3-Specific C++ library wrapper functions¶
The CBM core functionality is the set of low level functions that compose the CBM model.
- libcbm.wrapper.cbm.cbm_ctypes.initialize_CBM_ctypes(dll)¶
Extends a
libcbm.wrapper.libcbm_ctypes.LibCBM_ctypes
object by wrapping the CBM specific functions contained in the low level c/c++ library.- Parameters:
libcbm_ctypes (LibCBM_ctypes) – An instance the core LibCBM ctypes wrapper.
- class libcbm.wrapper.cbm.cbm_wrapper.CBMWrapper(handle: LibCBMHandle, config: str)¶
Exposes low level ctypes wrapper to regular python, for CBM specific libcbm functions.
The base class is
libcbm.wrapper.libcbm_ctypes.LibCBM_ctypes
- Parameters:
handle (LibCBMHandle) – handle to the low level function library
config (str) –
A json formatted string containing CBM configuration.
See
libcbm.model.cbm.cbm_defaults
for construction of the “cbm_defaults” value, andlibcbm.model.cbm.cbm_config
for helper methods.Example:
{ "cbm_defaults": {"p1": {}, "p2": {}, ..., "pN": {}}, "classifiers": [ {"id": 1, "name": "a"}, {"id": 2, "name": "b"}, {"id": 3, "name": "c"} ], "classifier_values": [ { "id": 1, "classifier_id": 1, "value": "a1", "description": "a1" }, { "id": 2, "classifier_id": 2, "value": "b2", "description": "b2" }, { "id": 3, "classifier_id": 3, "value": "c1", "description": "c1" } ], "merch_volume_to_biomass": { 'db_path': './cbm_defaults.db', 'merch_volume_curves': [ { 'classifier_set': { 'type': 'name', 'values': ['a1','b2','c1'] }, 'components': [ { 'species_id': 1, 'age_volume_pairs': [(age0, vol0), (age1, vol0), (ageN, volN)] }, { 'species_id': 2, 'age_volume_pairs': [(age0, vol0), (age1, vol0), (ageN, volN)] } ] } ] } }
- advance_spinup_state(inventory: DataFrame, variables: DataFrame, parameters: DataFrame) int ¶
Advances spinup state variables through one spinup step.
- Parameters:
- Returns:
The number of stands finished running the spinup routine as of the end of this call.
- Return type:
int
- advance_stand_state(classifiers: DataFrame, inventory: DataFrame, state_variables: DataFrame, parameters: DataFrame)¶
Advances CBM stand variables through a timestep based on the current simulation state.
- Parameters:
classifiers (DataFrame) – classifier values associated with the inventory
inventory (DataFrame) – CBM inventory data. Will not be modified by this function.
state_variables (DataFrame) – simulation variables which define all non-pool state in the CBM model. Altered by this function call.
parameters (DataFrame) – Read-only parameters used in a CBM timestep.
- end_spinup_step(pools: DataFrame, variables: DataFrame)¶
Applies end-of-timestep changes to the spinup state
- Parameters:
pools (DataFrame) – matrix of shape n_stands by n_pools. The values in this matrix are used to compute a criteria for exiting the spinup routine. The biomass pools are also zeroed for historical and last pass disturbances.
variables (DataFrame) – Spinup working variables. Defines all non-pool simulation state during spinup. Set to an end-of-timestep state by this function.
- end_step(state_variables: DataFrame)¶
Applies end-of-timestep changes to the CBM state
- Parameters:
state_variables (DataFrame) – simulation variables which define all non-pool state in the CBM model. This function call will alter this variable with end-of-step changes.
- get_decay_ops(dom_decay_op: int, slow_decay_op: int, slow_mixing_op: int, inventory: DataFrame, parameters: DataFrame, historical_mean_annual_temp: bool = False)¶
Prepares dead organic matter decay bulk matrix operations.
- Parameters:
dom_decay_op (int) – Handle for a block of matrices as allocated by the
allocate_op()
function. Used to compute dom decay operations.slow_decay_op (int) – Handle for a block of matrices as allocated by the
allocate_op()
function. Used to compute slow pool decay operations.slow_mixing_op (int) – Handle for a block of matrices as allocated by the
allocate_op()
function. Used to compute slow pool mixing operations.inventory (object) – CBM inventory data. Used by this function to find correct parameters from the set of decay parameters passed to library initialization. Will not be modified by this function.
parameters (object) – parameters for this timestep
historical_mean_annual_temp (bool, optional) – If set to true, the historical default mean annual temperature is used. This is intended for spinup. If explicit mean annual temperature is provided via the parameters argument, this parameter will be ignored, and the explicit mean annual temp will be used. Defaults to False.
- get_disturbance_ops(disturbance_op: int, inventory: DataFrame, parameters: DataFrame)¶
Sets up CBM disturbance matrices as a bulk matrix operations.
- Parameters:
disturbance_op (int) – Handle for a block of matrices as allocated by the
AllocateOp()
function. Used to compute disturbance event pool flows.inventory (DataFrame) – CBM inventory data. Used by this function to find correct parameters from the set of disturbance parameters passed to library initialization. Will not be modified by this function.
parameters (DataFrame) – Read-only parameters used to set disturbance type id to fetch the appropriate disturbance matrix.
- get_merch_volume_growth_ops(growth_op: int, overmature_decline_op: int, classifiers: DataFrame, inventory: DataFrame, pools: DataFrame, state_variables: DataFrame)¶
Computes CBM merchantable growth as a bulk matrix operation.
- Parameters:
growth_op (int) – Handle for a block of matrices as allocated by the
AllocateOp()
function. Used to compute merch volume growth operations.overmature_decline_op (int) – Handle for a block of matrices as allocated by the
AllocateOp()
function. Used to compute merch volume growth operations.DataFrame) (classifiers) – matrix of classifier ids associated with yield tables.
inventory (DataFrame) – Used by this function to find correct spatial parameters from the set of merch volume growth parameters. Will not be modified by this function.
pools (DataFrame) – matrix of shape n_stands by n_pools. Used by this function to compute a root increment, and also to limit negative growth increments such that a negative biomass pools are prevented. This parameter is not modified by this function.
state_variables (DataFrame) – simulation variables which define all non-pool state in the CBM model. This function call will not alter this parameter.
- get_turnover_ops(biomass_turnover_op: int, snag_turnover_op: int, inventory: DataFrame)¶
Computes biomass turnovers and dead organic matter turnovers as bulk matrix operations.
- Parameters:
biomass_turnover_op (int) – Handle for a block of matrices as allocated by the
allocate_op()
function. Used to compute biomass turnover operations.snag_turnover_op (int) – Handle for a block of matrices as allocated by the
allocate_op()
function. Used to compute dom (specifically snags) turnover operations.inventory (DataFrame) – CBM inventory data. Used by this function to find correct parameters from the set of turnover parameters passed to library initialization. Will not be modified by this function.
- initialize_land_state(inventory: DataFrame, pools: DataFrame, state_variables: DataFrame)¶
Initializes CBM state to values appropriate for after running spinup and before starting CBM stepping
- Parameters:
inventory (DataFrame) – CBM inventory data. Will not be modified by this function.
pools (DataFrame) – matrix of shape n_stands by n_pools. The values in this matrix are updated by this function for stands that have an afforestation pre-type defined.
state_variables (DataFrame) – simulation variables which define all non-pool state in the CBM model. This function call will alter this variable with CBM initial state values.