forest module

This module implements functions for building and running the wood supply simulation models.

The ws3.forest.ForestModel and ws3.forest.DevelopmentType classes constitute the core functional units of this module, and of the ws3 package in general.

class forest.Action(code: str, targetage: int | None = None, descr: str = '', lockexempt: bool = False, components: list[str] | None = None, partial: list[str] | None = None, is_harvest: int = 0, is_sticky: int = 0)[source]

Bases: object

Encapsulates data for an action.

code: str
components: list[str]
descr: str
is_compiled: bool
is_harvest: int
is_sticky: int
lockexempt: bool
oper_a: Any | None
oper_p: Any | None
partial: list[str]
targetage: int | None
treatment_type: Any | None
class forest.DevelopmentType(key: tuple[str, ...], parent: ForestModel)[source]

Bases: object

Encapsulates development type data (curves, age, area), and provides methods to operate on the data. This is the core class in this module, with respect to tracking forest inventory and simulating growth and actions.

Parameters:
  • key (tuple) – Development type key (a unique combination of theme values). Tuple length must match the number of themes in the parent forest model.

  • parent (ws3.forest.ForestModel) – Parent forest model.

add_ycomp(ytype: str, yname: str, ycomp: Any, first_match: bool = True) None[source]

Adds a yield component.

Parameters:
  • ytype (str) – Type of yield component to add ('c' for complex).

  • yname (str) – Name of the yield component.

  • ycomp (str) – Yield component to add.

  • first_match (bool) – Flag indicating whether to only add the component if it does not already exist. Defaults to True.

area(period: int, age: int | None = None, area: float | None = None, delta: bool = True) float | None[source]

If area not specified, returns area inventory for period (with optional age filter), else sets area for period and age. If delta switch active (default True), area value is interpreted as an increment on current inventory (otherwise will clobber current inventory).

Parameters:
  • period (int) – The period for which the area is being retrieved or set.

  • age (int) – The age for which the area is being retrieved or set. If None, returns total area.

  • area (float) – The area value to set. If None, returns the area inventory.

  • delta (bool) – If True (default), interprets the area value as an increment on the current inventory. If False, sets the area value directly.

compile_action(acode: str, verbose: bool = False) int | None[source]

Compile action, given action code. This mostly involves resolving operability expression strings into lower and upper operability limits, defined as (alo, ahi) age pair for each period. Deletes action from self if never operable.

Parameters:
  • acode (str) – Action code.

  • verbose (bool) – Verbosity flag. Defaults to False.

compile_actions(verbose: bool = False) None[source]

Compile all actions.

Parameters:

verbose (bool) – Verbosity flag. Defaults to False.

grow(start_period: int = 1, cascade: bool = True) None[source]

Grow self (default starting period 1, and cascading to end of planning horizon). Growing basically just increments age and bumps inventory area to the next period.

Parameters:
  • start_period (int) – The starting period for growth (default is 1).

  • cascade (bool) – If True, growth cascades to the end of the planning horizon, otherwise only grows the specified period. Default is True.

initialize_areas() None[source]

Copy initial inventory to period-1 inventory.

is_operable(acode: str, period: int, age: int | None = None, verbose: bool = False) bool | tuple[int, int][source]

Test hypothetical operability, given an action code, a period, and optional age. Does not imply that there is any operable area in current inventory at the specified period.

Parameters:
  • acode (str) – The action code for which to test operability.

  • period (int) – The period in which to test operability.

  • age (int) – The age at which to test operability. If None, only checks operability for the period.

  • verbose (bool) – Verbosity flag.

key: tuple[str, ...]
oper_expr: defaultdict[list]
operability: dict[str, dict[int, tuple[int, int] | None]]
operable_ages(acode: str, period: int) list[int] | None[source]

Finds list of ages at which self is operable, given an action code and period index. Takes into account both action operability age range and current inventory at the specified period.

Parameters:
  • acode (str) – Action code for which to compile operable ages.

  • period (int) – Period at which to compile operable ages.

Return list:

List of ages at which the specified action is operable in the specified period.

operable_area(acode: str, period: int, age: int | None = None, cleanup: bool = True) float[source]

Compiles operable area, given an action code, a period, and optional age.

Parameters:
  • acode (str) – The action code to determine operability.

  • period (int) – The period to determine operability for.

  • age (int) – The age to determine operability for. If None, only checks operability for the period.

  • cleanup (bool) – If True (default), removes the age class from the inventory dict if operable area is less than self.parent.area_epsilon.

Return float:

Operable area. Returns 0 if inoperable or no current inventory, and operable area otherwise.

overwrite_initial_areas(period)[source]

Overwrites the initial areas with area from a specified period. Basically rolls the planning horizon forward to the specified period.

Parameters:

period (int) – Source period from which to copy initial areas.

parent: ForestModel
reset_areas(period: int | None = None) None[source]

Reset areas dictionary. By default will reset all periods (except for period 0), unless period is specified.

Parameters:

period (int) – Period for which to reset areas dictionary.

resolve_condition(yname: str, lo: float, hi: float) list[int][source]

Compile list of ages corresponding to lower- and and upper-bound values of specified yield component Yield bounds are interpreted as first occurence of lower-bound value (reading curve from left to right) and first occurrence of upper-bound value (reading curve from right to left).

Parameters:
  • yname (str) – Yield component name to use for age lookup

  • lo (float) – Yield lower-bound value to use for age lookup

  • hi (float) – Yield upper-bound value to use for age lookup

Return list:

List of ages corresponding to specified yield bounds on specified yield curve.

transitions: dict[tuple[str, int], list[Any]]
ycomp(yname: str, silent_fail: bool = True) Curve | None[source]

Returns the yield components associated with the given yield name.

Parameters:
  • yname (str) – The name of the yield to retrieve components for.

  • silent_fail (bool) – If True (default), returns None if the yield name is not found. If False, raises a KeyError that yield name is not found.

Returns:

Returns None if the yield name is not found and silent_fail is True, otherwise returns the requested yield component.

Return type:

ws3.core.Curve

ycomps() list[str][source]
Returns:

List of yield component names.

class forest.ForestModel(model_name, model_path, base_year, horizon=30, period_length=10, max_age=1000, area_epsilon=0.01, curve_epsilon=0.01)[source]

Bases: object

This is the core class of the ws3 package. Includes methods import data from various sources, simulate growth and apply actions. The model can be used in either a (prescriptive) simulation-based approach or a (descriptive) optimization-based approach.

This class encapsulates all the information used to simulate scenarios from a given dataset (i.e., stratified intial inventory, growth and yield functions, action eligibility, transition matrix, action schedule, etc.), as well as a large collection of functions to import and export data, generate activity schedules, and simulate application of these schedules (i.e., run scenarios).

At the heart of the ForestModel class is a list of DevelopentType instances. Each DevelopmentType instance encapsulates information about one development type (i.e., a forest stratum, which is an aggregate of smaller stands that make up the raw forest inventory input data). The DevelopmentType class also stores a list of operable actions, maps state variable transitions to these actions, stores growth and yield functions, and knows how to grow itself when time is incremented during a simulation.

A typical use case starts with creating an instance of the ForestModel class. Then, we need to load data into this instance, define one or more scenarios (using a mix of heuristic and optimization approaches), run the scenarios, and export output data to a format suitable for analysis (or link to the next model in a larger modelling pipeline).

Initializes the ForestModel with the provided parameters.

Parameters:
  • model_name (str) – The name of model.

  • model_path (str) – The path to input data of model.

  • base_year (int) – The base year of teh model.

  • horizon (int) – The length (in number of periods) of the simulation horizon.

  • max_age (int) – The maximum age considered in the model.

  • area_epsilon (int)

  • curve_epsilon (int)

actions: dict[str, Any]
add_null_action(acode='null', maxage=None)[source]

Adds a null action with the specified action code, minimum age (default is None), and maximum age (default is None).

Parameters:
  • acode (str) – Action code for the new null action. Defaults to 'null'.

  • maxage (int) – Maximum age at which the new null action is operable.

add_problem(name: str, coeff_funcs: Any, cflw_e: Any = None, cgen_data: Any = None, solver: Any = 'highs', formulation: int = 1, z_coeff_key: str = 'z', acodes: Any = None, sense: int = -1, mask: Any = None, workers: int = 1, verbose: bool = False) Any[source]

Add an optimization problem to the model.

Parameters:
  • name (str) – Used as key to store ws3.opt.Problem instances in a dict in the ws3.forest.ForestModel instanace, so make sure it is unique within a given model or you will overwrite dict values (assuming you want to stuff multiple problems, and their solutions, into your model at the same time).

  • coeff_funcs (dict) – Dict of function references, keyed on row name strings. These are the functions that generate the LP optimization problem matrix coefficients (for the objective function and constraint rows). This one gets complicated, and is a likely source of bugs. Make sure the row name key strings are all unique or you will make a mess. You can name the constraint rows anything you want, but the objective function row has to be named ‘z’. All coefficient functions must accept exactly two args, in this order: a ws3.forest.ForestModel instance and a path (a tuple of ws3.core.Node object instances). The ‘z’ coefficient function is special in that it must return a single float value. All other (i.e., constraint) coefficient functions just return a dict of floats, keyed on period ints (can be sparse, i.e., not necessary to include key:value pairs in output dict if value is 0.0). It is useful (but not necessary) to use functools.partial to specialize a smaller number of more general function definitions (with more args, that get “locked down” and hidden by partial) as we have done in the example in this notebook.

  • cflw_e (dict) –

    Even-flow (flow-constraint) specification, keyed on row name strings (must match row name key values used to define coefficient functions for flow constraints in coeff_func dict). Two value forms are supported:

    • Legacy (eps_dict, ref_period) tuple: a symmetric +/-eps band tying each period’s output to the single anchor period ref_period (int). eps_dict maps period -> epsilon (must include all periods). {'foo':({1:0.01, ..., 10:0.01}, 1), 'bar':({1:0.05, ..., 10:0.05}, 1)}

    • Extended {"decrease": d, "increase": i, "ref": r} dict: separate period-keyed tolerances. decrease (alpha) bounds the fractional period-over-period decrease (H_t - (1-alpha) H_ref >= 0); increase (beta) bounds the fractional increase (H_t - (1+beta) H_ref <= 0); either may be None to omit that bound. ref is an int anchor period or "consecutive" (each period anchored to the previous period). This enables the classic FORPLAN sequential-flow policies — e.g. non-declining yield {"decrease": {t: 0.0}, "increase": None, "ref": "consecutive"} and bounded deviation {"decrease": {t: eps}, "increase": {t: eps}, "ref": "consecutive"} (cf. Daugherty 1991, Table 5.6).

  • cgen_data (dict) –

    Dict of dict of dicts. The outer-level dict is keyed on row name strings (must match row names used in coeff_funcs. The middle second level of dicts always has keys ‘lb’ and ‘ub’, and the inner level of dicts specifies lower- and upper-bound general constraint RHS (float) values, keyed on period (int). See example below.

    {'foo':{'lb':{1:1., ..., 10:1.}, 'ub':{1:2., ..., 10:2.}}, 'bar':{{'lb':{1:1., ..., 10:1.}, 'ub':{1:2., ..., 10:4.}}}}

  • acodes (int) – List of strings. Action codes to be included in optimization problem formulation (actions must defined in the ws3.forest.ForestModel instance, but can be only a subset).

  • sense (int) – Must be one of ws3.opt.SENSE_MAXIMIZE or ws3.opt.SENSE_MINIMIZE, or equivalent int values (use the constants to keep code more legible).

  • mask (tuple) – Tuple of strings constituting a valid mask for your ws3.forest.ForestModel instance. Can be None if you do not want to filter ws3.forest.DevelopmentType instances.

  • workers (int) – Number of worker threads to use for parallel processing.

Returns:

ws3.opt.Problem. Reference to a new Problem instance that was created. Also stored in the ForestModel instance (problems attribute, keyed on problem name).

add_theme(name, basecodes=None, aggs=None, description='')[source]

Adds a theme to the model.

Parameters:
  • name (str) – The name of theme.

  • basecodes (list) – List of base codes for the theme.

  • aggs (dict) – Dictionary containing aggregate values for the theme.

  • description (str) – Description of the theme.

age_class_distribution(period, mask=None, omit_null=False)[source]

Returns age class distribution (dict of areas, keys on age).

Parameters:
  • period (int) – The period for which to retrieve the age class distribution.

  • mask (tuple) – A mask to filter development types. Default is None.

  • omit_null (bool) – If True, omits null areas from the distribution. Default is False.

Return dict:

A dictionary where keys are ages and values are the corresponding area distributions.

applied_actions: dict[int, dict[str, Any]]
apply_action(dtype_key: tuple[str, ...], acode: str, period: int, age: int, area: float, override_operability: bool = False, fuzzy_age: bool = True, recourse_enabled: bool = True, areaselector: Any = None, compile_t_ycomps: bool = False, compile_c_ycomps: bool = False, verbose: bool = False) tuple[int, float, list[tuple[tuple[str, ...], Any, int]]][source]

Applies action, given action code, development type, period, age, area. Can optionally override operability limits, optionally use fuzzy age (i.e., attempt to apply action to proximal age class if specified age is not operable), optionally use default AreaSelector to patch missing area (if recourse enabled). Applying an action is a rather complex process, involving testing for operability (JIT-compiling operability expression as required), checking that valid transitions are defined, checking that area is available (possibly using fuzzy age and area selector functions to find missing area), generate list of target development types (from source development type and transition expressions [which may need to be JIT-compiled]), creating new development types (as needed), doing the area accounting correctly (without creating or destroying any area) and compiling the products from the action (which gets a bit complicated in the case of partial cuts…).

Parameters:
  • dtype_key (tuple) – The key identifying the development type.

  • acode (str) – The action code to apply.

  • period (int) – The period in which to apply the action.

  • age (int) – The age at which to apply the action.

  • area (float) – The area to apply the action on.

  • override_operability (bool) – If True, overrides operability limits. Default is False.

  • fuzzy_age (bool) – If True, attempts to apply action to proximal age class if specified age is not operable.

  • recourse_enabled (bool) – If True, uses default AreaSelector to patch missing area. Default is True.

  • areaselector (bool) – The AreaSelector object to use for patching missing area. Default is None.

  • compile_t_ycomps (bool) – If True, compiles time-indexed yield components. Default is False.

  • compile_c_ycomps (bool) – If True, compiles complex yield components. Default is False.

  • verbose (bool) – If True, prints additional information for debugging purposes. Default is False.

Return tuple:

Returns (errorcode, missing_area, target_dt) triplet, where errorcode is an error code, missing_area is the missing area, and target_dt is a list of (dtk, tprop, targetage) triplets (one triplet per target development type).

Error codes: 1. Invalid area argument 2. Requested action not defined for development type 3. Requested action defined, but never operable 4. Action not operable 5. Transitions not defined for action

apply_schedule(schedule: Any, max_period: int | None = None, verbose: bool = False, fail_on_missingarea: bool = False, force_integral_area: bool = False, override_operability: bool = False, fuzzy_age: bool = True, recourse_enabled: bool = True, areaselector: Any = None, compile_t_ycomps: bool = False, compile_c_ycomps: bool = False, rounding_bias: float = 0.15, scale_area: Any = None, reset: bool = True, crash_on_action_error: bool = False) None[source]

Assumes schedule in format returned by import_schedule_section(). That is: list of (dtype_key, age, area, acode, period, etype) tuples. Also assumes that actions in list are sorted by applied period.

Parameters:
  • schedule (list) – The schedule of actions to apply.

  • max_period (int) – The maximum period to apply actions for. If None, defaults to the self.horizon.

  • verbose (bool) – If True, prints additional information for debugging purposes. Default is False.

  • fail_on_missingarea (bool) – If True, raises an exception if missing area is encountered. Default is False.

  • force_integral_area (bool) – If True, forces the area to be integral. Default is False.

  • override_operability (bool) – If True, overrides operability limits. Default is False.

  • fuzzy_age (bool) – If True, attempts to apply action to proximal age class if specified age is not operable. Default is True.

  • recourse_enabled (bool) – If True, uses default AreaSelector to patch missing area. Default is True.

  • areaselector (object) – The AreaSelector object to use for patching missing area. Default is None.

  • compile_t_ycomps (bool) – If True, compiles time-indexed yield components. Default is False.

  • compile_c_ycomps (bool) – If True, compiles complex yield components. Default is False.

  • rounding_bias (float) – The rounding bias to use when forcing integral area. Default is 0.15.

  • scale_area – The scaling factor to apply to the area. Default is None.

  • reset (bool) – If True, resets the model before applying the schedule. Default is True.

  • crash_on_action_error (bool) – Crash on error applying action. Default is False.

Returns:

The missing area (float) after applying the schedule.

commit_actions(period: int = 1, repair_future_actions: bool = False, verbose: bool = False) None[source]

Commits applied actions (i.e., apply transitions and grow, default starting at period 1). By default, will attempt to repair broken (infeasible) future actions, attempting to replace infeasiblea operated area using default area selector.

Parameters:
  • period (int) – Period at which to start committing actions. Defaults to 1.

  • repair_future_actions (bool) – If True will attempt to repair future actions (i.e., actions currently scheduled for periods after period), else resets actions in future periods. Defaults to False.

compile_actions(mask: Any = None, verbose: bool = False) None[source]

Compile actions for the development types filtered by mask.

compile_product(period, expr, acode=None, dtype_keys=None, age=None, coeff=False, verbose=False)[source]

Compiles products from applied actions in given period. Parses string expression, which resolves to a single coefficient. Operated area can be filtered on action code, development type key list, and age. Result is product of sum of filtered area and coefficient.

Parameters:
  • period (int) – Period for which to compile product query.

  • expr (str) – String expression to use when compiling product query. Must be a valid expression string (see documentation for more details on what types of expressions ws3 can parse). Yield component names used in expressions will be automatically resolved to the corresponding float yield values (by development type, with age lookup corresponding to the age at which an action was applied in the current schedule).

  • acode (str) – Optional action code filter.

  • dtype_keys (list) – Optional list of development type keys on which to filter the query.

  • age (int) – Optional age filter.

  • coeff (bool) – Will force areas used to compile product query to 1 if True, else will use the actionned areas in the current schedule. Mostly only for use when validating or debugging a model (and does not really make to use unless a single development type key is specified in dtype_keys filter).

  • verbose (bool) – Verbosity flag.

Return float:

Result of product query.

compile_schedule(problem: Any = None) list[tuple[Any, ...]][source]

Compiles an action schedule. If a :py:class;`ws3.opt.Problem` instance is specified compiles the schedule from the optimal solution of the problem instance, otherwise compiles the schedule from the current solution (i.e., self.applied_actions).

:param ws3.opt.Problem problem: Optimization problem from which to extract an action schedule :return list: Action schedule as list of (dtk, age, area, acode, period, etype) tuples.

create_dtype_fromkey(key: tuple[str, ...]) Any[source]

Creates a new development type, given a development type key (checks for existing, auto-assigns yield compompontents, auto-assign actions and transitions, checks for operability (filed under inoperable if applicable).

Parameters:

key (tuple) – Development type key

Returns:

New development type

Return type:

ws3.forest.DevelopmentType

dt(dtype_key: tuple[str, ...]) Any[source]

Returns development type, given key (returns None on invalid key).

Parameters:

dtype_key (tuple) – Development type key.

Returns:

Development type.

Return type:

ws3.forest.DevelopmentType

grow(start_period=1, cascade=True)[source]

Simulates growth (default start at period 1 and cascading to the end of the planning horizon). Basically just calls ws3.forest.DevelopmentType.grow() on all development types. Growth in ws3 just increments age—any other consequences of aging (e.g., tree height growth, diameter growth, volume growth) is all in implicitly embedded in the yield curves.

Parameters:
  • start_period (int) – Period at which to start aging inventory

  • cascade (bool) – Will cascade growth to all future periods if True, else only grows the specified period.

import_actions_section(filename_suffix='act', mask_func=None, nthemes=None, convert_periods_to_years=None)[source]

Imports ACTIONS section from a Woodstock-formatted model input dataset.

Parameters:
  • filename_suffix (str) – Suffix for CONSTANTS section file name.

  • mask_func (function) – Custom mask function (deprecate?)

  • nthemes (int) – Number of themes

import_areas_section(model_path=None, model_name=None, filename_suffix='are', import_empty=False, convert_periods_to_years=None)[source]

Imports AREAS section from a Woodstock-formatted model input dataset. Each line in the section represents an area for a unique combination of development type key and age class. Empty areas (with values less than area_epsilon) will be skipped if import_empty is False.

Parameters:
  • filename_suffix (str) – Suffix for AREAS section file name.

  • import_empty (bool) – Whether or not to import empty areas (with values less than area_epsilon).

Return int:

0 if succcess, 1 otherwise.

import_constants_section(filename_suffix='con')[source]

Imports CONSTANTS section from a Woodstock-formatted input dataset. Each line in the section represents a constant and its value. Constants are stored in a dictionary where the keys are the constant names and the values are their respective values.

Parameters:

filename_suffix (str) – Suffix for CONSTANTS section file name.

import_control_section(filename_suffix='run')[source]

Imports CONTROL section from a Woodstock-formatted model input dataset.

Warning

Not implemented yet.

import_graphics_section(filename_suffix='gra')[source]

Imports GRAPHICS section from a Woodstock-formatted model input dataset.

Warning

Not implemented yet.

import_landscape_section(filename_suffix='lan', ti_offset=0)[source]

Imports LANDSCAPE section from a Woodstock-formatted model input dataset. Model path and file base name assumed from self.model_path and self.model_path.

Parameters:
  • filename_suffix (str) – Filename suffix in which to look for LANDSCAPE section data

  • ti_offset (str) – Theme index offset. Will bump theme index by this value. Defaults to 0.

import_lifespan_section(filename_suffix='lif')[source]

Imports LIFESPAN section from a Woodstock-formatted model input dataset.

Warning

Not implemented yet.

import_optimize_section(filename_suffix='opt')[source]

Imports OPTIMIZE section from a Woodstock-formatted model input dataset.

Warning

Not implemented yet.

import_outputs_section(filename_suffix='out')[source]

Imports OUTPUTS section from a Woodstock-formatted model input dataset. Model path and file base name assumed from self.model_path and self.model_path.

Parameters:

filename_suffix (str) – Filename suffix in which to look for OUTPUTS section data.

import_schedule_section(filename_suffix='seq', replace_commas=True, filename_prefix=None, convert_periods_to_years=None)[source]

Imports SCHEDULE section from a Woodstock-formatted model input dataset.

Parameters:
  • filename_suffix (str) – Suffix for SCHEDULE section file name.

  • replace_commas (bool) – Remove commas from area value string tokens

  • filename_prefix (str) – Prefix for SCEDULE section file name.

import_transitions_section(filename_suffix='trn', mask_func=None, nthemes=None, convert_periods_to_years=None)[source]

Imports TRANSITIONS section from a Woodstock-formatted model input dataset.

Parameters:
  • filename_suffix (str) – Suffix for CONSTANTS section file name.

  • mask_func (function) – Custom mask function

  • nthemes (int) – Number of themes

import_yields_section(filename_suffix='yld', mask_func=None, verbose=False, convert_periods_to_years=None)[source]

Imports YIELDS section from a Forest model.

Parameters:
  • filename_suffix (str) – Suffix for CONSTANTS section file name.

  • mask_func (function) – Custom mask function (deprecate?)

  • verbose (bool) – Verbosity flag

initialize_areas(reset_areas: bool = True) None[source]

Copies areas from period 0 to period 1.

Parameters:

reset_areas (bool) – Optionally calls self.reset_areas() if True.

inventory(period, yname=None, age=None, mask=None, dtype_keys=None, verbose=0)[source]

Flexible method that compiles inventory at given period. Unit of return data defaults to area if yname not given, but takes on unit of specificed yield component otherwise. Can optionally be constrained by age and development type mask.

Parameters:
  • period (int) – Period for which to compile inventory.

  • yname (str) – Name of yield component to use when compiling inventory.

  • age (int) – Optional age filter.

  • mask (tuple) – Optional development type mask filter (dtype_keys must be None if this is used).

  • dtype_keys (list) – Optional development type key filter (mask must be None if this is used).

  • verbose (int) – Optional verbosity setting (passed to call to ws3.forest.ForestModel.unmask()).

Return float:

Result of compiling inventory query.

is_harvest(acode)[source]

Returns the value of ws3.forest.Action.is_harvest for a given action code.

Parameters:

acode (str) – The action code for which to look up the is_harvest attribute value. Should return True or False (not guaranteed—must have been correctly set when action defined).

match_mask(mask: tuple[str, ...], key: tuple[str, ...]) bool[source]

Checks if a development type key matches a development type mask.

Parameters:
  • mask (tuple) – Development type mask

  • key (tuple) – Development type key

Return bool:

Returns True if key matches mask, False otherwise.

nthemes() int[source]
Returns:

Number of themes

operable_area(acode, period, age=None, mask=None)[source]

Returns total operable area, given action code and period (and optionally age).

Parameters:
  • acode (str) – Action code for which to compile operable area.

  • period (int) – Period for which to compile operable area.

  • age (int) – Optional age filter.

  • mask (tuple) – Optional development type mask.

Return float:

Result of operable area query.

operable_dtypes(acode: str, period: int, mask: Any = None) dict[tuple[str, ...], list[int]][source]

Looks up operable development types for a given action code and period (and optional mask).

Parameters:

acode – Action code for which to look up operable development types.

Returns:

Dictionary keyed on development type key, values are lists of operable ages.

operated_area(acode, period, dtype_key=None, age=None)[source]

Compiles operated area, given action code and period (and optionally list of development type keys or age).

Parameters:
  • acode (str) – Action code for which to compile operated area.

  • period (int) – Period for which to compile operated area.

  • dtype_keys (list) – Optional list of development type keys to use as filter for operated area query.

  • age (int) – Optional age filter.

Return float:

Result of operated area query.

output_groups: dict[str, Any]
outputs: dict[str, Any]
overwrite_initial_areas(period)[source]

Overwrites the initial areas for all development types, for the specified period.

Parameters:

period (int) – Period for which to overwrite initial areas.

register_curve(curve: Any) Any[source]

Add curve to global curve dictionary (uses result of curve.points() to construct key).

repair_actions(period: int, areaselector: Any = None, verbose: bool = False) None[source]

Attempts to repair the action schedule for given period, using ws3.forest.AreaSelector object (defaults to class-default greed oldest-first area selector).

Parameters:
  • period (int) – Period for which to attempt to repair the action schedule.

  • areaselector (ws3.forest.AreaSelector) – Area selector to use when attempting to repair action schedule.

  • verbose (book) – Verbosity flag.

reset() None[source]

Resets the forest model by clearing applied actions and reinitializing areas.

reset_actions(period: int | None = None, acode: str | None = None, override_sticky: bool = False) None[source]

Resets actions. By default resets, all actions in all periods (except for sticky actions, unless overridden), unless period or acode specified.

Parameters:
  • period (int) – Optional period for which to reset actions.

  • acode (str) – Optional action code for which to reset actions.

  • override_sticky (bool) – Will override sticky actions if True.

reset_areas(period: int | None = None) None[source]

Reset areas for all development types.

Parameters:

period (int) – Optional period for which to reset areas. Defaults to None (in which case resets all periods).

resolve_append(dtk: tuple[str, ...], expr: str) Any[source]

Not been implemented yet.

resolve_condition(condition: Any, dtype_key: tuple[str, ...] | None = None) list[int][source]

Expands @AGE or @YLD conditions to list of age values. @AGE condition specifies lower- and upper-bound ages in a range, so just expands to age values that fall within that range. @YLD condition specifies lower- and upper-bound yield values for a given yield component name, so needs to do a reverse age lookup on the specified yield component (so dtype_key must be specified or in this case or the method will crash).

Parameters:
  • condition (str) – Condition expression string

  • dtype_key (tuple) – Development type key

Return list:

List of age values

resolve_replace(dtk: tuple[str, ...], expr: str) str[source]

Enables the creation of new development types by replacing an existing attribute code with a new value for a specific theme, instead of directly coding the attribute change in transition.

Parameters:
  • dtk (tuple) – Source development type key.

  • expr (str) – Woodstock REPLACE expression parsed from an TRANSITIONS model section using the ws3.forest.ForestModel.import_transitions_section() method.

Returns:

Updated development type key tuple.

Return type:

tuple

resolve_tappend(dt, tappend)[source]

Resolves a theme append expression, in the context of defining a new development type when implementing a transition (following application of an action to a source development type).

Warning

Not implemented yet.

resolve_targetage(dtk: tuple[str, ...], tyield: Any, sage: int, tage: int | None, acode: str, verbose: bool = False) int[source]

Determines the target age for a transition. :param tuple dtk: Development type key tuple :param str tyield: Target yield component name :param int sage: Source age :param int tage: Target age :param str acode: Action code :param bool verbose: Verbosity flag :return int: Target age

resolve_tmask(dt, tmask, treplace, tappend)[source]

Returns new developement type key (tuple of values, one per theme), given developement type, theme mask, theme replace expression, and theme append expression.

:param ws3.forest.DevelopmentType dt: Source development type :param tuple tmask: Theme mask to apply to source development type key :param str treplace: Theme replace expresion to apply source development type key :param str tappend: Theme append expression to apply to soruce development type key :return tuple: New development type key

resolve_treplace(dt: Any, treplace: str) str[source]

Resolves a theme replace expression, in the context of defining a new development type when implementing a transition (following application of an action to a source development type).

:param ws3.forest.DevelopmentType dt: Source development type :param str treplace: Theme replace expression to apply :return str: New theme value string

set_horizon(horizon: int) None[source]

Sets the horizon of the model.

This method updates the horizon of the model to the specified value and adjusts the list of periods accordingly.

sylv_cred_formula(treatment_type, cover_type)[source]

Calculate Sylviculture Credits based on treatment type and cover type.

theme_basecodes(theme_index: int) list[str][source]

Return list of base codes, given theme index.

Parameters:

theme_index (int) – Theme index for which to return basecodes.

Return list:

List of theme basecodes.

to_cbm_sit(softwood_volume_yname, hardwood_volume_yname, admin_boundary, eco_boundary, disturbance_type_mapping, export_csv=False, sit_data_path='', default_last_pass_disturbance='fire', n_yield_vals=100, include_empty_dtypes=False)[source]

Exports model data in a CBM standard import tool (SIT) data exchange format. Calls several private methods to compile individual CBM SIT tables for the current ws3.forest.ForestModel instance.

Parameters:
  • softwood_volume_yname (str) – The yield component name for softwood volume.

  • hardwood_volume_yname (str) – The yield component name for hardwood volume.

  • admin_boundary (str) – The administrative boundary for spatial units mapping.

  • eco_boundary (str) – The ecological boundary for spatial units mapping.

  • disturbance_type_mapping (dict) – A dictionary containing disturbance type mapping information.

  • export_csv (bool) – Flag indicating whether to export data to CSV files. Default is False.

  • sit_data_path (str) – The path to export CSV files. Default is empty string.

  • default_last_pass_disturbance (str) – The default last pass disturbance type. Default is ‘fire’.

  • n_yield_vals (int) – The number of yield values. Default is 100.

Return tuple:

Tuple of sit_config (JSON-like dict namespace) and sit_tables (dict of pandas.DataFrame objects).

transitions: dict[Any, Any]
tree()
unmask(mask: Any, verbose: int = 0) list[tuple[str, ...]][source]

Iteratively filter list of development type keys using mask values. Accepts Woodstock-style string masks to facilitate cut-and-paste testing.

Parameters:
  • mask (tuple or str) – Development type mask (tuple or Woodstock-style string format)

  • verbose (int) – Verbosity level (passed to self._expand_theme).

Return list:

List of development type keys that match the mask.

class forest.GreedyAreaSelector(parent: ForestModel)[source]

Bases: object

Default AreaSelector implementation. Selects areas for treatment from oldest age classes.

operate(period: int, acode: str, target_area: float, mask: tuple[Any, ...] | None = None, commit_actions: bool = True, verbose: bool = False) float[source]

Greedily operate on oldest operable age classes. Returns missing area (i.e., difference between target and operated areas).

Parameters:
  • period (int) – The time period for the operation.

  • acode (str) – The action code to specify the action.

  • target_area (float) – The desired area to be achieved through operation.

  • mask (tuple) – Tuple of values for development types.

  • commit_actions (bool) – Flag indicating whether to commit actions. Defaults to True.

  • verbose (bool) – Verbosity flag. Defaults to False.

parent: ForestModel
class forest.Output(parent, code=None, expression=None, factor=(1.0, 1), description='', theme_index=-1, is_basic=False, is_level=False)[source]

Bases: object

Encapsulates data and methods to operate on aggregate outputs from the model. Emulates behaviour of Forest outputs.

Warning

Behaviour of Forest outputs is quite complex. This class needs more work before it is used in a production setting (i.e., resolution of some complex output cases is buggy).