fvs2py 0.2.1__tar.gz

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-0.2.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Vibrant Planet, PBC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
fvs2py-0.2.1/PKG-INFO ADDED
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: fvs2py
3
+ Version: 0.2.1
4
+ Summary: Python wrapper for the Forest Vegetation Simulator API.
5
+ Author-email: David Diaz <ddiaz@vibrantplanet.net>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Vibrant-Planet-Open-Science/fvs2py
8
+ Project-URL: Repository, https://github.com/Vibrant-Planet-Open-Science/fvs2py
9
+ Project-URL: Issues, https://github.com/Vibrant-Planet-Open-Science/fvs2py/issues
10
+ Project-URL: Changelog, https://github.com/Vibrant-Planet-Open-Science/fvs2py/blob/main/CHANGELOG.md
11
+ Keywords: forest,growth,yield,fvs
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Scientific/Engineering
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.12
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: numpy<3,>=2.1
25
+ Requires-Dist: pandas<4,>=3.0
26
+ Provides-Extra: dev
27
+ Requires-Dist: ipykernel==7.2.0; extra == "dev"
28
+ Requires-Dist: mypy==2.1.0; extra == "dev"
29
+ Requires-Dist: nbval==0.11.0; extra == "dev"
30
+ Requires-Dist: pandas-stubs==3.0.0.260204; extra == "dev"
31
+ Requires-Dist: pre-commit==4.6.0; extra == "dev"
32
+ Requires-Dist: pytest-mock==3.15.1; extra == "dev"
33
+ Requires-Dist: pytest==9.0.3; extra == "dev"
34
+ Requires-Dist: ruff==0.15.13; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ # fvs2py
38
+ A Python wrapper of the [Forest Vegetation Simulator (FVS)](https://www.fs.usda.gov/fvs/).
39
+
40
+ This project has been designed to provide programmatic access to FVS through the [`FVS-API`](https://github.com/USDAForestService/ForestVegetationSimulator/wiki/FVS-API) from Python. It is inspired by and generally follows the pattern demonstrated by [`rFVS`](https://github.com/USDAForestService/ForestVegetationSimulator/wiki/rFVS), which loads a pre-compiled shared library of a single FVS variant and provides the user access to FVS variables and commands from a modern programming language.
41
+
42
+ Our initial focus is to replicate the functionality provided by `rFVS`.
43
+
44
+ We will then build upon the addition of new subroutines in Fortran that extend the underlying `FVS-API` and to produce corresponding wrapper functions here in `fvs2py` that will allow users access to get and set a broader suite of FVS parameters. The ultimate goal for this Python API is to allow users to run FVS, get and set simulation parameters at runtime, and to retrieve FVS output tables at runtime and in-memory without needing to interact with an external database or other output files.
45
+
46
+ ## Installation
47
+
48
+ ```bash
49
+ pip install fvs2py
50
+ ```
51
+
52
+ fvs2py doesn't include the FVS libraries. You supply a compiled FVS variant library, either your own build or one from the [`usfs-fvs` container image](https://github.com/Vibrant-Planet-Open-Science/fvs-build/pkgs/container/usfs-fvs) (`ghcr.io/vibrant-planet-open-science/usfs-fvs`), which has every variant's library at `/usr/local/lib/FVS<variant>.so`.
53
+
54
+ ## Usage
55
+
56
+ ```python
57
+ from fvs2py import FVS
58
+
59
+ fvs = FVS("/path/to/FVSpn.so")
60
+ fvs.load_keyfile("name.key")
61
+ fvs.run()
62
+ fvs.summary # pandas DataFrame
63
+ ```
64
+
65
+ ## Command line
66
+
67
+ fvs2py also installs an `fvs` command that works like FVS executables do. These two commands are equivalent:
68
+
69
+ ```bash
70
+ FVSpn --keywordfile=name.key
71
+ fvs --lib=/path/to/FVSpn.so --keywordfile=name.key
72
+ ```
73
+
74
+ Most users of `fvs2py` should primarily expect to use the Python interface. The CLI is for running FVS in a separate process, so a crash by FVS doesn't take down your program and its output can be captured.
75
+
76
+ ## Development
77
+
78
+ A **dev container** is provided under [`.devcontainer/`](https://github.com/Vibrant-Planet-Open-Science/fvs2py/tree/main/.devcontainer) for VS Code. Open the repository with **Dev Containers: Reopen in Container** to get the `dev` Docker target, Python tooling, and extensions preconfigured. On first open, `postCreateCommand` runs `uv sync --frozen --extra dev` (creating a project-local `.venv` in your clone, gitignored) and installs pre-commit hooks. After pulling changes that touch the Dockerfile or lockfile, **rebuild** the dev container (or run `uv sync --extra dev` manually).
79
+
80
+ The `.venv` directory lives on your host via the bind-mounted workspace (Linux binaries from the container). You can delete it and re-run `uv sync --extra dev` to recreate.
81
+
82
+ If you don't want to use a dev container, install dev dependencies and hooks the same way before opening a pull request:
83
+
84
+ ```bash
85
+ uv sync --extra dev
86
+ uv run pre-commit install
87
+ ```
88
+
89
+ Run tests locally or inside the dev container:
90
+
91
+ ```bash
92
+ uv run pytest .
93
+ ```
94
+
95
+ Hooks run on each commit (secret scan, Ruff, mypy). Run them manually with `uv run pre-commit run --all-files`. CI runs the same checks on pull requests via the Lint workflow, and runs pytest in the `dev` Docker image via the Pytest workflow.
fvs2py-0.2.1/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # fvs2py
2
+ A Python wrapper of the [Forest Vegetation Simulator (FVS)](https://www.fs.usda.gov/fvs/).
3
+
4
+ This project has been designed to provide programmatic access to FVS through the [`FVS-API`](https://github.com/USDAForestService/ForestVegetationSimulator/wiki/FVS-API) from Python. It is inspired by and generally follows the pattern demonstrated by [`rFVS`](https://github.com/USDAForestService/ForestVegetationSimulator/wiki/rFVS), which loads a pre-compiled shared library of a single FVS variant and provides the user access to FVS variables and commands from a modern programming language.
5
+
6
+ Our initial focus is to replicate the functionality provided by `rFVS`.
7
+
8
+ We will then build upon the addition of new subroutines in Fortran that extend the underlying `FVS-API` and to produce corresponding wrapper functions here in `fvs2py` that will allow users access to get and set a broader suite of FVS parameters. The ultimate goal for this Python API is to allow users to run FVS, get and set simulation parameters at runtime, and to retrieve FVS output tables at runtime and in-memory without needing to interact with an external database or other output files.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ pip install fvs2py
14
+ ```
15
+
16
+ fvs2py doesn't include the FVS libraries. You supply a compiled FVS variant library, either your own build or one from the [`usfs-fvs` container image](https://github.com/Vibrant-Planet-Open-Science/fvs-build/pkgs/container/usfs-fvs) (`ghcr.io/vibrant-planet-open-science/usfs-fvs`), which has every variant's library at `/usr/local/lib/FVS<variant>.so`.
17
+
18
+ ## Usage
19
+
20
+ ```python
21
+ from fvs2py import FVS
22
+
23
+ fvs = FVS("/path/to/FVSpn.so")
24
+ fvs.load_keyfile("name.key")
25
+ fvs.run()
26
+ fvs.summary # pandas DataFrame
27
+ ```
28
+
29
+ ## Command line
30
+
31
+ fvs2py also installs an `fvs` command that works like FVS executables do. These two commands are equivalent:
32
+
33
+ ```bash
34
+ FVSpn --keywordfile=name.key
35
+ fvs --lib=/path/to/FVSpn.so --keywordfile=name.key
36
+ ```
37
+
38
+ Most users of `fvs2py` should primarily expect to use the Python interface. The CLI is for running FVS in a separate process, so a crash by FVS doesn't take down your program and its output can be captured.
39
+
40
+ ## Development
41
+
42
+ A **dev container** is provided under [`.devcontainer/`](https://github.com/Vibrant-Planet-Open-Science/fvs2py/tree/main/.devcontainer) for VS Code. Open the repository with **Dev Containers: Reopen in Container** to get the `dev` Docker target, Python tooling, and extensions preconfigured. On first open, `postCreateCommand` runs `uv sync --frozen --extra dev` (creating a project-local `.venv` in your clone, gitignored) and installs pre-commit hooks. After pulling changes that touch the Dockerfile or lockfile, **rebuild** the dev container (or run `uv sync --extra dev` manually).
43
+
44
+ The `.venv` directory lives on your host via the bind-mounted workspace (Linux binaries from the container). You can delete it and re-run `uv sync --extra dev` to recreate.
45
+
46
+ If you don't want to use a dev container, install dev dependencies and hooks the same way before opening a pull request:
47
+
48
+ ```bash
49
+ uv sync --extra dev
50
+ uv run pre-commit install
51
+ ```
52
+
53
+ Run tests locally or inside the dev container:
54
+
55
+ ```bash
56
+ uv run pytest .
57
+ ```
58
+
59
+ Hooks run on each commit (secret scan, Ruff, mypy). Run them manually with `uv run pre-commit run --all-files`. CI runs the same checks on pull requests via the Lint workflow, and runs pytest in the `dev` Docker image via the Pytest workflow.
@@ -0,0 +1,3 @@
1
+ from ._base import FVS
2
+
3
+ __all__ = ["FVS"]
@@ -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()
@@ -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
+ )