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,226 @@
1
+ """Event Monitor variable access and FVS activity scheduling mixin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes as ct
6
+ from collections.abc import Callable, Iterable
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+
11
+ from fvs2py.common import fvs_property
12
+ from fvs2py.constants import STR_NCYCLES
13
+ from fvs2py.enums import FvsActivity, FvsAttributeAccessor
14
+
15
+
16
+ class EventMixin:
17
+ """Expose Event Monitor variable access and FVS activity scheduling.
18
+
19
+ Assumes the composed class provides `FvsCore._invoke` for registry
20
+ dispatch, `self.keyfile` and `self.stop_point_code` from
21
+ `ControlMixin`, `self.dims` from `StandMixin`, and the
22
+ `_evmon_attrs` buffer seeded by `FVS._initialize_attributes`.
23
+ """
24
+
25
+ _invoke: Callable[..., Any]
26
+ _evmon_attrs: dict[str, None]
27
+ keyfile: str | None
28
+ stop_point_code: int | None
29
+ dims: dict
30
+
31
+ @fvs_property
32
+ def evmon_attrs(self) -> dict[str, float | None]:
33
+ """Return current values for every tracked Event Monitor variable.
34
+
35
+ Iterates through the canonical names seeded from
36
+ `fvs2py.constants.EVMON_ATTRS` plus any names registered via
37
+ `set_evmon_attr`, querying FVS for each and recording
38
+ `None` when FVS reports the name as not-found (`rtncode == 1`).
39
+ This bulk-inspection view deliberately tolerates not-found names
40
+ because the canonical list includes phase-specific variables that
41
+ may have no value at the current stop point. For a strict
42
+ raise-or-return contract on a single variable, use
43
+ `get_evmon_attr`.
44
+ """
45
+ out: dict[str, float | None] = {}
46
+ for name in self._evmon_attrs:
47
+ try:
48
+ out[name] = self.get_evmon_attr(name)
49
+ except NameError:
50
+ out[name] = None
51
+ return out
52
+
53
+ def get_evmon_attr(self, attr: str) -> float | None:
54
+ """Return the current FVS value for a single Event Monitor variable.
55
+
56
+ Args:
57
+ attr: Name of the Event Monitor variable (canonical FVS name
58
+ or one defined at runtime via a keyfile `COMPUTE`
59
+ statement or via `set_evmon_attr`).
60
+
61
+ Returns:
62
+ The variable's current value, or `None` if FVS has not
63
+ advanced far enough in the current cycle for any value to be
64
+ reported (`ncycles == 0`).
65
+
66
+ Raises:
67
+ NameError: If FVS does not recognize `attr`.
68
+ KeyError: If no keyfile has been loaded.
69
+ RuntimeError: If the simulation has not been started.
70
+ """
71
+ return self._evmon_attr(attr, FvsAttributeAccessor.GET)
72
+
73
+ def set_evmon_attr(self, attr: str, val: int | float) -> None:
74
+ """Set the value of a single Event Monitor variable.
75
+
76
+ If `attr` is not already tracked in the instance's known-names
77
+ cache, it is registered so subsequent `evmon_attrs`
78
+ iterations include it. The Python-side cache is not treated as
79
+ an authoritative whitelist: FVS itself decides whether the name
80
+ is valid and reports `NameError` via `attr_accessor_policy`
81
+ if it is not.
82
+
83
+ Args:
84
+ attr: Name of the Event Monitor variable to set.
85
+ val: New value to assign.
86
+
87
+ Raises:
88
+ NameError: If FVS does not recognize `attr`.
89
+ KeyError: If no keyfile has been loaded.
90
+ RuntimeError: If the simulation has not been started.
91
+ """
92
+ if attr not in self._evmon_attrs:
93
+ self._evmon_attrs[attr] = None
94
+ self._evmon_attr(attr, FvsAttributeAccessor.SET, val)
95
+
96
+ def _evmon_attr(
97
+ self,
98
+ attr: str,
99
+ action: FvsAttributeAccessor,
100
+ val: float | None = None,
101
+ ) -> float | None:
102
+ """Dispatch a get or set on a single Event Monitor variable.
103
+
104
+ Allocates a fresh single-element float64 buffer for every call
105
+ (FVS owns the authoritative value; the buffer is transient
106
+ working memory), runs the registered `fvsEvmonAttr` call, and
107
+ returns the scalar on GET. SET calls do not return a value.
108
+ """
109
+ if self.keyfile is None:
110
+ msg = "No keyfile loaded yet."
111
+ raise KeyError(msg)
112
+ if self.stop_point_code is None:
113
+ msg = (
114
+ "Simulation has not yet started and no inventory data have "
115
+ "been loaded yet. Call `run` method."
116
+ )
117
+ raise RuntimeError(msg)
118
+
119
+ if self.dims[STR_NCYCLES] == 0:
120
+ return None
121
+
122
+ if action == FvsAttributeAccessor.SET and val is None:
123
+ msg = "Must provide `val` if `action` is 'set'."
124
+ raise TypeError(msg)
125
+
126
+ if action == FvsAttributeAccessor.SET:
127
+ arr = np.array([val], dtype=np.float64)
128
+ else:
129
+ arr = np.empty(shape=(1,), dtype=np.float64)
130
+
131
+ self._invoke(
132
+ "fvsEvmonAttr",
133
+ attr_name=ct.c_char_p(attr.encode()),
134
+ nch=ct.c_int(len(attr)),
135
+ action=ct.c_char_p(action.encode()),
136
+ arr=arr,
137
+ )
138
+
139
+ if action == FvsAttributeAccessor.GET:
140
+ return float(arr[0])
141
+ return None
142
+
143
+ def add_activity(
144
+ self,
145
+ year: int,
146
+ activity: FvsActivity | int,
147
+ params: Iterable[float] | None = None,
148
+ ) -> None:
149
+ """Schedule an FVS activity to fire in a given simulation year.
150
+
151
+ Args:
152
+ year: Simulation year when the activity should execute.
153
+ activity: Activity to schedule. Accepts any member of the
154
+ per-extension activity enums (`FvsBaseActivity`,
155
+ `FvsFireActivity`, etc.) or a raw FVS activity code as
156
+ an integer.
157
+ params: Iterable of numeric parameters for the activity.
158
+ `None` and an empty iterable both pass a length-zero
159
+ buffer to FVS, which is only safe for activities that
160
+ take no parameters (e.g. `FvsBaseActivity.TREELIST`).
161
+ See the warning below.
162
+
163
+ Raises:
164
+ KeyError: If no keyfile has been loaded.
165
+ RuntimeError: If the simulation has not been started or no
166
+ inventory has been loaded.
167
+ ValueError: If FVS reports a failure
168
+ (`fvsAddActivity` rtncode == 1).
169
+
170
+ Warning:
171
+ FVS does **not** validate the length of `params` against the
172
+ chosen activity's documented signature. Internally,
173
+ `fvsAddActivity` copies the caller's values into a fixed
174
+ 20-wide `real(4)` buffer and hands the whole buffer to
175
+ `opadd`, which then interprets every slot the keyword's
176
+ schema expects. Any positions past `len(params)` contain
177
+ **uninitialized stack memory** that `opadd` will read as if
178
+ it were valid input. `fvsAddActivity` still returns
179
+ `rtncode == 0` in this case, so the failure is silent: the
180
+ activity may no-op, or it may be scheduled with nonsensical
181
+ thresholds, depending on what happened to be on the stack at
182
+ call time.
183
+
184
+ Callers should therefore supply the full documented parameter
185
+ vector for every activity. There are no "optional" trailing
186
+ parameters from FVS's point of view. Consult the
187
+ `FVS Keyword Reference Guide
188
+ <https://www.fs.usda.gov/fvs/documents/gtrs/FVSKeywords.pdf>`_
189
+ for the field count and default values of each keyword.
190
+
191
+ For example, `FvsBaseActivity.THINABA` takes six fields
192
+ (residual BA, cut efficiency, min DBH, max DBH, min HT, max
193
+ HT). Passing only a target residual basal area
194
+ (`params=[80]`) will silently misbehave. The correct call
195
+ supplies every field explicitly, e.g.
196
+ `params=[80.0, 1.0, 0.0, 999.0, 0.0, 999.0]`.
197
+ """
198
+ if self.keyfile is None:
199
+ msg = "No keyfile loaded yet."
200
+ raise KeyError(msg)
201
+ if self.stop_point_code is None:
202
+ msg = "Simulation hasn't been started yet. Call `run` method."
203
+ raise RuntimeError(msg)
204
+ if self.dims[STR_NCYCLES] == 0:
205
+ msg = (
206
+ "No inventory plots loaded yet. Consider FVS.run(7, 0) to "
207
+ "load inventory data and run configuration before "
208
+ "simulating anything else."
209
+ )
210
+ raise RuntimeError(msg)
211
+
212
+ if params is None:
213
+ arr = np.empty(shape=(0,), dtype=np.float64)
214
+ else:
215
+ arr = np.array(list(params), dtype=np.float64)
216
+ if np.isnan(arr).any():
217
+ msg = "params may not contain NaN values."
218
+ raise ValueError(msg)
219
+
220
+ self._invoke(
221
+ "fvsAddActivity",
222
+ year=ct.c_int(int(year)),
223
+ activity_code=ct.c_int(int(activity)),
224
+ params=arr,
225
+ nparams=ct.c_int(len(arr)),
226
+ )
@@ -0,0 +1,209 @@
1
+ """Simulation lifecycle and run-status mixin."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes as ct
6
+ import logging
7
+ from collections.abc import Callable
8
+ from typing import Any
9
+
10
+ from fvs2py.common import fvs_property
11
+ from fvs2py.enums import FvsItrnCode, FvsRestartCode, FvsSimulationState
12
+
13
+
14
+ class SimulationMixin:
15
+ """Expose FVS simulation status codes and the top-level `run` loop.
16
+
17
+ Assumes the composed class provides `fvs2py._core.FvsCore._invoke`
18
+ plus the Python-side buffers `_itrncd` and `_state`, the `keyfile`
19
+ attribute, and the `set_stop_point_codes` helper contributed by
20
+ `ControlMixin`.
21
+ """
22
+
23
+ _invoke: Callable[..., Any]
24
+ _itrncd: ct.c_int
25
+ _state: FvsSimulationState
26
+ keyfile: str | None
27
+ stop_point_code: int | None
28
+ stop_point_year: int | None
29
+ set_stop_point_codes: Callable[..., None]
30
+
31
+ @fvs_property
32
+ def exit_code(self) -> int:
33
+ """Gets the integer code returned when FVS exits.
34
+
35
+ Possible values are:
36
+ 0 - No serious errors occurred.
37
+ 1 - Input data error.
38
+ 2 - Keyword or expression error.
39
+ 3 - Extension or group activities error.
40
+ 4 - Scratch file error.
41
+ """
42
+ return self._invoke("fvsGetICCode")
43
+
44
+ @fvs_property
45
+ def itrncd(self) -> int:
46
+ """Returns with the current return code value in FVS.
47
+
48
+ -1: indicates that FVS has not been started.
49
+ 0: indicates that FVS is in good running state.
50
+ 1: indicates that FVS has detected an error of some kind and should not
51
+ be used until reset by specifying new input.
52
+ 2: indicates that FVS has finished processing all the stands; new input
53
+ can be specified.
54
+ """
55
+ return self._invoke("fvsGetRtnCode")
56
+
57
+ @fvs_property
58
+ def restart_code(self) -> int:
59
+ """A code indicating when FVS stopped.
60
+
61
+ 1: Stop was done just before the first call to the Event Monitor.
62
+ 2: Stop was done just after the first call to the Event Monitor.
63
+ 3: Stop was done just before the second call to the Event Monitor.
64
+ 4: Stop was done just after the second call to the Event Monitor.
65
+ 5: Stop was done after growth and mortality has been computed, but
66
+ prior to applying them.
67
+ 6: Stop was done just before the ESTAB routines are called.
68
+ 100: Stop was done after a stand has been simulated but prior to
69
+ starting a subsequent stand.
70
+ """
71
+ return self._invoke("fvsGetRestartCode")
72
+
73
+ def _run_cycles(self) -> None:
74
+ """Advance FVS until the current stand pauses or reaches stand-done.
75
+
76
+ Shared inner loop used by both `run` and `run_batch`: call
77
+ `fvs` while FVS reports a good running state, breaking out the
78
+ moment `restart_code` leaves `INITIALIZED` (either a stop-point
79
+ pause or the `DONE_RUNNING_STAND` marker).
80
+ """
81
+ while self.itrncd == FvsItrnCode.GOOD_RUNNING_STATE:
82
+ logging.debug("itrncd in GOOD_RUNNING_STATE.")
83
+ self._invoke("fvs", itrncd=self._itrncd)
84
+ logging.debug(f"Ran _fvs routine, itrncd is {self.itrncd}")
85
+ if self.restart_code != FvsRestartCode.INITIALIZED:
86
+ logging.debug("restart code non-zero, halting run loop.")
87
+ break
88
+
89
+ def run(
90
+ self,
91
+ stop_point_code: int = 0,
92
+ stop_point_year: int = 0,
93
+ ) -> None:
94
+ """Run FVS until the stand completes or a stop point is reached.
95
+
96
+ The call stays eager: when the stand finishes (FVS reports
97
+ `restart_code == FvsRestartCode.DONE_RUNNING_STAND`), `run`
98
+ issues one additional `_fvs` call to flush the main output file
99
+ before returning, so callers do not need to invoke `run` a
100
+ second time just to finalize output. When `stop_point_code` pauses
101
+ the simulation mid-cycle, no flush is performed and the next call to
102
+ `run` resumes from the stop.
103
+
104
+ Multi-stand keyfiles are out of scope here; use `run_batch`
105
+ (and load the keyfile with `check_single_stand=False`) when the
106
+ keyfile defines more than one stand.
107
+
108
+ Args:
109
+ stop_point_code (optional, int): when FVS should stop during a cycle:
110
+ -1 : Stop at every stop location
111
+ 0 : Never stop
112
+ 1 : Stop just before the first call to the Event Monitor
113
+ 2 : Stop just after the first call to the Event Monitor
114
+ 3 : Stop just before the second call to the Event Monitor
115
+ 4 : Stop just after the second call to the Event Monitor
116
+ 5 : Stop after growth and mortality has been computed, but
117
+ prior to applying them
118
+ 6 : Stop just before the ESTAB routines are called
119
+ 7 : Stop just after input is read but before missing values
120
+ are imputed
121
+ stop_point_year (optional, int): years FVS should stop, options are:
122
+ 0 : Never stop
123
+ -1 : Stop at every cycle
124
+ YYYY : A specific year during the simulation period
125
+
126
+ Raises:
127
+ AttributeError: If no keyfile has been loaded yet.
128
+ RuntimeError: If another `run` call is already in progress
129
+ on this instance.
130
+ """
131
+ if self.keyfile is None:
132
+ msg = "No keyfile loaded yet."
133
+ raise AttributeError(msg)
134
+ if self._state == FvsSimulationState.RUNNING:
135
+ msg = "Simulation already in progress."
136
+ raise RuntimeError(msg)
137
+ logging.debug("Found keyfile.")
138
+ self.set_stop_point_codes(stop_point_code, stop_point_year)
139
+ logging.debug(
140
+ f"Set stop point codes, {stop_point_code}:{self.stop_point_code}, "
141
+ f"{stop_point_year}:{self.stop_point_year}"
142
+ )
143
+ self._state = FvsSimulationState.RUNNING
144
+ try:
145
+ self._run_cycles()
146
+ if self.restart_code == FvsRestartCode.DONE_RUNNING_STAND:
147
+ logging.debug("Stand complete; flushing output.")
148
+ self._invoke("fvs", itrncd=self._itrncd)
149
+ self._state = FvsSimulationState.COMPLETE
150
+ except Exception:
151
+ self._state = FvsSimulationState.ERROR
152
+ raise
153
+
154
+ def run_batch(
155
+ self,
156
+ stop_point_code: int = 0,
157
+ stop_point_year: int = 0,
158
+ ) -> None:
159
+ """Advance FVS one stand's worth of cycles without auto-flushing.
160
+
161
+ Unlike `run`, this method does not follow a `DONE_RUNNING_STAND`
162
+ restart code with a flush call. It simply returns once FVS either
163
+ pauses at a stop point or reports the stand-done marker, leaving
164
+ output finalization, stand-advance, and termination detection in
165
+ the caller's hands. This is the low-level building block for
166
+ driving multi-stand keyfiles, where the caller typically loops:
167
+
168
+ fvs.load_keyfile(path, check_single_stand=False)
169
+ while fvs.itrncd == FvsItrnCode.GOOD_RUNNING_STATE:
170
+ fvs.run_batch()
171
+ # optionally inspect per-stand outputs here
172
+ if fvs.itrncd == FvsItrnCode.ERROR or fvs.exit_code:
173
+ ... # handle the failure
174
+
175
+ The loop ends at `FINISHED_ALL_STANDS` or `ERROR`. Don't loop on
176
+ `itrncd != FINISHED_ALL_STANDS`: after an FVS error, `itrncd`
177
+ stays at `ERROR` and that loop never ends. Some errors (e.g. FVS
178
+ can't open an output file) set `itrncd` to `ERROR` but leave
179
+ `exit_code` at 0, so check both.
180
+
181
+ Stop-point semantics are identical to `run`: pass non-zero
182
+ `stop_point_code` / `stop_point_year` to pause mid-cycle, then
183
+ call `run_batch` again to resume.
184
+
185
+ Args:
186
+ stop_point_code (optional, int): when FVS should stop during a
187
+ cycle. See `run` for the full list of values.
188
+ stop_point_year (optional, int): year(s) at which FVS should
189
+ stop. See `run` for the full list of values.
190
+
191
+ Raises:
192
+ AttributeError: If no keyfile has been loaded yet.
193
+ RuntimeError: If another run is already in progress on this
194
+ instance.
195
+ """
196
+ if self.keyfile is None:
197
+ msg = "No keyfile loaded yet."
198
+ raise AttributeError(msg)
199
+ if self._state == FvsSimulationState.RUNNING:
200
+ msg = "Simulation already in progress."
201
+ raise RuntimeError(msg)
202
+ self.set_stop_point_codes(stop_point_code, stop_point_year)
203
+ self._state = FvsSimulationState.RUNNING
204
+ try:
205
+ self._run_cycles()
206
+ self._state = FvsSimulationState.COMPLETE
207
+ except Exception:
208
+ self._state = FvsSimulationState.ERROR
209
+ raise
@@ -0,0 +1,186 @@
1
+ """Species codes and per-species attribute access 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 SPECIES_COLUMN_NAMES, STR_MAXSPECIES
16
+ from fvs2py.enums import FvsAttributeAccessor
17
+
18
+
19
+ class SpeciesMixin:
20
+ """Expose species metadata and per-species attribute get/set helpers.
21
+
22
+ Assumes the composed class provides `FvsCore._invoke` for registry
23
+ dispatch and the `_species_attrs` mapping seeded by
24
+ `FVS._initialize_attributes`. Uses `self.dims` from
25
+ `StandMixin`.
26
+ """
27
+
28
+ _invoke: Callable[..., Any]
29
+ _species_attrs: dict[str, npt.NDArray[np.float64] | None]
30
+ dims: dict
31
+
32
+ @fvs_property
33
+ def species(self) -> pd.DataFrame:
34
+ """Returns species codes and attributes for all species."""
35
+ codes = self.species_codes
36
+ attrs = self.species_attrs
37
+ return codes.merge(attrs, left_index=True, right_index=True, copy=False)
38
+
39
+ @fvs_property
40
+ def species_codes(self) -> pd.DataFrame:
41
+ """Fetch the various codes used to refer to different tree species."""
42
+ dims = self.dims
43
+
44
+ _fvs_spp = ct.create_string_buffer(4)
45
+ _fia_spp = ct.create_string_buffer(4)
46
+ _plants_spp = ct.create_string_buffer(6)
47
+
48
+ spp_codes = pd.DataFrame(
49
+ index=range(dims[STR_MAXSPECIES]),
50
+ columns=SPECIES_COLUMN_NAMES,
51
+ )
52
+
53
+ for i in range(dims[STR_MAXSPECIES]):
54
+ self._invoke(
55
+ "fvsSpeciesCode",
56
+ fvs_spp=_fvs_spp,
57
+ fia_spp=_fia_spp,
58
+ plants_spp=_plants_spp,
59
+ index=ct.c_int(i + 1),
60
+ fvs_spp_len=ct.c_int(0),
61
+ fia_spp_len=ct.c_int(0),
62
+ plants_spp_len=ct.c_int(0),
63
+ )
64
+ spp_codes.iloc[i] = (
65
+ i + 1,
66
+ _fvs_spp.value.decode().strip(),
67
+ _fia_spp.value.decode().strip(),
68
+ _plants_spp.value.decode().strip(),
69
+ )
70
+
71
+ return spp_codes
72
+
73
+ @fvs_property
74
+ def species_attrs(self) -> pd.DataFrame:
75
+ """Returns a dataframe of species attributes.
76
+
77
+ Fields returned are:
78
+ spccf: CCF for each species, recomputed in FVS so setting will
79
+ likely have no effect
80
+ spsdi: SDI maximums for each species
81
+ spsiteindx: Species site indices
82
+ bfmind: Min diameter related to BFVOLUME keyword
83
+ bftopd: Top diameter related to BFVOLUME keyword
84
+ bfstmp: Stump height related to BFVOLUME keyword
85
+ frmcls: Form class related to BFVOLUME keyword
86
+ bfmeth: Volume calculation code related to BFVOLUME keyword
87
+ (internal FVS variable methb)
88
+ mcmind: Min diameter related to VOLUME keyword (internal FVS
89
+ variable dbhmin)
90
+ mctopd: Top diameter related to VOLUME keyword (internal FVS
91
+ variable topd)
92
+ mcstmp: Stump height related to VOLUME keyword (internal FVS
93
+ variable stmp)
94
+ mcmeth: Volume calculation code related to VOLUME keyword (internal
95
+ FVS variable methc)
96
+ baimult: Basal area increment multiplier for large trees (internal
97
+ FVS variable xdmult)
98
+ htgmult: Height growth multiplier for large trees (internal FVS
99
+ variable xhmult)
100
+ mortmult: Mortality rate multiplier (internal FVS variable xmmult)
101
+ mortdia1: Lower diameter limit for mortality multiplier (internal
102
+ FVS variable xmdia1)
103
+ mortdia2: Upper diameter limit for mortality multiplier (internal
104
+ FVS variable xmdia2)
105
+ regdmult: Diameter growth mulitplier for regeneration (internal FVS
106
+ variable xrdmlt)
107
+ reghmult: Height growth multiplier for regeneration (internal FVS
108
+ variable xrhmlt)
109
+ """
110
+ for attr in self._species_attrs:
111
+ _ = self.get_species_attr(attr)
112
+
113
+ attrs = pd.DataFrame(self._species_attrs, copy=False)
114
+ if (attrs == 0).all().all():
115
+ warnings.warn("No species attributes initialized yet.")
116
+ return attrs.replace(0, None)
117
+
118
+ return attrs
119
+
120
+ def get_species_attr(self, attr: str) -> npt.NDArray[np.float64]:
121
+ """Gets a single attribute for all existing species.
122
+
123
+ Args:
124
+ attr (str): name of species attribute to fetch
125
+
126
+ Returns:
127
+ array with values of requested attribute for all trees
128
+
129
+ """
130
+ self._species_attr(attr, FvsAttributeAccessor.GET)
131
+ return self._species_attrs[attr]
132
+
133
+ def set_species_attr(self, attr: str, arr: npt.NDArray[np.float64]) -> None:
134
+ """Sets a single attribute for all existing species.
135
+
136
+ Args:
137
+ attr (str): name of species attribute to fetch
138
+ arr (npt.NDArray[np.float64]): array of values to set
139
+
140
+ """
141
+ return self._species_attr(attr, FvsAttributeAccessor.SET, arr)
142
+
143
+ def _species_attr(
144
+ self,
145
+ attr: str,
146
+ action: FvsAttributeAccessor,
147
+ arr: npt.NDArray[np.float64] | None = None,
148
+ ) -> None:
149
+ """Gets or sets a single attribute for all existing species.
150
+
151
+ Args:
152
+ attr (str): name of species attribute to get or set
153
+ action (FvsAttributeAccessor): 'get' or 'set'
154
+ arr (optional, npt.NDArray[np.float64]): array of values to set
155
+ """
156
+ if attr not in self._species_attrs:
157
+ msg = "Invalid variable requested. Valid options are"
158
+ raise NameError(msg, self._species_attrs)
159
+
160
+ dims = self.dims
161
+ if (
162
+ action == FvsAttributeAccessor.GET
163
+ and self._species_attrs[attr] is None
164
+ ):
165
+ self._species_attrs[attr] = np.empty(
166
+ dtype=np.float64, shape=(dims[STR_MAXSPECIES])
167
+ )
168
+ elif action == FvsAttributeAccessor.SET:
169
+ if arr is None:
170
+ msg = "Must provide `arr` if `action` is 'set'"
171
+ raise TypeError(msg)
172
+ if arr.shape != (dims[STR_MAXSPECIES],):
173
+ msg = (
174
+ "`arr` must be same shape as `maxspecies` "
175
+ f"({dims[STR_MAXSPECIES]},)"
176
+ )
177
+ raise ValueError(msg)
178
+ self._species_attrs[attr] = arr
179
+
180
+ self._invoke(
181
+ "fvsSpeciesAttr",
182
+ attr_name=ct.c_char_p(attr.encode()),
183
+ nch=ct.c_int(len(attr)),
184
+ action=ct.c_char_p(action.encode()),
185
+ arr=self._species_attrs[attr],
186
+ )