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/cli.py ADDED
@@ -0,0 +1,78 @@
1
+ """The `fvs` command, a drop-in for the `FVS<variant>` executables.
2
+
3
+ These two commands do the same thing:
4
+
5
+ FVSpn --keywordfile=name.key
6
+ fvs --lib=/usr/local/lib/FVSpn.so --keywordfile=name.key
7
+
8
+ Every argument other than `--lib` is passed straight to FVS. The exit status matches the FVS executables: 0 on success, otherwise
9
+ 10 times the FVS error code.
10
+
11
+ Run `fvs` as a subprocess to survive FVS crashes and capture its output.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import ctypes as ct
18
+ import faulthandler
19
+ import os
20
+ import sys
21
+
22
+ from fvs2py._base import FVS
23
+ from fvs2py.enums import FvsItrnCode
24
+
25
+
26
+ def main(argv: list[str] | None = None) -> int:
27
+ """Run FVS with CLI semantics and return the process exit status.
28
+
29
+ Args:
30
+ argv: Command-line arguments, excluding the program name. Defaults
31
+ to `sys.argv[1:]`.
32
+
33
+ Returns:
34
+ `0` on success, otherwise `10 * fvsGetICCode` like the FVS CLI.
35
+ """
36
+ parser = argparse.ArgumentParser(
37
+ prog="fvs",
38
+ description=(
39
+ "Run FVS through fvs2py. Arguments other than --lib are passed "
40
+ "to FVS unchanged."
41
+ ),
42
+ allow_abbrev=False,
43
+ )
44
+ parser.add_argument(
45
+ "--lib", required=True, help="path to the FVS shared library"
46
+ )
47
+ args, fvs_args = parser.parse_known_args(argv)
48
+
49
+ if not os.path.isfile(args.lib):
50
+ parser.error(f"--lib {args.lib!r} does not exist")
51
+
52
+ # Python traceback on SIGSEGV/SIGFPE/SIGABRT; the signal is re-raised so
53
+ # the parent still sees a negative return code.
54
+ faulthandler.enable()
55
+ # Must be set before libgfortran initializes (on library load), or
56
+ # output buffered just before a crash is lost.
57
+ os.environ.setdefault("GFORTRAN_UNBUFFERED_PRECONNECTED", "y")
58
+
59
+ fvs = FVS(args.lib)
60
+
61
+ cmdline = " ".join(fvs_args).encode()
62
+ fvs._invoke(
63
+ "fvsSetCmdLine",
64
+ cmdline=cmdline,
65
+ nch=ct.c_int(len(cmdline)),
66
+ itrncd=fvs._itrncd,
67
+ )
68
+ while fvs.itrncd == FvsItrnCode.GOOD_RUNNING_STATE:
69
+ fvs._invoke("fvs", itrncd=fvs._itrncd)
70
+
71
+ status = 10 * fvs.exit_code
72
+ if status:
73
+ sys.stderr.write(f"STOP {status}\n")
74
+ return status
75
+
76
+
77
+ if __name__ == "__main__":
78
+ sys.exit(main())
fvs2py/common.py ADDED
@@ -0,0 +1,280 @@
1
+ from __future__ import annotations
2
+
3
+ import ctypes as ct
4
+ import functools
5
+ import logging
6
+ import os
7
+ import sys
8
+ from collections.abc import Callable
9
+ from typing import Any, ParamSpec, TypeVar, cast
10
+
11
+ P = ParamSpec("P")
12
+ T = TypeVar("T")
13
+
14
+
15
+ def load_dll(dll_path: str | os.PathLike) -> ct.CDLL:
16
+ """Loads a native FVS library.
17
+
18
+ Works on Linux (`.so`), Windows (`.dll`), and macOS (`.dylib`).
19
+ The caller supplies the full path including the file suffix.
20
+
21
+ The FVS libraries are assumed to be statically linked, and loader search
22
+ path manipulation is included to allow for the detection of dependent DLLs.
23
+
24
+ Args:
25
+ dll_path (str | os.PathLike): the path to the DLL to be loaded.
26
+
27
+ Returns:
28
+ the loaded DLL as a ctypes CDLL instance
29
+ """
30
+ dll_path_str = os.fspath(dll_path)
31
+ logging.info(f"Loading library from {dll_path_str}")
32
+ dll = ct.CDLL(dll_path_str)
33
+ logging.info(f"Library loaded successfully from {dll_path_str}")
34
+ return dll
35
+
36
+
37
+ def unload_dll(dll: ct.CDLL) -> None:
38
+ """Unloads a native FVS library.
39
+
40
+ Uses `FreeLibrary` on Windows and `dlclose` elsewhere (Linux and
41
+ macOS). On success the handle is zeroed so a repeat unload cannot hand
42
+ a stale handle back to the loader.
43
+
44
+ Args:
45
+ dll: the loaded DLL.
46
+
47
+ Raises:
48
+ RuntimeError: if the platform loader refused to unload the library.
49
+ """
50
+ if sys.platform == "win32":
51
+ _free_library(dll._handle)
52
+ else:
53
+ _dlclose(dll._handle)
54
+ dll._handle = 0
55
+ logging.debug("Library unloaded successfully.")
56
+
57
+
58
+ def _free_library(handle: int) -> None:
59
+ """Release a loaded library handle with the Windows `FreeLibrary`.
60
+
61
+ Args:
62
+ handle: the `_handle` of the loaded library.
63
+
64
+ Raises:
65
+ RuntimeError: if `FreeLibrary` reports failure.
66
+ """
67
+ kernel32 = ct.WinDLL("kernel32", use_last_error=True) # type: ignore[attr-defined]
68
+ free_library = kernel32.FreeLibrary
69
+ free_library.argtypes = (ct.c_void_p,)
70
+ free_library.restype = ct.c_int
71
+ if not free_library(handle):
72
+ err = ct.get_last_error() # type: ignore[attr-defined]
73
+ msg = f"Failed to unload DLL: FreeLibrary error {err}"
74
+ raise RuntimeError(msg)
75
+
76
+
77
+ def _dlclose(handle: int) -> None:
78
+ """Release a loaded library handle with the POSIX `dlclose`.
79
+
80
+ Args:
81
+ handle: the `_handle` of the loaded library.
82
+
83
+ Raises:
84
+ RuntimeError: if `dlclose` returns non-zero.
85
+ """
86
+ close_func = ct.CDLL(None).dlclose
87
+ close_func.argtypes = (ct.c_void_p,)
88
+ close_func.restype = ct.c_int
89
+ result = close_func(handle)
90
+ if result != 0:
91
+ msg = f"Failed to unload DLL: {result}"
92
+ raise RuntimeError(msg)
93
+
94
+
95
+ def function_requires_fvs_library() -> Callable[
96
+ [Callable[P, T]], Callable[P, T]
97
+ ]:
98
+ """Decorator ensuring a ._lib attribute is present and not None.
99
+
100
+ This decorator is intended to be applied to instance methods that rely upon
101
+ accessing attributes or routines frome the FVS library. If the FVS library has been
102
+ unloaded without this protection, a segmentation fault would occur.
103
+ """
104
+
105
+ def decorator(func: Callable[P, T]) -> Callable[P, T]:
106
+ @functools.wraps(func)
107
+ def wrapper(self, *args, **kwargs) -> T:
108
+ if not hasattr(self, "_lib") or self._lib is None:
109
+ msg = f"FVS library not loaded, unable to call {func.__name__}."
110
+ raise RuntimeError(msg)
111
+ return func(self, *args, **kwargs)
112
+
113
+ return cast(Callable[P, T], wrapper)
114
+
115
+ return decorator
116
+
117
+
118
+ class fvs_property:
119
+ """Property descriptor with an FVS-library-loaded guard.
120
+
121
+ Behaves like the built-in `property`, but before invoking either the
122
+ getter or the setter it checks that the instance has a non-`None` `_lib`
123
+ attribute and raises `RuntimeError` otherwise. Guarding here prevents
124
+ the segmentation fault that would result from calling into an unloaded FVS
125
+ shared library.
126
+
127
+ Supports the standard `@<name>.setter` fluent syntax, mirroring the
128
+ stdlib `property`. Setters receive the same `_lib`-loaded guard
129
+ as getters.
130
+
131
+ Args:
132
+ fget: Getter function taking `self` and returning the property
133
+ value.
134
+ fset: Optional setter function taking `self` and the new value.
135
+ """
136
+
137
+ def __init__(
138
+ self,
139
+ fget: Callable[[Any], Any] | None = None,
140
+ fset: Callable[[Any, Any], None] | None = None,
141
+ ) -> None:
142
+ self.fget = fget
143
+ self.fset = fset
144
+ self.__doc__ = fget.__doc__ if fget is not None else None
145
+ self.__name__ = fget.__name__ if fget is not None else ""
146
+
147
+ def _check_lib(self, obj: Any, action: str) -> None:
148
+ """Raise if `obj._lib` is missing or `None`."""
149
+ if not hasattr(obj, "_lib") or obj._lib is None:
150
+ msg = (
151
+ f"FVS library not loaded, unable to "
152
+ f"{action} {self.__name__} property."
153
+ )
154
+ raise RuntimeError(msg)
155
+
156
+ def __get__(self, obj: Any, objtype: type | None = None) -> Any:
157
+ """Invoke the wrapped getter after verifying the library is loaded."""
158
+ if obj is None:
159
+ return self
160
+ if self.fget is None:
161
+ msg = f"property {self.__name__!r} has no getter"
162
+ raise AttributeError(msg)
163
+ self._check_lib(obj, "access")
164
+ return self.fget(obj)
165
+
166
+ def __set__(self, obj: Any, value: Any) -> None:
167
+ """Invoke the wrapped setter after verifying the library is loaded."""
168
+ if self.fset is None:
169
+ msg = f"property {self.__name__!r} has no setter"
170
+ raise AttributeError(msg)
171
+ self._check_lib(obj, "set")
172
+ self.fset(obj, value)
173
+
174
+ def setter(self, fset: Callable[[Any, Any], None]) -> fvs_property:
175
+ """Return a new `fvs_property` combining `self.fget` with `fset`.
176
+
177
+ Supports the `@<name>.setter` fluent syntax used with the stdlib
178
+ `property`.
179
+
180
+ Args:
181
+ fset: Setter function taking `self` and a new value.
182
+
183
+ Returns:
184
+ A new `fvs_property` sharing this descriptor's getter and
185
+ using `fset` as its setter.
186
+ """
187
+ return type(self)(self.fget, fset)
188
+
189
+
190
+ def no_fvs_library_required[**P, T](func: Callable[P, T]) -> Callable[P, T]:
191
+ """Mark a method so `class_requires_fvs_library` leaves it unwrapped.
192
+
193
+ Use this to opt a pure-Python helper out of the automatic `_lib`-loaded
194
+ guard applied by `class_requires_fvs_library`. The marker is read
195
+ from the underlying function object during class decoration.
196
+
197
+ Args:
198
+ func: Instance method to leave unguarded.
199
+
200
+ Returns:
201
+ The same function object with a `_fvs_library_required` attribute set
202
+ to `False`.
203
+ """
204
+ func._fvs_library_required = False # type: ignore[attr-defined]
205
+ return func
206
+
207
+
208
+ def class_requires_fvs_library[ClassT: type](cls: ClassT) -> ClassT:
209
+ """Decorator enforcing `function_requires_fvs_library` for all public methods.
210
+
211
+ Walks `cls.__mro__` so that public methods contributed by mixins receive
212
+ the same `_lib`-loaded guard that methods defined directly on `cls`
213
+ get. The first occurrence of each public name wins (respecting MRO), so
214
+ overrides on `cls` are not shadowed by same-named methods on a base.
215
+
216
+ Skips:
217
+ - names that start with `_` (private / dunder).
218
+ - non-callables (e.g. `property` descriptors, which are expected to
219
+ carry their own guard via `fvs_property`).
220
+ - `staticmethod` / `classmethod` descriptors — they have no `self`
221
+ to inspect and their own guard would have to be different.
222
+ - methods marked with `no_fvs_library_required`.
223
+ - methods already wrapped by a previous call (idempotent).
224
+
225
+ Args:
226
+ cls: The class to decorate.
227
+
228
+ Returns:
229
+ The same class, with public methods replaced by `_lib`-guarded
230
+ wrappers.
231
+ """
232
+ wrapped_names: set[str] = set()
233
+ for base in cls.__mro__:
234
+ if base is object:
235
+ continue
236
+ for name, method in vars(base).items():
237
+ if name in wrapped_names:
238
+ continue
239
+ if name.startswith("_") or not callable(method):
240
+ continue
241
+ if isinstance(method, (staticmethod, classmethod)):
242
+ continue
243
+ if getattr(method, "_fvs_library_required", True) is False:
244
+ continue
245
+ if getattr(method, "_fvs_wrapped", False):
246
+ continue
247
+ wrapped = function_requires_fvs_library()(method)
248
+ wrapped._fvs_wrapped = True # type: ignore[attr-defined]
249
+ setattr(cls, name, wrapped)
250
+ wrapped_names.add(name)
251
+ return cls
252
+
253
+
254
+ def call_out(
255
+ func: Callable[..., Any],
256
+ *in_args: Any,
257
+ out_types: tuple[type, ...] = (ct.c_int,),
258
+ ) -> Any:
259
+ """Call a ctypes function, auto-allocating output pointer args.
260
+
261
+ Allocates one fresh ctypes object of each type in `out_types`, appends
262
+ them (in order) after `in_args` when calling `func`, and returns the
263
+ unwrapped `.value` of each output.
264
+
265
+ Args:
266
+ func: Resolved ctypes foreign function whose trailing parameters are
267
+ `POINTER` types corresponding to `out_types`.
268
+ *in_args: Positional input arguments passed to `func` unchanged.
269
+ out_types: Ctypes scalar types to allocate as output parameters.
270
+ Defaults to a single `ct.c_int` output.
271
+
272
+ Returns:
273
+ The scalar value if exactly one output was requested, otherwise a
274
+ tuple of unwrapped scalars in declaration order.
275
+ """
276
+ outs = [t(0) for t in out_types]
277
+ func(*in_args, *outs)
278
+ if len(outs) == 1:
279
+ return outs[0].value
280
+ return tuple(o.value for o in outs)
fvs2py/constants.py ADDED
@@ -0,0 +1,328 @@
1
+ STR_C_CONTIGUOUS = "C_CONTIGUOUS"
2
+ # core forest vegetation simulator attribute names
3
+ STR_MAXCYCLES = "maxcycles"
4
+ STR_MAXPLOTS = "maxplots"
5
+ STR_MAXSPECIES = "maxspecies"
6
+ STR_MAXTREES = "maxtrees"
7
+ STR_NCYCLES = "ncycles"
8
+ STR_NPLOTS = "nplots"
9
+ STR_NTREES = "ntrees"
10
+ # stand visualization system attribute names
11
+ STR_NSVSOBJS = "nsvsobjs"
12
+ STR_NDEADOBJS = "ndeadobjs"
13
+ STR_NCWDOBJS = "ncwdobjs"
14
+ STR_MXSVSOBJS = "mxsvsobjs"
15
+ STR_MXDEADOBJS = "mxdeadobjs"
16
+ STR_MXCWDOBJS = "mxcwdobjs"
17
+ STR_NOBJS = "nobjs"
18
+
19
+ STAND_CN_COLUMN_NAME = "stand_cn"
20
+ STAND_ID_COLUMN_NAME = "stand_id"
21
+ MGMT_ID_COLUMN_NAME = "mgmt_id"
22
+
23
+ NEEDED_ROUTINES = (
24
+ "fvs",
25
+ "fvsAddActivity",
26
+ "fvsAddTrees",
27
+ "fvsDimSizes",
28
+ "fvsEvmonAttr",
29
+ "fvsFFEAttrs",
30
+ "fvsGetRestartCode",
31
+ "fvsGetRtnCode",
32
+ "fvsGetICCode",
33
+ "fvsSVSDimSizes",
34
+ "fvsSetStoppointCodes",
35
+ "fvsSetCmdLine",
36
+ "fvsSVSObjData",
37
+ "fvsSpeciesAttr",
38
+ "fvsSpeciesCode",
39
+ "fvsStandID",
40
+ "fvsSummary",
41
+ "fvsTreeAttr",
42
+ "fvsUnitConversion",
43
+ )
44
+
45
+ SPECIES_INDEX_COLUMN_NAME = "fvs_index"
46
+ SPECIES_ALPHA_COLUMN_NAME = "fvs_alpha"
47
+ SPECIES_FIA_COLUMN_NAME = "fia"
48
+ SPECIES_PLANTS_COLUMN_NAME = "plants"
49
+ SPECIES_COLUMN_NAMES = [
50
+ SPECIES_INDEX_COLUMN_NAME,
51
+ SPECIES_ALPHA_COLUMN_NAME,
52
+ SPECIES_FIA_COLUMN_NAME,
53
+ SPECIES_PLANTS_COLUMN_NAME,
54
+ ]
55
+ ADD_TREES_COLS = (
56
+ "dbh",
57
+ "species",
58
+ "ht",
59
+ "cratio",
60
+ "plot",
61
+ "tpa",
62
+ )
63
+
64
+ TREE_ATTRS = (
65
+ "age",
66
+ "bapctile",
67
+ "bdft",
68
+ "cratio",
69
+ "crownwt0",
70
+ "crownwt1",
71
+ "crownwt2",
72
+ "crownwt3",
73
+ "crownwt4",
74
+ "crownwt5",
75
+ "crwdth",
76
+ "dbh",
77
+ "defect",
78
+ "dg",
79
+ "ht",
80
+ "htg",
81
+ "id",
82
+ "mcuft",
83
+ "mgmtcd",
84
+ "mort",
85
+ "plot",
86
+ "plotsize",
87
+ "ptbalt",
88
+ "scuft",
89
+ "special",
90
+ "species",
91
+ "tcuft",
92
+ "tpa",
93
+ )
94
+
95
+ SPECIES_ATTRS = (
96
+ "baimult",
97
+ "bfmeth",
98
+ "bfmind",
99
+ "bfstmp",
100
+ "bftopd",
101
+ "frmcls",
102
+ "htgmult",
103
+ "maxdbh",
104
+ "maxdbhcd",
105
+ "maxht",
106
+ "mcmeth",
107
+ "mcmind",
108
+ "mcstmp",
109
+ "mctopd",
110
+ "minmort",
111
+ "mortdia1",
112
+ "mortdia2",
113
+ "mortmult",
114
+ "regdmult",
115
+ "reghmult",
116
+ "spccf",
117
+ "spsdi",
118
+ "spsiteindx",
119
+ )
120
+
121
+ FFE_FALLYRS_ATTRS = (
122
+ "fallyrs0",
123
+ "fallyrs1",
124
+ "fallyrs2",
125
+ "fallyrs3",
126
+ "fallyrs4",
127
+ "fallyrs5",
128
+ )
129
+
130
+ # `fvsSVSObjData` (live 3D objects, standing dead snags, and coarse
131
+ # woody debris). Length of each array is the corresponding current
132
+ # count from `fvsSVSDimSizes`.
133
+ SVS_LIVE_OBJ_ATTRS = (
134
+ "objtype",
135
+ "objindex",
136
+ "xloc",
137
+ "yloc",
138
+ )
139
+ SVS_SNAG_OBJ_ATTRS = (
140
+ "snagdbh",
141
+ "snaglen",
142
+ "snagyear",
143
+ "snagspp",
144
+ "snagfdir",
145
+ "snagstat",
146
+ "snagwt0",
147
+ "snagwt1",
148
+ "snagwt2",
149
+ "snagwt3",
150
+ )
151
+ SVS_CWD_OBJ_ATTRS = (
152
+ "cwddia",
153
+ "cwdlen",
154
+ "cwdpil",
155
+ "cwddir",
156
+ "cwdwt",
157
+ )
158
+ SVS_OBJ_ATTRS: tuple[str, ...] = (
159
+ SVS_LIVE_OBJ_ATTRS + SVS_SNAG_OBJ_ATTRS + SVS_CWD_OBJ_ATTRS
160
+ )
161
+
162
+ EVMON_ATTRS = (
163
+ "aabvbio",
164
+ "aabvcrb",
165
+ "aadbh",
166
+ "aba",
167
+ "abdft",
168
+ "acancov",
169
+ "acc",
170
+ "accf",
171
+ "adbhwtba",
172
+ "afolbio",
173
+ "afolcrb",
174
+ "age",
175
+ "agecmp",
176
+ "ahtwtba",
177
+ "amaxhs",
178
+ "amcuft",
179
+ "amerbio",
180
+ "amercrb",
181
+ "aminhs",
182
+ "anumss",
183
+ "arden",
184
+ "arden2",
185
+ "asawbio",
186
+ "asawcrb",
187
+ "asclass",
188
+ "ascuft",
189
+ "asdi",
190
+ "asdi2",
191
+ "asdimax",
192
+ "aspect",
193
+ "astrdbh",
194
+ "atcuft",
195
+ "atopht",
196
+ "atpa",
197
+ "babvbio",
198
+ "babvcrb",
199
+ "badbh",
200
+ "bba",
201
+ "bbdft",
202
+ "bcancov",
203
+ "bccf",
204
+ "bdbhwtba",
205
+ "bfolbio",
206
+ "bfolcrb",
207
+ "bmaxhs",
208
+ "bmcuft",
209
+ "bmerbio",
210
+ "bmercrb",
211
+ "bminhs",
212
+ "bnumss",
213
+ "brden",
214
+ "brden2",
215
+ "bsawbio",
216
+ "bsawcrb",
217
+ "bsclass",
218
+ "bscuft",
219
+ "bsdi",
220
+ "bsdi2",
221
+ "bsdimax",
222
+ "bstrdbh",
223
+ "btcuft",
224
+ "btopht",
225
+ "btpa",
226
+ "bw%stnd",
227
+ "cendyear",
228
+ "county",
229
+ "crbaseht",
230
+ "crbulkdn",
231
+ "crownidx",
232
+ "cut",
233
+ "cycle",
234
+ "dba",
235
+ "dba%",
236
+ "dccf",
237
+ "dccf%",
238
+ "disccost",
239
+ "discrate",
240
+ "discrevn",
241
+ "dtpa",
242
+ "dtpa%",
243
+ "ecbdft",
244
+ "ecbdft",
245
+ "eccuft",
246
+ "eccuft",
247
+ "elev",
248
+ "evphase",
249
+ "fire",
250
+ "fireyear",
251
+ "fisherin",
252
+ "forstval",
253
+ "fortyp",
254
+ "habtype",
255
+ "harvcost",
256
+ "harvrevn",
257
+ "herbwt",
258
+ "invyear",
259
+ "irr",
260
+ "lat",
261
+ "long",
262
+ "mai",
263
+ "minsoil",
264
+ "mort",
265
+ "mpbprob",
266
+ "mpbtpak",
267
+ "no",
268
+ "numtrees",
269
+ "pai",
270
+ "pctcost",
271
+ "pnv",
272
+ "propstk",
273
+ "rabvbio",
274
+ "rabvcrb",
275
+ "rbdft",
276
+ "rfolbio",
277
+ "rfolcrb",
278
+ "rmcuft",
279
+ "rmerbio",
280
+ "rmercrb",
281
+ "rprodval",
282
+ "rsawbio",
283
+ "rsawcrb",
284
+ "rscuft",
285
+ "rtcuft",
286
+ "rtpa",
287
+ "sampwt",
288
+ "sev",
289
+ "shrubwt",
290
+ "silvahft",
291
+ "site",
292
+ "sizcls",
293
+ "slope",
294
+ "smr",
295
+ "state",
296
+ "stkcls",
297
+ "tm%df",
298
+ "tm%gf",
299
+ "tm%stnd",
300
+ "torchidx",
301
+ "undiscst",
302
+ "undisrvn",
303
+ "year",
304
+ "yes",
305
+ )
306
+
307
+ SUMMARY_COLS = (
308
+ "year",
309
+ "age",
310
+ "tpa",
311
+ "tcuft",
312
+ "mcuft",
313
+ "bdft",
314
+ "rtpa",
315
+ "rtcuft",
316
+ "rmcuft",
317
+ "rbdft",
318
+ "atba",
319
+ "atccf",
320
+ "attopht",
321
+ "prdlen",
322
+ "acc",
323
+ "mort",
324
+ "sampwt",
325
+ "fortyp",
326
+ "sizecls",
327
+ "stkcls",
328
+ )