fvs2py 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fvs2py/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from ._base import FVS
2
+
3
+ __all__ = ["FVS"]
fvs2py/_base.py ADDED
@@ -0,0 +1,93 @@
1
+ """Public `FVS` class, assembled from focused mixins over `FvsCore`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes as ct
6
+ import os
7
+
8
+ from fvs2py._core import FvsCore
9
+ from fvs2py._mixins import (
10
+ ControlMixin,
11
+ EventMixin,
12
+ SimulationMixin,
13
+ SpeciesMixin,
14
+ StandMixin,
15
+ SVSMixin,
16
+ TreesMixin,
17
+ )
18
+ from fvs2py.common import class_requires_fvs_library
19
+ from fvs2py.constants import (
20
+ EVMON_ATTRS,
21
+ FFE_FALLYRS_ATTRS,
22
+ SPECIES_ATTRS,
23
+ SVS_OBJ_ATTRS,
24
+ TREE_ATTRS,
25
+ )
26
+ from fvs2py.enums import FvsSimulationState
27
+
28
+
29
+ @class_requires_fvs_library
30
+ class FVS(
31
+ EventMixin,
32
+ SVSMixin,
33
+ TreesMixin,
34
+ SpeciesMixin,
35
+ StandMixin,
36
+ SimulationMixin,
37
+ ControlMixin,
38
+ FvsCore,
39
+ ):
40
+ """Main class for interacting with FVS at runtime.
41
+
42
+ Public behavior is contributed by the seven mixins
43
+ (`EventMixin`, `SVSMixin`, `TreesMixin`,
44
+ `SpeciesMixin`, `StandMixin`, `SimulationMixin`,
45
+ `ControlMixin`); this class just initializes the Python-side
46
+ buffers they rely on and wires the library-reload hook.
47
+ """
48
+
49
+ def __init__(self, lib_path: str | os.PathLike) -> None:
50
+ """Load the FVS shared library and initialize per-instance buffers.
51
+
52
+ Args:
53
+ lib_path: Path to the FVS shared library.
54
+ """
55
+ super().__init__(lib_path=lib_path)
56
+ self._initialize_attributes()
57
+
58
+ def _initialize_attributes(self) -> None:
59
+ """Reset all Python-side buffers and state tracked alongside FVS.
60
+
61
+ Called both at construction and after `_reload_fvs` so the
62
+ mixins can rely on a known set of pre-initialized attributes.
63
+ """
64
+ self.keyfile_path = None
65
+ self.keyfile = None
66
+ self._evmon_attrs = dict.fromkeys(EVMON_ATTRS)
67
+ self._exit_code = ct.c_int(0)
68
+ self._ffe_attrs = dict.fromkeys(FFE_FALLYRS_ATTRS)
69
+ self._svs_obj_attrs = dict.fromkeys(SVS_OBJ_ATTRS)
70
+ self._itrncd = ct.c_int(-1)
71
+ self._maxcycles = ct.c_int(0)
72
+ self._maxplots = ct.c_int(0)
73
+ self._maxspecies = ct.c_int(0)
74
+ self._maxtrees = ct.c_int(0)
75
+ self._mgmt_id = ct.create_string_buffer(4)
76
+ self._ncycles = ct.c_int(0)
77
+ self._nplots = ct.c_int(0)
78
+ self._ntrees = ct.c_int(0)
79
+ self._restart_code = ct.c_int(0)
80
+ self._species_attrs = dict.fromkeys(SPECIES_ATTRS)
81
+ self._stand_cn = ct.create_string_buffer(40)
82
+ self._stand_id = ct.create_string_buffer(26)
83
+ self._state = FvsSimulationState.IDLE
84
+ self._stop_point_code = None
85
+ self._stop_point_year = None
86
+ self._tree_attrs = TREE_ATTRS
87
+ self._trees = dict.fromkeys(TREE_ATTRS)
88
+
89
+ def _reload_fvs(self) -> None:
90
+ """Unload the current library, load a fresh one, and reset buffers."""
91
+ self._unload_fvs()
92
+ self._load_fvs()
93
+ self._initialize_attributes()
fvs2py/_core.py ADDED
@@ -0,0 +1,155 @@
1
+ from __future__ import annotations
2
+
3
+ import ctypes as ct
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from fvs2py._routines import FVS_ROUTINES
10
+ from fvs2py.common import load_dll, unload_dll
11
+ from fvs2py.constants import NEEDED_ROUTINES
12
+
13
+
14
+ class FvsCore:
15
+ """Base class for FVS API wrapper."""
16
+
17
+ def __init__(self, lib_path: str | os.PathLike) -> None:
18
+ """Load the FVS shared library and bind its needed routines.
19
+
20
+ Resolves each routine in `NEEDED_ROUTINES` from the loaded
21
+ library, tolerating both the unix-style `name_` mangling and the
22
+ un-mangled `name` spelling, and assigns each to `self._<name>`.
23
+ Argtypes/restype are applied per-call by `_invoke` via the
24
+ `fvs2py._routines.FVS_ROUTINES` registry.
25
+
26
+ Args:
27
+ lib_path: Path to the FVS shared library.
28
+
29
+ Raises:
30
+ ImportError: If one or more routines in `NEEDED_ROUTINES`
31
+ are not present or not callable on the loaded library.
32
+ """
33
+ self.lib_path: Path = Path(os.path.abspath(lib_path))
34
+ self._lib: ct.CDLL | None = None
35
+ self.variant: str = (
36
+ os.path
37
+ .basename(self.lib_path)
38
+ .split(".")[0]
39
+ .split("FVS")[-1]
40
+ .upper()
41
+ )
42
+
43
+ # Declare function attributes with type annotations for mypy.
44
+ # These are ctypes foreign function pointers loaded from the shared library.
45
+ self._fvs: ct._FuncPointer
46
+ self._fvsAddActivity: ct._FuncPointer
47
+ self._fvsAddTrees: ct._FuncPointer
48
+ self._fvsDimSizes: ct._FuncPointer
49
+ self._fvsEvmonAttr: ct._FuncPointer
50
+ self._fvsFFEAttrs: ct._FuncPointer
51
+ self._fvsGetRestartCode: ct._FuncPointer
52
+ self._fvsGetRtnCode: ct._FuncPointer
53
+ self._fvsGetICCode: ct._FuncPointer
54
+ self._fvsSVSDimSizes: ct._FuncPointer
55
+ self._fvsSetStoppointCodes: ct._FuncPointer
56
+ self._fvsSetCmdLine: ct._FuncPointer
57
+ self._fvsSVSObjData: ct._FuncPointer
58
+ self._fvsSpeciesAttr: ct._FuncPointer
59
+ self._fvsSpeciesCode: ct._FuncPointer
60
+ self._fvsStandID: ct._FuncPointer
61
+ self._fvsSummary: ct._FuncPointer
62
+ self._fvsTreeAttr: ct._FuncPointer
63
+ self._fvsUnitConversion: ct._FuncPointer
64
+
65
+ self._load_fvs()
66
+ assert self._lib is not None # to satisfy type checker
67
+
68
+ self._resolve_routines()
69
+
70
+ def _resolve_routines(self) -> None:
71
+ """Bind each needed FVS routine to `self` as a raw `_FuncPointer`.
72
+
73
+ For every name in `NEEDED_ROUTINES`, look up the corresponding
74
+ foreign function on `self._lib` (trying the `name_` mangling
75
+ first, then the un-mangled name) and assign the resolved function to
76
+ `self._<name>`. Per-call argtypes/restype are applied by
77
+ `_invoke` using the `fvs2py._routines.FVS_ROUTINES`
78
+ registry; no static signature is applied here.
79
+
80
+ Raises:
81
+ ImportError: If any needed routines are missing or not callable.
82
+ """
83
+ assert self._lib is not None # to satisfy type checker
84
+ missing: list[str] = []
85
+ for name in NEEDED_ROUTINES:
86
+ func: ct._FuncPointer | None = None
87
+ for candidate in (f"{name.lower()}_", name):
88
+ attr = getattr(self._lib, candidate, None)
89
+ if attr is not None and callable(attr):
90
+ func = attr
91
+ logging.debug(f"Found {name} as {candidate}.")
92
+ break
93
+ if func is None:
94
+ missing.append(name)
95
+ continue
96
+ setattr(self, f"_{name}", func)
97
+
98
+ if missing:
99
+ msg = " ".join([
100
+ ", ".join(missing),
101
+ "are needed routines that are not available in library, "
102
+ "(maybe they weren't exported when library was built)",
103
+ ])
104
+ raise ImportError(msg)
105
+
106
+ def _invoke(self, name: str, /, **kwargs: Any) -> Any:
107
+ """Dispatch a call to a registered FVS routine.
108
+
109
+ Looks up `name` in `fvs2py._routines.FVS_ROUTINES`, resolves
110
+ the bound foreign function at `self._<name>`, and hands off to
111
+ `fvs2py._routines.Routine.call` for argtype resolution, OUT
112
+ buffer allocation, return-code policy dispatch, and result unwrap.
113
+
114
+ Args:
115
+ name: Un-mangled FVS routine name (the same key used by
116
+ `NEEDED_ROUTINES`).
117
+ **kwargs: Per-parameter values; see the relevant
118
+ `fvs2py._routines.Routine` declaration for the
119
+ expected kwarg names.
120
+
121
+ Returns:
122
+ Whatever `fvs2py._routines.Routine.call` returns for the
123
+ routine: `None` when there are no non-rc OUT params, an
124
+ unwrapped scalar for a single OUT param, or a dict keyed by
125
+ OUT-param name for multiple OUT params.
126
+
127
+ Raises:
128
+ NotImplementedError: If `name` is not registered in
129
+ `FVS_ROUTINES` (either a typo or the routine has not
130
+ been migrated to the registry yet).
131
+ AttributeError: If the corresponding foreign function has not
132
+ been resolved on `self`.
133
+ """
134
+ try:
135
+ routine = FVS_ROUTINES[name]
136
+ except KeyError as exc:
137
+ msg = f"{name!r} is not registered in FVS_ROUTINES"
138
+ raise NotImplementedError(msg) from exc
139
+ func = getattr(self, f"_{name}")
140
+ return routine.call(func, **kwargs)
141
+
142
+ def _load_fvs(self) -> None:
143
+ """Load the FVS shared library into `self._lib`, unloading any prior handle."""
144
+ if self._lib:
145
+ logging.debug("Unloading existing library.")
146
+ self._unload_fvs()
147
+ self._lib = load_dll(self.lib_path)
148
+
149
+ def _unload_fvs(self) -> None:
150
+ """Unload the currently held FVS shared library, if any."""
151
+ if self._lib:
152
+ unload_dll(self._lib)
153
+ self._lib = None
154
+ else:
155
+ logging.debug("No library to unload.")
@@ -0,0 +1,25 @@
1
+ """Focused mixins that compose the `fvs2py.FVS` public API.
2
+
3
+ Each mixin owns a coherent slice of FVS functionality and assumes the instance
4
+ already has `self._lib` plus the resolved `_fvsXyz` foreign-function
5
+ attributes from `fvs2py._core.FvsCore` and the Python-side buffers
6
+ initialized by `FVS._initialize_attributes`.
7
+ """
8
+
9
+ from fvs2py._mixins.control import ControlMixin
10
+ from fvs2py._mixins.events import EventMixin
11
+ from fvs2py._mixins.simulation import SimulationMixin
12
+ from fvs2py._mixins.species import SpeciesMixin
13
+ from fvs2py._mixins.stand import StandMixin
14
+ from fvs2py._mixins.svs import SVSMixin
15
+ from fvs2py._mixins.trees import TreesMixin
16
+
17
+ __all__ = [
18
+ "ControlMixin",
19
+ "EventMixin",
20
+ "SVSMixin",
21
+ "SimulationMixin",
22
+ "SpeciesMixin",
23
+ "StandMixin",
24
+ "TreesMixin",
25
+ ]
@@ -0,0 +1,215 @@
1
+ """Keyfile-loading and stop-point control mixin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes as ct
6
+ import logging
7
+ import os
8
+ import warnings
9
+ from collections.abc import Callable
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from fvs2py.common import fvs_property
14
+ from fvs2py.enums import FvsItrnCode, FvsStopPointCode
15
+ from fvs2py.keyfile import validate_single_stand
16
+
17
+
18
+ class ControlMixin:
19
+ """Expose keyfile loading and stop-point configuration.
20
+
21
+ Assumes the composed class provides `FvsCore._invoke` for registry
22
+ dispatch, the `_itrncd` buffer, and the
23
+ `_stop_point_code`/`_stop_point_year` slots initialized by
24
+ `FVS._initialize_attributes`. `run` on `SimulationMixin`
25
+ is expected to call into `set_stop_point_codes`.
26
+ """
27
+
28
+ _invoke: Callable[..., Any]
29
+ _itrncd: ct.c_int
30
+ _stop_point_code: ct.c_int | None
31
+ _stop_point_year: ct.c_int | None
32
+ keyfile_path: Path | None
33
+ keyfile: str | None
34
+ itrncd: int
35
+ _reload_fvs: Callable[[], None]
36
+
37
+ @fvs_property
38
+ def stop_point_code(self) -> int | None:
39
+ """A code used to instruct FVS when to stop during a cycle.
40
+
41
+ -1 : Stop at every stop location.
42
+ 0 : Never stop.
43
+ 1 : Stop just before the first call to the Event Monitor.
44
+ 2 : Stop just after the first call to the Event Monitor.
45
+ 3 : Stop just before the second call to the Event Monitor.
46
+ 4 : Stop just after the second call to the Event Monitor.
47
+ 5 : Stop after growth and mortality has been computed, but prior to
48
+ applying them.
49
+ 6 : Stop just before the ESTAB routines are called.
50
+ 7 : Stop just after input is read but before missing values are imputed
51
+ (tree heights and crown ratios, for example) and model
52
+ calibration (argument stptyr is ignored).
53
+
54
+ Assigning to this property delegates to `set_stop_point_codes`,
55
+ preserving the currently-configured `stop_point_year` (or `0` if
56
+ year has not been set).
57
+ """
58
+ if self._stop_point_code is not None:
59
+ return self._stop_point_code.value
60
+ return None
61
+
62
+ @stop_point_code.setter # type: ignore[no-redef]
63
+ def stop_point_code(self, value: int) -> None:
64
+ year = (
65
+ self._stop_point_year.value
66
+ if self._stop_point_year is not None
67
+ else 0
68
+ )
69
+ self.set_stop_point_codes(value, year)
70
+
71
+ @fvs_property
72
+ def stop_point_year(self) -> int | None:
73
+ """A code indicating which cycles FVS should stop at.
74
+
75
+ 0 : Never stop.
76
+ 1 : Stop at every cycle.
77
+ YYYY : A specific year during the simulation period.
78
+
79
+ Assigning to this property delegates to `set_stop_point_codes`,
80
+ preserving the currently-configured `stop_point_code` (or `0` if
81
+ code has not been set).
82
+ """
83
+ if self._stop_point_year is not None:
84
+ return self._stop_point_year.value
85
+ return None
86
+
87
+ @stop_point_year.setter # type: ignore[no-redef]
88
+ def stop_point_year(self, value: int) -> None:
89
+ code = (
90
+ self._stop_point_code.value
91
+ if self._stop_point_code is not None
92
+ else 0
93
+ )
94
+ self.set_stop_point_codes(code, value)
95
+
96
+ def load_keyfile(
97
+ self,
98
+ keywordfile: str | os.PathLike,
99
+ *,
100
+ check_single_stand: bool = True,
101
+ ) -> None:
102
+ """Set the keywordfile as a command-line argument to FVS.
103
+
104
+ If `check_single_stand` is true (the default), the keyfile text is
105
+ first passed to `fvs2py.keyfile.validate_single_stand`; a keyfile
106
+ that describes zero or multiple stands raises `ValueError`
107
+ before FVS is invoked. Callers driving multi-stand runs via
108
+ `FVS.run_batch` must set `check_single_stand=False` to bypass
109
+ the guard.
110
+
111
+ Args:
112
+ keywordfile: Path to the FVS keyword file.
113
+ check_single_stand: When true (default), require the keyfile to define
114
+ exactly one stand (one each of `STDIDENT`, `PROCESS`,
115
+ and `STOP`).
116
+
117
+ Raises:
118
+ ValueError: If `check_single_stand` is true and the keyfile
119
+ fails `fvs2py.keyfile.validate_single_stand`.
120
+ """
121
+ if self.itrncd != FvsItrnCode.NOT_STARTED:
122
+ if self.itrncd != FvsItrnCode.FINISHED_ALL_STANDS:
123
+ msg = (
124
+ "FVS had not completed the previous simulation. "
125
+ "Outputs from that simulation may be incomplete."
126
+ )
127
+ warnings.warn(msg)
128
+ logging.debug("FVS was already started. Resetting.")
129
+ self._reload_fvs()
130
+
131
+ self.keyfile_path = Path(os.path.abspath(keywordfile))
132
+ with open(self.keyfile_path) as f:
133
+ self.keyfile = f.read()
134
+
135
+ if check_single_stand:
136
+ try:
137
+ validate_single_stand(self.keyfile)
138
+ except ValueError as exc:
139
+ msg = (
140
+ f"{exc}\n"
141
+ "If this keyfile is intended to describe multiple "
142
+ "stands, bypass this check by calling "
143
+ "`load_keyfile(..., check_single_stand=False)` and "
144
+ "drive the simulation via `FVS.run_batch()`."
145
+ )
146
+ raise ValueError(msg) from exc
147
+
148
+ cmdline = f"--keywordfile={self.keyfile_path}"
149
+ nch = len(cmdline)
150
+
151
+ self._invoke(
152
+ "fvsSetCmdLine",
153
+ cmdline=cmdline.encode(),
154
+ nch=ct.c_int(nch),
155
+ itrncd=self._itrncd,
156
+ )
157
+ logging.debug(f"Return code updated to {self.itrncd}")
158
+
159
+ def set_stop_point_codes(
160
+ self,
161
+ stop_point_code: int | None = None,
162
+ stop_point_year: int | None = None,
163
+ ) -> None:
164
+ """Sets FVS stop point codes.
165
+
166
+ Args:
167
+ stop_point_code (int): Optional code for when FVS should stop during
168
+ a cycle:
169
+ -1 : Stop at every stop location
170
+ 0 : Never stop
171
+ 1 : Stop just before the first call to the Event Monitor
172
+ 2 : Stop just after the first call to the Event Monitor
173
+ 3 : Stop just before the second call to the Event Monitor
174
+ 4 : Stop just after the second call to the Event Monitor
175
+ 5 : Stop after growth and mortality has been computed, but
176
+ prior to applying them
177
+ 6 : Stop just before the ESTAB routines are called
178
+ 7 : Stop just after input is read but before missing values
179
+ are imputed
180
+ stop_point_year (int): Optional, years FVS should stop, options are:
181
+ 0 : Never stop
182
+ -1 : Stop at every cycle
183
+ YYYY : A specific year during the simulation period
184
+
185
+ Raises:
186
+ ValueError: If `stop_point_code` is outside the range `[-1, 7]`,
187
+ or if `stop_point_year` is provided without `stop_point_code`.
188
+ """
189
+ if stop_point_code is not None:
190
+ try:
191
+ FvsStopPointCode(stop_point_code)
192
+ except ValueError as e:
193
+ msg = "Invalid value for stop_point_code"
194
+ raise ValueError(msg) from e
195
+ self._stop_point_code = ct.c_int(stop_point_code)
196
+ elif self._stop_point_code is None:
197
+ self._stop_point_code = ct.c_int(0)
198
+
199
+ if stop_point_year is not None:
200
+ if stop_point_code is not None:
201
+ self._stop_point_year = ct.c_int(stop_point_year)
202
+ else:
203
+ msg = (
204
+ "Must specify stop_point_year if also specifying "
205
+ "stop_point_code"
206
+ )
207
+ raise ValueError(msg)
208
+ elif self._stop_point_year is None:
209
+ self._stop_point_year = ct.c_int(0)
210
+
211
+ self._invoke(
212
+ "fvsSetStoppointCodes",
213
+ stop_point_code=self._stop_point_code,
214
+ stop_point_year=self._stop_point_year,
215
+ )