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.
@@ -0,0 +1,102 @@
1
+ """Stand identification, dimensions, and summary mixin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes as ct
6
+ from collections.abc import Callable
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from fvs2py.common import fvs_property
13
+ from fvs2py.constants import (
14
+ MGMT_ID_COLUMN_NAME,
15
+ STAND_CN_COLUMN_NAME,
16
+ STAND_ID_COLUMN_NAME,
17
+ STR_NCYCLES,
18
+ SUMMARY_COLS,
19
+ )
20
+
21
+
22
+ class StandMixin:
23
+ """Expose stand-level FVS outputs: dimensions, identifiers, summary table.
24
+
25
+ Assumes the composed class provides `FvsCore._invoke` for registry
26
+ dispatch and the Python-side buffers `_stand_id`, `_stand_cn`,
27
+ `_mgmt_id` (initialized by `FVS._initialize_attributes`). `keyfile`
28
+ and `stop_point_code` come from `ControlMixin`.
29
+ """
30
+
31
+ _invoke: Callable[..., Any]
32
+ _stand_id: ct.Array[ct.c_char]
33
+ _stand_cn: ct.Array[ct.c_char]
34
+ _mgmt_id: ct.Array[ct.c_char]
35
+ keyfile: str | None
36
+ stop_point_code: int | None
37
+
38
+ @fvs_property
39
+ def dims(self) -> dict:
40
+ """Return the max dimensions of important FVS data storage."""
41
+ return self._invoke("fvsDimSizes")
42
+
43
+ @fvs_property
44
+ def stand_ids(self) -> dict:
45
+ """Return stand identification codes.
46
+
47
+ Raises:
48
+ AttributeError: If no keyfile has been loaded.
49
+ RuntimeError: If inventory data has not yet been loaded (i.e.
50
+ `run` has not been called).
51
+ """
52
+ if self.keyfile is None:
53
+ msg = "Keyfile not loaded yet."
54
+ raise AttributeError(msg)
55
+ if self.stop_point_code is None:
56
+ msg = "No inventory data loaded yet. Call `run` method."
57
+ raise RuntimeError(msg)
58
+
59
+ self._invoke(
60
+ "fvsStandID",
61
+ stand_id=self._stand_id,
62
+ stand_cn=self._stand_cn,
63
+ mgmt_id=self._mgmt_id,
64
+ stand_id_len=ct.c_int(0),
65
+ stand_cn_len=ct.c_int(0),
66
+ mgmt_id_len=ct.c_int(0),
67
+ )
68
+
69
+ return {
70
+ STAND_ID_COLUMN_NAME: self._stand_id.value.decode().strip(),
71
+ STAND_CN_COLUMN_NAME: self._stand_cn.value.decode().strip(),
72
+ MGMT_ID_COLUMN_NAME: self._mgmt_id.value.decode().strip(),
73
+ }
74
+
75
+ @fvs_property
76
+ def summary(self) -> pd.DataFrame | None:
77
+ """Return a dataframe with FVS Summary Statistics for all initiated cycles.
78
+
79
+ The returned dataframe omits cycles that have not yet been initiated, which are
80
+ identifiable where all values in that row are zero.
81
+ """
82
+ dims = self.dims
83
+ if dims[STR_NCYCLES] == 0:
84
+ return None
85
+ summary = np.zeros(
86
+ dtype=np.intc,
87
+ shape=(dims[STR_NCYCLES] + 1, len(SUMMARY_COLS)),
88
+ )
89
+ for i in range(dims[STR_NCYCLES] + 1):
90
+ self._invoke(
91
+ "fvsSummary",
92
+ summary=summary[i],
93
+ icycle=ct.c_int(i + 1),
94
+ ncycles=ct.c_int(dims[STR_NCYCLES]),
95
+ maxrow=ct.c_int(0),
96
+ maxcol=ct.c_int(0),
97
+ )
98
+
99
+ empty_years = (summary == 0).all(axis=1)
100
+ return pd.DataFrame(
101
+ summary[~empty_years, :], columns=SUMMARY_COLS
102
+ ).copy()
fvs2py/_mixins/svs.py ADDED
@@ -0,0 +1,166 @@
1
+ """SVS/FFE API: `fvsSVSDimSizes`, `fvsSVSObjData`, and `fvsFFEAttrs`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes as ct
6
+ import warnings
7
+ from collections.abc import Callable
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+ import numpy.typing as npt
12
+ import pandas as pd
13
+
14
+ from fvs2py.common import fvs_property
15
+ from fvs2py.constants import (
16
+ STR_MAXSPECIES,
17
+ STR_NCWDOBJS,
18
+ STR_NDEADOBJS,
19
+ STR_NSVSOBJS,
20
+ SVS_CWD_OBJ_ATTRS,
21
+ SVS_LIVE_OBJ_ATTRS,
22
+ SVS_SNAG_OBJ_ATTRS,
23
+ )
24
+ from fvs2py.enums import FvsAttributeAccessor
25
+
26
+
27
+ def _svs_nobjs_key(attr: str) -> str:
28
+ if attr in SVS_LIVE_OBJ_ATTRS:
29
+ return STR_NSVSOBJS
30
+ if attr in SVS_SNAG_OBJ_ATTRS:
31
+ return STR_NDEADOBJS
32
+ if attr in SVS_CWD_OBJ_ATTRS:
33
+ return STR_NCWDOBJS
34
+ msg = f"unrecognized SVS object attribute: {attr!r}"
35
+ raise NameError(msg)
36
+
37
+
38
+ class SVSMixin:
39
+ """Stand Visualization System and related FFE per-species schedules.
40
+
41
+ This mixin groups FVS entry points used for 3D/SVS object geometry and
42
+ the Fire and Fuels Extension per-species snag crown fall-year vectors
43
+ (`fallyrs0`..`fallyrs5` via `fvsFFEAttrs`). FFE *stand-level*
44
+ compute variables (e.g. `torchidx`, `crbaseht`) remain in
45
+ `fvs2py._mixins.events.EventMixin` and `fvsEvmonAttr`.
46
+
47
+ Assumes the composed class provides `FvsCore._invoke`, `dims`
48
+ from `StandMixin`, and buffers `_ffe_attrs` and
49
+ `_svs_obj_attrs` from `FVS._initialize_attributes`.
50
+ """
51
+
52
+ _invoke: Callable[..., Any]
53
+ _ffe_attrs: dict[str, npt.NDArray[np.float64] | None]
54
+ _svs_obj_attrs: dict[str, npt.NDArray[np.float64] | None]
55
+ dims: dict
56
+
57
+ @fvs_property
58
+ def svs_dim_sizes(self) -> dict[str, int]:
59
+ """Current and max SVS object counts from `fvsSVSDimSizes`.
60
+
61
+ Keys: `nsvsobjs`, `ndeadobjs`, `ncwdobjs` (current counts) and
62
+ `mxsvsobjs`, `mxdeadobjs`, `mxcwdobjs` (capacity).
63
+ """
64
+ return self._invoke("fvsSVSDimSizes")
65
+
66
+ @fvs_property
67
+ def ffe_attrs(self) -> pd.DataFrame:
68
+ """DataFrame of per-species `fallyrs0`..`fallyrs5` (`fvsFFEAttrs`)."""
69
+ for attr in self._ffe_attrs:
70
+ _ = self.get_ffe_attr(attr)
71
+
72
+ attrs = pd.DataFrame(self._ffe_attrs, copy=False)
73
+ if (attrs == 0).all().all():
74
+ warnings.warn(
75
+ "No FFE fallyrs attributes initialized yet. "
76
+ "Is the Fire and Fuels Extension active in the loaded keyfile?"
77
+ )
78
+ return attrs.replace(0, None)
79
+
80
+ return attrs
81
+
82
+ def get_ffe_attr(self, attr: str) -> npt.NDArray[np.float64]:
83
+ """Get one `fvsFFEAttrs` fallyrs column (shape `(maxspecies,)`)."""
84
+ self._ffe_attr(attr, FvsAttributeAccessor.GET)
85
+ return self._ffe_attrs[attr]
86
+
87
+ def set_ffe_attr(self, attr: str, arr: npt.NDArray[np.float64]) -> None:
88
+ """Set one `fvsFFEAttrs` fallyrs column (shape `(maxspecies,)`)."""
89
+ return self._ffe_attr(attr, FvsAttributeAccessor.SET, arr)
90
+
91
+ def get_svs_obj_attr(self, attr: str) -> npt.NDArray[np.float64]:
92
+ """Get one `fvsSVSObjData` array (length = current nsvs/ndead/ncwd)."""
93
+ self._svs_obj_attr(attr, FvsAttributeAccessor.GET)
94
+ return self._svs_obj_attrs[attr]
95
+
96
+ def set_svs_obj_attr(self, attr: str, arr: npt.NDArray[np.float64]) -> None:
97
+ """Set one `fvsSVSObjData` array; shape must match current count."""
98
+ return self._svs_obj_attr(attr, FvsAttributeAccessor.SET, arr)
99
+
100
+ def _ffe_attr(
101
+ self,
102
+ attr: str,
103
+ action: FvsAttributeAccessor,
104
+ arr: npt.NDArray[np.float64] | None = None,
105
+ ) -> None:
106
+ if attr not in self._ffe_attrs:
107
+ msg = "Invalid variable requested. Valid options are"
108
+ raise NameError(msg, tuple(self._ffe_attrs))
109
+
110
+ dims = self.dims
111
+ if action == FvsAttributeAccessor.GET and self._ffe_attrs[attr] is None:
112
+ self._ffe_attrs[attr] = np.empty(
113
+ dtype=np.float64, shape=(dims[STR_MAXSPECIES],)
114
+ )
115
+ elif action == FvsAttributeAccessor.SET:
116
+ if arr is None:
117
+ msg = "Must provide `arr` if `action` is 'set'"
118
+ raise TypeError(msg)
119
+ if arr.shape != (dims[STR_MAXSPECIES],):
120
+ msg = (
121
+ "`arr` must be same shape as `maxspecies` "
122
+ f"({dims[STR_MAXSPECIES]},)"
123
+ )
124
+ raise ValueError(msg)
125
+ self._ffe_attrs[attr] = arr
126
+
127
+ self._invoke(
128
+ "fvsFFEAttrs",
129
+ attr_name=ct.c_char_p(attr.encode()),
130
+ nch=ct.c_int(len(attr)),
131
+ action=ct.c_char_p(action.encode()),
132
+ maxspecies=ct.c_int(dims[STR_MAXSPECIES]),
133
+ arr=self._ffe_attrs[attr],
134
+ )
135
+
136
+ def _svs_obj_attr(
137
+ self,
138
+ attr: str,
139
+ action: FvsAttributeAccessor,
140
+ arr: npt.NDArray[np.float64] | None = None,
141
+ ) -> None:
142
+ if attr not in self._svs_obj_attrs:
143
+ msg = "Invalid variable requested. Valid options are"
144
+ raise NameError(msg, self._svs_obj_attrs)
145
+
146
+ nkey = _svs_nobjs_key(attr)
147
+ n = int(self.svs_dim_sizes[nkey])
148
+ if action == FvsAttributeAccessor.SET:
149
+ if arr is None:
150
+ msg = "Must provide `arr` if `action` is 'set'"
151
+ raise TypeError(msg)
152
+ if arr.shape != (n,):
153
+ msg = f"`arr` must have shape `({n},)` for {attr!r}."
154
+ raise ValueError(msg)
155
+ self._svs_obj_attrs[attr] = arr
156
+ else:
157
+ self._svs_obj_attrs[attr] = np.empty(dtype=np.float64, shape=(n,))
158
+
159
+ self._invoke(
160
+ "fvsSVSObjData",
161
+ attr_name=ct.c_char_p(attr.encode()),
162
+ nch=ct.c_int(len(attr)),
163
+ action=ct.c_char_p(action.encode()),
164
+ nobjs=ct.c_int(n),
165
+ arr=self._svs_obj_attrs[attr],
166
+ )
@@ -0,0 +1,163 @@
1
+ """Tree-level attribute access and bulk tree insertion mixin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes as ct
6
+ import warnings
7
+ from collections.abc import Callable
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+ import numpy.typing as npt
12
+ import pandas as pd
13
+
14
+ from fvs2py.common import fvs_property
15
+ from fvs2py.constants import (
16
+ ADD_TREES_COLS,
17
+ STR_MAXTREES,
18
+ STR_NPLOTS,
19
+ STR_NTREES,
20
+ )
21
+ from fvs2py.enums import FvsAttributeAccessor
22
+
23
+
24
+ class TreesMixin:
25
+ """Expose per-tree attribute access and bulk tree insertion.
26
+
27
+ Assumes the composed class provides `FvsCore._invoke` for registry
28
+ dispatch, `self.dims` from `StandMixin`, `self.species_codes`
29
+ from `SpeciesMixin`, and the `_tree_attrs` / `_trees` buffers
30
+ seeded by `FVS._initialize_attributes`.
31
+ """
32
+
33
+ _invoke: Callable[..., Any]
34
+ _tree_attrs: tuple[str, ...]
35
+ _trees: dict[str, npt.NDArray[np.float64] | None]
36
+ dims: dict
37
+ species_codes: pd.DataFrame
38
+
39
+ @fvs_property
40
+ def trees(self) -> pd.DataFrame | None:
41
+ """Returns a dataframe of trees currently in FVS."""
42
+ if self.dims[STR_NTREES] == 0:
43
+ warnings.warn("No trees in FVS yet.")
44
+ return None
45
+
46
+ for attr in self._tree_attrs:
47
+ _ = self.get_tree_attr(attr)
48
+
49
+ return pd.DataFrame(self._trees, copy=False)
50
+
51
+ def get_tree_attr(self, attr: str) -> npt.NDArray[np.float64]:
52
+ """Gets a single attribute for existing trees.
53
+
54
+ Args:
55
+ attr (str): name of tree attribute to fetch
56
+
57
+ Returns:
58
+ array with values of requested attribute for all trees
59
+ """
60
+ self._tree_attr(attr, FvsAttributeAccessor.GET)
61
+ return self._trees[attr]
62
+
63
+ def set_tree_attr(self, attr: str, arr: npt.NDArray[np.float64]) -> None:
64
+ """Sets a single attribute for all existing trees.
65
+
66
+ Args:
67
+ attr (str): name of tree attribute to set
68
+ arr (npt.NDArray[np.float64]): values to set tree attribute to
69
+ """
70
+ return self._tree_attr(attr, FvsAttributeAccessor.SET, arr)
71
+
72
+ def _tree_attr(
73
+ self,
74
+ attr: str,
75
+ action: FvsAttributeAccessor,
76
+ arr: npt.NDArray[np.float64] | None = None,
77
+ ) -> None:
78
+ """Get or set a single attribute for existing trees.
79
+
80
+ Args:
81
+ attr (str): attribute to set or get
82
+ action (FvsAttributeAccessor): 'set' or 'get'
83
+ arr (optional, npt.NDArray[np.float64]): array of values to set
84
+ """
85
+ if attr not in self._tree_attrs:
86
+ self._trees[attr] = None
87
+
88
+ ntrees = self.dims[STR_NTREES]
89
+
90
+ if action == FvsAttributeAccessor.GET:
91
+ self._trees[attr] = np.empty(dtype=np.float64, shape=(ntrees,))
92
+ if ntrees == 0:
93
+ warnings.warn("No trees in FVS yet.")
94
+ elif action == FvsAttributeAccessor.SET:
95
+ if arr is None:
96
+ msg = "Must provide `arr` if `action` is 'set'"
97
+ raise TypeError(msg)
98
+ if arr.shape != (ntrees,):
99
+ msg = f"`arr` must be same shape as `ntrees` ({ntrees},)"
100
+ raise ValueError(msg)
101
+ self._trees[attr] = arr
102
+
103
+ self._invoke(
104
+ "fvsTreeAttr",
105
+ attr_name=ct.c_char_p(attr.encode()),
106
+ nch=ct.c_int(len(attr)),
107
+ action=ct.c_char_p(action.encode()),
108
+ ntrees=ct.c_int(ntrees),
109
+ arr=self._trees[attr],
110
+ )
111
+
112
+ def add_trees(self, tree_df: pd.DataFrame) -> None:
113
+ """Adds trees to an existing simulation.
114
+
115
+ Args:
116
+ tree_df (pd.DataFrame): trees to add. Must contain every column
117
+ listed in `fvs2py.constants.ADD_TREES_COLS`
118
+ (`dbh`, `species`, `ht`, `cratio`, `plot`, `tpa`),
119
+ with non-null float-coercible values for every row. Extra
120
+ columns are ignored.
121
+ """
122
+ missing = tuple(c for c in ADD_TREES_COLS if c not in tree_df.columns)
123
+ if missing:
124
+ msg = (
125
+ f"tree_df is missing required column(s) {list(missing)}; "
126
+ f"expected all of {list(ADD_TREES_COLS)}"
127
+ )
128
+ raise ValueError(msg)
129
+
130
+ ntrees = len(tree_df)
131
+ trees = tree_df[list(ADD_TREES_COLS)].astype(np.float64)
132
+ if trees.isna().any().any():
133
+ msg = "No null values allowed in trees to add."
134
+ raise ValueError(msg)
135
+
136
+ dims = self.dims
137
+ if dims[STR_MAXTREES] < dims[STR_NTREES] + ntrees:
138
+ room = dims[STR_MAXTREES] - dims[STR_NTREES]
139
+ msg = f"Only room for {room} new trees but {ntrees} supplied."
140
+ raise ValueError(msg)
141
+
142
+ if dims[STR_NPLOTS] == 0:
143
+ msg = "No inventory plots loaded yet."
144
+ raise RuntimeError(msg)
145
+
146
+ if not trees["plot"].isin(range(1, dims[STR_NPLOTS] + 1)).all():
147
+ msg = "Plot codes must be within range already defined."
148
+ raise ValueError(msg)
149
+
150
+ if not trees["species"].isin(self.species_codes["fvs_index"]).all():
151
+ msg = "Unrecognized species code(s). Use FVS Species Index."
152
+ raise ValueError(msg)
153
+
154
+ self._invoke(
155
+ "fvsAddTrees",
156
+ dbh=trees["dbh"].values,
157
+ species=trees["species"].values,
158
+ ht=trees["ht"].values,
159
+ cratio=trees["cratio"].values,
160
+ plot=trees["plot"].values,
161
+ tpa=trees["tpa"].values,
162
+ ntrees=ct.c_int(ntrees),
163
+ )