Ejemplo n.º 1
0
    def get_decay_ops(self, dom_decay_op, slow_decay_op, slow_mixing_op,
                      inventory, parameters,
                      historical_mean_annual_temp=False):
        """Prepares dead organic matter decay bulk matrix operations.

        Args:
            dom_decay_op (int): Handle for a block of matrices as
                allocated by the :py:func:`allocate_op` function. Used to
                compute dom decay operations.
            slow_decay_op (int): Handle for a block of matrices as
                allocated by the :py:func:`allocate_op` function. Used to
                compute slow pool decay operations.
            slow_mixing_op (int): Handle for a block of matrices as
                allocated by the :py:func:`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. See:
                :py:func:`libcbm.model.cbm_variables.initialize_inventory`
                for a compatible definition
            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.
        """
        i = data_helpers.unpack_ndarrays(inventory)
        p = data_helpers.unpack_ndarrays(parameters)
        n = i.spatial_unit.shape[0]
        opIds = (ctypes.c_size_t * (3))(
            *[dom_decay_op, slow_decay_op, slow_mixing_op])
        spatial_unit = data_helpers.get_nullable_ndarray(
            i.spatial_unit, dtype=ctypes.c_int)

        mean_annual_temp = \
            data_helpers.get_nullable_ndarray(
                p.mean_annual_temp) \
            if "mean_annual_temp" in p.__dict__ else None

        if mean_annual_temp is not None:
            # If the mean annual temperature is specified, then omit the
            # spatial unit, whose only purpose in the context of the decay
            # routine is to fetch the mean annual temperature value from
            # the CBM defaults database
            spatial_unit = None

        self.handle.call(
            "LibCBM_GetDecayOps", opIds, n, spatial_unit,
            historical_mean_annual_temp, mean_annual_temp)
Ejemplo n.º 2
0
    def get_merch_volume_growth_ops(self, growth_op, overmature_decline_op,
                                    classifiers, inventory, pools,
                                    state_variables):
        """Computes CBM merchantable growth as a bulk matrix operation.

        Args:
            growth_op (int): Handle for a block of matrices as allocated by
                the :py:func:`AllocateOp` function. Used to compute merch
                volume growth operations.
            overmature_decline_op (int): Handle for a block of matrices as
                allocated by the :py:func:`AllocateOp` function. Used to
                compute merch volume growth operations.
            classifiers (pandas.DataFrame): matrix of classifier ids
                associated with yield tables.
            inventory (object): Used by this function to find correct spatial
                parameters from the set of merch volume growth parameters.
                Will not be modified by this function. See:
                :py:func:`libcbm.model.cbm_variables.initialize_inventory`
                for a compatible definition.
            pools (numpy.ndarray or pandas.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 (pandas.DataFrame): simulation variables which
                define all non-pool state in the CBM model.  This function
                call will not alter this parameter. See:
                :py:func:`libcbm.model.cbm_variables.initialize_cbm_state_variables`
                for a compatible definition
        """
        n = pools.shape[0]
        poolMat = LibCBM_Matrix(data_helpers.get_ndarray(pools))

        opIds = (ctypes.c_size_t * (2))(*[growth_op, overmature_decline_op])
        i = data_helpers.unpack_ndarrays(inventory)
        classifiers_mat = LibCBM_Matrix_Int(
            data_helpers.get_ndarray(classifiers))
        v = data_helpers.unpack_ndarrays(state_variables)

        last_disturbance_type = data_helpers.get_nullable_ndarray(
            v.last_disturbance_type, dtype=ctypes.c_int)
        time_since_last_disturbance = data_helpers.get_nullable_ndarray(
            v.time_since_last_disturbance, dtype=ctypes.c_int)
        growth_multiplier = data_helpers.get_nullable_ndarray(
            v.growth_multiplier, dtype=ctypes.c_double)
        growth_enabled = data_helpers.get_nullable_ndarray(
            v.growth_enabled, dtype=ctypes.c_int)

        self.handle.call(
            "LibCBM_GetMerchVolumeGrowthOps", opIds, n, classifiers_mat,
            poolMat, v.age, i.spatial_unit, last_disturbance_type,
            time_since_last_disturbance, growth_multiplier, growth_enabled)
Ejemplo n.º 3
0
    def advance_spinup_state(self, inventory, variables, parameters):
        """Advances spinup state variables through one spinup step.

        Args:
            inventory (object): CBM inventory data. Will not be modified by
                this function. See:
                :py:func:`libcbm.model.cbm.cbm_variables.initialize_inventory`
                for a compatible definition
            variables (object): Spinup working variables.  Defines all
                non-pool simulation state during spinup.  See:
                :py:func:`libcbm.model.cbm.cbm_variables.initialize_spinup_variables`
                for a compatible definition
            parameters (object): spinup parameters. See:
                :py:func:`libcbm.model.cbm.cbm_variables.initialize_spinup_parameters`
                for a compatible definition

        Returns:
            int: The number of stands finished running the spinup routine
            as of the end of this call.
        """

        i = data_helpers.unpack_ndarrays(inventory)
        p = data_helpers.unpack_ndarrays(parameters)
        v = data_helpers.unpack_ndarrays(variables)
        n = i.spatial_unit.shape[0]

        # If return_interval, min_rotations, max_rotations are explicitly
        # set by the user, ignore the spatial unit, which is used to set
        # default value for these 3 variables.
        return_interval = data_helpers.get_nullable_ndarray(
            p.return_interval, dtype=ctypes.c_int)
        min_rotations = data_helpers.get_nullable_ndarray(
            p.min_rotations, dtype=ctypes.c_int)
        max_rotations = data_helpers.get_nullable_ndarray(
            p.max_rotations, dtype=ctypes.c_int)
        spatial_unit = None
        if return_interval is None or min_rotations is None \
           or max_rotations is None:
            spatial_unit = data_helpers.get_nullable_ndarray(
                i.spatial_unit, dtype=ctypes.c_int)

        n_finished = self.handle.call(
            "LibCBM_AdvanceSpinupState", n, spatial_unit, return_interval,
            min_rotations, max_rotations, i.age, i.delay, v.slow_pools,
            i.historical_disturbance_type, i.last_pass_disturbance_type,
            i.afforestation_pre_type_id, v.spinup_state, v.disturbance_type,
            v.rotation, v.step, v.last_rotation_slow_C, v.growth_enabled,
            v.enabled)

        return n_finished
Ejemplo n.º 4
0
    def compute_flux(self, ops, op_processes, pools, flux, enabled=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.

        Args:
            ops (ndarray): list of matrix block ids as allocated by the
                allocate_op function.
            op_processes (ndarray): list of integers of length n_ops.
                Ids referencing flux indicator process_id definition in the
                Initialize method.
            pools (numpy.ndarray or pandas.DataFrame): matrix of shape
                n_stands by n_pools. The values in this matrix are updated by
                this function.
            flux (ndarray or pandas.DataFrame): 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 (ndarray, optional): 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.

        Raises:
            ValueError: raised when parameters passed to this function are not
                valid.
        """
        if not self.handle:
            raise AssertionError("dll not initialized")

        n_ops = len(ops)
        if len(op_processes) != n_ops:
            raise ValueError("ops and op_processes must be of equal length")
        nd_pools = data_helpers.get_ndarray(pools)
        pools_mat = LibCBM_Matrix(nd_pools)

        nd_flux = data_helpers.get_ndarray(flux)
        flux_mat = LibCBM_Matrix(nd_flux)

        ops_p = ctypes.cast(
            (ctypes.c_size_t*n_ops)(*ops), ctypes.POINTER(ctypes.c_size_t))
        op_process_p = ctypes.cast(
            (ctypes.c_size_t*n_ops)(*op_processes),
            ctypes.POINTER(ctypes.c_size_t))
        enabled = data_helpers.get_nullable_ndarray(
            enabled, dtype=ctypes.c_int)

        self.handle.call(
            "LibCBM_ComputeFlux", ops_p, op_process_p, n_ops, pools_mat,
            flux_mat, enabled)
Ejemplo n.º 5
0
    def compute_pools(self, ops, pools, enabled=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.

        Args:
            ops (ndarray): list of matrix block ids as allocated by the
                :py:func:`allocate_op` function.
            pools (numpy.ndarray or pandas.DataFrame): matrix of shape
                n_stands by n_pools. The values in this matrix are updated by
                this function.
            enabled (ndarray, optional): 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.

        """
        n_ops = len(ops)
        nd_pools = data_helpers.get_ndarray(pools)
        pool_mat = LibCBM_Matrix(nd_pools)
        ops_p = ctypes.cast(
            (ctypes.c_size_t*n_ops)(*ops), ctypes.POINTER(ctypes.c_size_t))

        self.handle.call(
            "LibCBM_ComputePools", ops_p, n_ops, pool_mat,
            data_helpers.get_nullable_ndarray(enabled, dtype=ctypes.c_int))