From 618db0910cb3cdd66ab34ddb0a33b3cc33f46748 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 7 Nov 2026 22:02:04 +0900 Subject: [PATCH 1/2] feat(python): read the two tables of a modal output file read_output stopped at the second table of .modes.out with a field count error. It now reads the frequency and mode-shape tables into a NaturalModes table, whose shapes attribute is a ModeShapes table, with accessors by line and mode. Twist columns, negative eigenvalues and lines without free nodes read as the driver writes them. A file without a mode-shape table, or whose tables do not hold the same modes, is refused. DriverResult gains modes_output and read_modes. Signed-off-by: Jae Hoon Seo --- doc/api_python.rst | 12 +- doc/outputs.rst | 2 + doc/python.rst | 43 ++- python/cabledyn/__init__.py | 4 + python/cabledyn/driver.py | 30 ++ python/cabledyn/results.py | 564 +++++++++++++++++++++++++++--- python/tests/test_modes_output.py | 394 +++++++++++++++++++++ 7 files changed, 1005 insertions(+), 44 deletions(-) create mode 100644 python/tests/test_modes_output.py diff --git a/doc/api_python.rst b/doc/api_python.rst index 20262612..53ad4b3d 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -62,8 +62,10 @@ Reading results :func:`read_output` returns the most specific table class for the file it reads: :class:`TimeHistory` for the main output, :class:`LineNodeHistory` and :class:`LineSegmentHistory` for per-line dynamic outputs, :class:`StaticProfile` for the static -profile, and :class:`OutputTable` for any other numeric table. :class:`TimeHistory` and -:class:`StaticProfile` are subclasses of :class:`OutputTable`; :class:`LineNodeHistory` and +profile, :class:`NaturalModes` for the two tables of a ``.modes.out`` file, and +:class:`OutputTable` for any other numeric table. :class:`TimeHistory`, :class:`StaticProfile`, +:class:`NaturalModes` and :class:`ModeShapes` are subclasses of :class:`OutputTable`; +:class:`LineNodeHistory` and :class:`LineSegmentHistory` are subclasses of :class:`TimeHistory`, so every table method is available on them. @@ -84,6 +86,12 @@ available on them. .. autoclass:: cabledyn.StaticProfile :members: +.. autoclass:: cabledyn.NaturalModes + :members: + +.. autoclass:: cabledyn.ModeShapes + :members: + .. autoclass:: cabledyn.ChannelStatistics :members: diff --git a/doc/outputs.rst b/doc/outputs.rst index 3229e994..09b9de9c 100644 --- a/doc/outputs.rst +++ b/doc/outputs.rst @@ -463,6 +463,8 @@ column, for every line of the file (``0`` on a line without torsion): mode (``PolarShare`` above 0.5) is scaled to a unit largest ``dTwist`` instead, and its translations are then in metres per radian of that twist. +:func:`cabledyn.read_output` reads both tables into a :class:`cabledyn.NaturalModes`. + Per-rod files (``RODS`` ``Outputs`` flag) ----------------------------------------- diff --git a/doc/python.rst b/doc/python.rst index a5ec813c..5517fe61 100644 --- a/doc/python.rst +++ b/doc/python.rst @@ -74,8 +74,9 @@ Pass the executable explicitly for the most reproducible setup: fairlead_tension = history.column("FairTen1") # N ``result`` retains the executable, absolute deck and output paths, captured ``stdout`` and -``stderr``, return code, the optional static profile and finite-EI element table -(``elements_output``), and all requested per-line and per-rod outputs. A result is returned only +``stderr``, return code, the optional static profile, finite-EI element table +(``elements_output``) and modal table (``modes_output``, read with ``result.read_modes()``), and +all requested per-line and per-rod outputs. A result is returned only for a fully converged analysis: the driver exits non-zero whenever a nonlinear step fails. Arrays returned by the parser are read-only so post-processing cannot accidentally mutate the recorded result. @@ -135,7 +136,8 @@ archive the native diagnostic. Typed result objects -------------------- -:func:`cabledyn.read_output` accepts main histories, static profiles, and per-line tables. It +:func:`cabledyn.read_output` accepts main histories, static profiles, per-line tables, and modal +tables. It recognises both current main output (title + channel row) and tables with a units row in the style of OpenFAST (maintained by NLR, the National Laboratory of the Rockies, formerly NREL): @@ -161,6 +163,41 @@ and a generic :class:`cabledyn.OutputTable` for static per-line node or segment strictly increasing; line and node identifiers must be positive integers; and arc length must be monotonic within each line. +Natural modes +~~~~~~~~~~~~~ + +A deck that sets ``nModes`` writes ``.modes.out``, which holds two tables (see +:doc:`outputs`). :func:`cabledyn.read_output` reads both into one +:class:`cabledyn.NaturalModes`: the object is the frequency table, and its ``shapes`` attribute is +the mode-shape table, a :class:`cabledyn.ModeShapes`. Each table is an +:class:`cabledyn.OutputTable`, so ``column``, ``unit`` and ``to_dataframe`` work on either; an +export of the object writes the frequency table only. + +.. code-block:: python + + from cabledyn import read_output + + modes = read_output("results/baseline.modes.out") # or result.read_modes() + + print(modes.line_ids) + print(modes.periods(1)) # s, by mode + print(modes.frequencies(1)) # Hz, by mode + + xyz = modes.shapes.positions(1) # static node positions, (n_nodes, 3), m + shape = modes.shapes.displacements(1, 2) # mode 2, (n_nodes, 3), largest node 1 + line_2 = modes.line(2) # both tables of one line + +A file with a line restrained in torsion has the columns ``PolarShare`` and ``dTwist`` for every +line, and ``has_twist`` is true. ``modes.polar_shares(1)`` and ``modes.shapes.twist(1, mode)`` +return them, and ``modes.torsional_modes(1)`` the modes above a polar share of 0.5, which are +scaled to a unit largest twist instead of a unit largest displacement. On a file without the +columns these return zeros and no modes, as on a line without torsion. + +A negative eigenvalue has a negative ``Frequency`` and ``Omega`` and a ``Period`` of 0. A line +without free nodes has no modes and no rows, so it is absent from ``line_ids``. The reader refuses +a file without a mode-shape table, and one whose two tables do not hold the same modes of the same +lines. + Statistics, range graphs, and geometry ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/python/cabledyn/__init__.py b/python/cabledyn/__init__.py index 26720afd..ec758e77 100644 --- a/python/cabledyn/__init__.py +++ b/python/cabledyn/__init__.py @@ -124,6 +124,8 @@ ChannelStatistics, LineNodeHistory, LineSegmentHistory, + ModeShapes, + NaturalModes, OutputTable, SpatialStatistics, StaticLineSummary, @@ -196,7 +198,9 @@ "LinePositions", "LineSegmentHistory", "LineSummary", + "ModeShapes", "MoorDynLineHistory", + "NaturalModes", "OutputFormatError", "OutputTable", "PowerSpectrum", diff --git a/python/cabledyn/driver.py b/python/cabledyn/driver.py index ee6ab8df..724e730b 100644 --- a/python/cabledyn/driver.py +++ b/python/cabledyn/driver.py @@ -24,6 +24,7 @@ from cabledyn.results import ( LineNodeHistory, LineSegmentHistory, + NaturalModes, OutputTable, StaticProfile, TimeHistory, @@ -174,6 +175,9 @@ class DriverResult: Captured standard error of the driver. returncode : int Native exit code; always ``0`` for a result. + modes_output : pathlib.Path | None + Natural frequencies and mode shapes ``.modes.out``, or ``None`` + if not written. """ executable: Path @@ -187,6 +191,7 @@ class DriverResult: stdout: str stderr: str returncode: int + modes_output: Path | None = None def read_main(self) -> TimeHistory: """Read the primary channel history again from disk. @@ -230,6 +235,29 @@ def read_static(self) -> StaticProfile: raise OutputFormatError(f"{self.static_output}: static output is not a line profile") return table + def read_modes(self) -> NaturalModes: + """Read the natural modes, raising if this run did not write them. + + Returns + ------- + NaturalModes + The frequency table of each line, with the mode shapes in its + ``shapes`` attribute. + + Raises + ------ + FileNotFoundError + If the run did not write a modal output (the deck sets no ``nModes``). + OutputFormatError + If the file is malformed or not a modal output. + """ + if self.modes_output is None: + raise FileNotFoundError("the run did not produce a .modes.out file") + table = read_output(self.modes_output) + if not isinstance(table, NaturalModes): + raise OutputFormatError(f"{self.modes_output}: modal output has no modal tables") + return table + @property def line_ids(self) -> tuple[int, ...]: """Line identifiers for which a per-line output file was produced.""" @@ -646,6 +674,7 @@ def _execute( ) from exc static_candidate = Path(f"{root}.static.out") elements_candidate = Path(f"{root}.elements.out") + modes_candidate = Path(f"{root}.modes.out") line_outputs = _auxiliary_outputs(root, "Line") rod_outputs = _auxiliary_outputs(root, "Rod") return DriverResult( @@ -660,4 +689,5 @@ def _execute( stdout=completed.stdout, stderr=completed.stderr, returncode=completed.returncode, + modes_output=modes_candidate if modes_candidate.is_file() else None, ) diff --git a/python/cabledyn/results.py b/python/cabledyn/results.py index 4c766ac1..b8e5fc4d 100644 --- a/python/cabledyn/results.py +++ b/python/cabledyn/results.py @@ -1197,6 +1197,29 @@ def plot_envelope( return ax +def _check_positive_integers(table: OutputTable, channels: tuple[str, ...]) -> None: + """Refuse a table whose identifier columns are not positive integers.""" + for channel in channels: + values = table.column(channel) + if np.any(values <= 0.0) or np.any(values != np.floor(values)): + raise OutputFormatError(f"{table.path}: {channel} values must be positive integers") + + +def _check_contiguous_lines(table: OutputTable) -> None: + """Refuse a table whose rows of one line are split by rows of another.""" + seen: set[int] = set() + active: int | None = None + for value in table.column("LineID"): + identifier = int(value) + if identifier != active: + if identifier in seen: + raise OutputFormatError( + f"{table.path}: LineID {identifier} rows are not contiguous" + ) + seen.add(identifier) + active = identifier + + @dataclass(frozen=True) class StaticProfile(OutputTable): """One or more CableDyn line profiles indexed by line and arc length. @@ -1236,21 +1259,8 @@ def __post_init__(self) -> None: raise OutputFormatError( f"{self.path}: static profile missing {', '.join(sorted(missing))}" ) - for channel in ("LineID", "Node"): - values = self.column(channel) - if np.any(values <= 0.0) or np.any(values != np.floor(values)): - raise OutputFormatError(f"{self.path}: {channel} values must be positive integers") - seen: set[int] = set() - active: int | None = None - for value in self.column("LineID"): - identifier = int(value) - if identifier != active: - if identifier in seen: - raise OutputFormatError( - f"{self.path}: LineID {identifier} rows are not contiguous" - ) - seen.add(identifier) - active = identifier + _check_positive_integers(self, ("LineID", "Node")) + _check_contiguous_lines(self) for line_id in self.line_ids: mask = self.column("LineID") == line_id arc = self.column("ArcLength")[mask] @@ -1515,8 +1525,431 @@ def plot_geometry( return ax +@dataclass(frozen=True) +class ModeShapes(OutputTable): + """The mode-shape table of a ``.modes.out`` file. + + A subclass of :class:`cabledyn.OutputTable` holding one row per line, mode + and node, with the columns ``LineID``, ``Mode``, ``Node``, ``X``, ``Y``, + ``Z``, ``dX``, ``dY``, and ``dZ``, and ``dTwist`` in a file that carries + twist angles. It is read as :attr:`cabledyn.NaturalModes.shapes`. + + ``X``, ``Y``, ``Z`` are the static node positions in m. ``dX``, ``dY``, + ``dZ`` are the nodal translations of the mode, scaled so that its largest + nodal displacement is 1. ``dTwist`` is the rotation of the section about + the line tangent, positive right-handed from End A to End B, on the same + scale; a torsional mode is scaled to a unit largest ``dTwist`` instead. + Nodes are numbered from End A. The attributes are those of + :class:`cabledyn.OutputTable`. + + Raises + ------ + OutputFormatError + If a required column is missing, ``LineID``, ``Mode``, or ``Node`` + values are not positive integers, a line's rows are not contiguous, + they are not the nodes 1, 2, ... of the modes 1, 2, ... in order, or + the static position of a node differs between modes. + """ + + def __post_init__(self) -> None: + super().__post_init__() + required = {"LineID", "Mode", "Node", "X", "Y", "Z", "dX", "dY", "dZ"} + missing = required.difference(self.channels) + if missing: + raise OutputFormatError( + f"{self.path}: mode-shape table missing {', '.join(sorted(missing))}" + ) + _check_positive_integers(self, ("LineID", "Mode", "Node")) + _check_contiguous_lines(self) + static = np.column_stack([self.column(axis) for axis in ("X", "Y", "Z")]) + for line_id in self.line_ids: + mask = self.column("LineID") == line_id + mode = self.column("Mode")[mask] + node = self.column("Node")[mask] + n_modes = int(np.count_nonzero(node == 1.0)) + n_nodes = mode.size // n_modes if n_modes else 0 + if not ( + np.array_equal(mode, np.repeat(np.arange(1, n_modes + 1), n_nodes)) + and np.array_equal(node, np.tile(np.arange(1, n_nodes + 1), n_modes)) + ): + raise OutputFormatError( + f"{self.path}: LineID {line_id} rows are not the nodes 1, 2, ... " + "of the modes 1, 2, ..." + ) + positions = static[mask].reshape(n_modes, n_nodes, 3) + if np.any(positions != positions[0]): + raise OutputFormatError( + f"{self.path}: LineID {line_id} static positions differ between modes" + ) + + @property + def line_ids(self) -> tuple[int, ...]: + """Line identifiers in first-appearance order.""" + return tuple(dict.fromkeys(int(value) for value in self.column("LineID"))) + + def _line_rows(self, line_id: int) -> npt.NDArray[np.bool_]: + mask = self.column("LineID") == int(line_id) + if not np.any(mask): + raise KeyError( + f"LineID {line_id} is not in {self.path.name}; available: {self.line_ids}" + ) + return mask + + def _mode_rows(self, line_id: int, mode: int) -> npt.NDArray[np.bool_]: + mask = self._line_rows(line_id) & (self.column("Mode") == int(mode)) + if not np.any(mask): + raise KeyError(f"LineID {line_id} has no mode {mode} in {self.path.name}") + return mask + + def line(self, line_id: int) -> ModeShapes: + """Return the rows belonging to one line identifier. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + ModeShapes + A new table holding only that line's rows. + + Raises + ------ + KeyError + If the table has no rows for ``line_id``. + """ + return ModeShapes( + self.path, + self.title, + self.channels, + self.units, + self.values[self._line_rows(line_id)].copy(), + ) + + def node_ids(self, line_id: int) -> tuple[int, ...]: + """Return the node numbers of one line, from End A. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + tuple[int, ...] + Node numbers ``1, 2, ...``. + + Raises + ------ + KeyError + If the table has no rows for ``line_id``. + """ + return tuple(int(value) for value in self.column("Node")[self._mode_rows(line_id, 1)]) + + def positions(self, line_id: int) -> npt.NDArray[Any]: + """Return the static node positions of one line. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + numpy.ndarray + ``(n_nodes, 3)`` array of ``X``, ``Y``, ``Z`` in m, from End A. + + Raises + ------ + KeyError + If the table has no rows for ``line_id``. + """ + rows = self._mode_rows(line_id, 1) + return np.column_stack([self.column(axis)[rows] for axis in ("X", "Y", "Z")]) + + def displacements(self, line_id: int, mode: int) -> npt.NDArray[Any]: + """Return the nodal translations of one mode. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + mode : int + One-based mode number, as in the ``Mode`` column. + + Returns + ------- + numpy.ndarray + ``(n_nodes, 3)`` array of ``dX``, ``dY``, ``dZ``, from End A. + + Raises + ------ + KeyError + If the table does not hold that mode of that line. + """ + rows = self._mode_rows(line_id, mode) + return np.column_stack([self.column(axis)[rows] for axis in ("dX", "dY", "dZ")]) + + def twist(self, line_id: int, mode: int) -> npt.NDArray[Any]: + """Return the nodal twist of one mode. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + mode : int + One-based mode number, as in the ``Mode`` column. + + Returns + ------- + numpy.ndarray + ``(n_nodes,)`` array of ``dTwist``, from End A; zeros in a file + without twist angles, as on a line without torsion. + + Raises + ------ + KeyError + If the table does not hold that mode of that line. + """ + rows = self._mode_rows(line_id, mode) + if "dTwist" not in self.channels: + return np.zeros(int(np.count_nonzero(rows))) + return self.column("dTwist")[rows].copy() + + +@dataclass(frozen=True) +class NaturalModes(OutputTable): + """Natural frequencies and mode shapes of a ``.modes.out`` file. + + A subclass of :class:`cabledyn.OutputTable` whose own table is the frequency + table, one row per line and mode, with the columns ``LineID``, ``Mode``, + ``Frequency`` (Hz), ``Period`` (s), and ``Omega`` (rad/s), and + ``PolarShare`` in a file that carries twist angles. The mode-shape table is + :attr:`shapes`. + + A negative eigenvalue is recorded with a negative ``Frequency`` and + ``Omega`` and a ``Period`` of 0. A line without free nodes has no modes and + no rows, so a file of such lines reads as two empty tables. + + Attributes + ---------- + shapes : ModeShapes + The mode-shape table of the same file. + + Raises + ------ + OutputFormatError + If a required column is missing, ``LineID`` or ``Mode`` values are not + positive integers, a line's rows are not contiguous or its modes are + not numbered 1, 2, ..., only one table carries the twist columns, or + the two tables do not hold the same modes. + """ + + shapes: ModeShapes + + def __post_init__(self) -> None: + super().__post_init__() + missing = {"LineID", "Mode", "Frequency", "Period", "Omega"}.difference(self.channels) + if missing: + raise OutputFormatError( + f"{self.path}: frequency table missing {', '.join(sorted(missing))}" + ) + _check_positive_integers(self, ("LineID", "Mode")) + _check_contiguous_lines(self) + if self.has_twist != ("dTwist" in self.shapes.channels): + raise OutputFormatError( + f"{self.path}: PolarShare and dTwist must appear together in the two tables" + ) + if self.line_ids != self.shapes.line_ids: + raise OutputFormatError(f"{self.path}: the two tables do not hold the same lines") + shape_line = self.shapes.column("LineID") + shape_mode = self.shapes.column("Mode") + for line_id in self.line_ids: + mode = self.column("Mode")[self.column("LineID") == line_id] + if np.any(mode != np.arange(1, mode.size + 1)): + raise OutputFormatError( + f"{self.path}: LineID {line_id} modes are not numbered 1, 2, ..." + ) + n_shapes = int(shape_mode[shape_line == line_id].max()) + if n_shapes != mode.size: + raise OutputFormatError( + f"{self.path}: LineID {line_id} has {mode.size} frequency rows " + f"but {n_shapes} mode shapes" + ) + + @property + def line_ids(self) -> tuple[int, ...]: + """Line identifiers in first-appearance order.""" + return tuple(dict.fromkeys(int(value) for value in self.column("LineID"))) + + @property + def has_twist(self) -> bool: + """Whether the file carries the ``PolarShare`` and ``dTwist`` columns.""" + return "PolarShare" in self.channels + + def _line_column(self, channel: str, line_id: int) -> npt.NDArray[Any]: + mask = self.column("LineID") == int(line_id) + if not np.any(mask): + raise KeyError( + f"LineID {line_id} is not in {self.path.name}; available: {self.line_ids}" + ) + return self.column(channel)[mask].copy() + + def line(self, line_id: int) -> NaturalModes: + """Return the frequency and shape rows of one line. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + NaturalModes + New tables holding only that line's rows. + + Raises + ------ + KeyError + If the file has no modes for ``line_id``. + """ + shapes = self.shapes.line(line_id) + rows = self.values[self.column("LineID") == int(line_id)].copy() + return NaturalModes(self.path, self.title, self.channels, self.units, rows, shapes) + + def mode_numbers(self, line_id: int) -> tuple[int, ...]: + """Return the mode numbers of one line, lowest frequency first. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + tuple[int, ...] + Mode numbers ``1, 2, ...``. + + Raises + ------ + KeyError + If the file has no modes for ``line_id``. + """ + return tuple(int(value) for value in self._line_column("Mode", line_id)) + + def frequencies(self, line_id: int) -> npt.NDArray[Any]: + """Return the natural frequencies of one line in Hz, by mode. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + numpy.ndarray + ``(n_modes,)`` array of ``Frequency``. + + Raises + ------ + KeyError + If the file has no modes for ``line_id``. + """ + return self._line_column("Frequency", line_id) + + def periods(self, line_id: int) -> npt.NDArray[Any]: + """Return the natural periods of one line in s, by mode. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + numpy.ndarray + ``(n_modes,)`` array of ``Period``; 0 for a negative eigenvalue. + + Raises + ------ + KeyError + If the file has no modes for ``line_id``. + """ + return self._line_column("Period", line_id) + + def angular_frequencies(self, line_id: int) -> npt.NDArray[Any]: + """Return the angular natural frequencies of one line in rad/s, by mode. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + numpy.ndarray + ``(n_modes,)`` array of ``Omega``. + + Raises + ------ + KeyError + If the file has no modes for ``line_id``. + """ + return self._line_column("Omega", line_id) + + def polar_shares(self, line_id: int) -> npt.NDArray[Any]: + """Return the polar share of the kinetic energy of each mode of one line. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + numpy.ndarray + ``(n_modes,)`` array of ``PolarShare``, 1 for a pure torsional mode; + zeros in a file without twist angles, as on a line without torsion. + + Raises + ------ + KeyError + If the file has no modes for ``line_id``. + """ + if self.has_twist: + return self._line_column("PolarShare", line_id) + return np.zeros_like(self._line_column("Mode", line_id)) + + def torsional_modes(self, line_id: int) -> tuple[int, ...]: + """Return the modes of one line that are mostly torsional. + + Parameters + ---------- + line_id : int + Line identifier, as in the ``LineID`` column. + + Returns + ------- + tuple[int, ...] + Mode numbers whose ``PolarShare`` is above 0.5, the modes a file + scales to a unit largest ``dTwist``. + + Raises + ------ + KeyError + If the file has no modes for ``line_id``. + """ + share = self.polar_shares(line_id) + return tuple(int(mode) for mode in self._line_column("Mode", line_id)[share > 0.5]) + + _HEADER_FIRST = frozenset({"time", "time(s)", "lineid", "node", "segment"}) _TIME_HEADERS = frozenset({"time", "time(s)"}) +# The first columns of the frequency table of a ``.modes.out`` file, and the comment that +# introduces its mode-shape table. +_MODE_FREQUENCY_CHANNELS = ("LineID", "Mode", "Frequency", "Period", "Omega") +_MODE_SHAPE_COMMENT = "# Mode shapes" # Fortran formatted real output: optional sign, digits with an optional decimal # point, and an optional exponent. ``ES``/``E`` editing omits the exponent @@ -1636,6 +2069,76 @@ def _unique_channels(channels: tuple[str, ...], source: str) -> tuple[str, ...]: return tuple(unique) +def _read_units( + table_path: Path, lines: list[str], cursor: int, channels: tuple[str, ...] +) -> tuple[tuple[str, ...] | None, int]: + """Return the units row at ``cursor``, if there is one, and the index of the first data row.""" + if cursor < len(lines): + tokens = tuple(lines[cursor].split()) + if tokens and all(token.startswith("(") and token.endswith(")") for token in tokens): + if len(tokens) != len(channels): + raise OutputFormatError( + f"{table_path}:{cursor + 1}: expected {len(channels)} units, got {len(tokens)}" + ) + return tokens, cursor + 1 + return None, cursor + + +def _read_rows( + table_path: Path, lines: list[str], start: int, stop: int, channels: tuple[str, ...] +) -> list[list[float]]: + """Parse the data rows ``lines[start:stop]``, one finite value per channel.""" + rows: list[list[float]] = [] + for i in range(start, stop): + fields = lines[i].split() + if not fields: + continue + if len(fields) != len(channels): + raise OutputFormatError( + f"{table_path}:{i + 1}: expected {len(channels)} fields, got {len(fields)}" + ) + rows.append([_parse_float(field, table_path, i + 1) for field in fields]) + return rows + + +def _read_natural_modes( + table_path: Path, + lines: list[str], + header_index: int, + channels: tuple[str, ...], + title: str, +) -> NaturalModes: + """Read the frequency table at ``header_index`` and the mode-shape table after it.""" + units, cursor = _read_units(table_path, lines, header_index + 1, channels) + comment = next( + (i for i in range(cursor, len(lines)) if lines[i].startswith(_MODE_SHAPE_COMMENT)), + None, + ) + if comment is None or comment + 1 >= len(lines): + raise OutputFormatError(f"{table_path}: modal output has no mode-shape table") + rows = _read_rows(table_path, lines, cursor, comment, channels) + shape_channels = tuple(lines[comment + 1].split()) + if len(shape_channels) != len(set(shape_channels)): + raise OutputFormatError(f"{table_path}:{comment + 2}: duplicate channel name") + shape_units, shape_cursor = _read_units(table_path, lines, comment + 2, shape_channels) + shape_rows = _read_rows(table_path, lines, shape_cursor, len(lines), shape_channels) + shapes = ModeShapes( + table_path, + lines[comment], + shape_channels, + shape_units, + np.asarray(shape_rows, dtype=np.float64).reshape(-1, len(shape_channels)), + ) + return NaturalModes( + table_path, + title, + channels, + units, + np.asarray(rows, dtype=np.float64).reshape(-1, len(channels)), + shapes, + ) + + def read_output(path: str | os.PathLike[str]) -> OutputTable: """Read and strictly validate a CableDyn numeric output table. @@ -1654,8 +2157,9 @@ def read_output(path: str | os.PathLike[str]) -> OutputTable: ------- OutputTable A :class:`TimeHistory`, :class:`LineNodeHistory`, - :class:`LineSegmentHistory`, or :class:`StaticProfile` when the layout - is recognized, otherwise a plain :class:`OutputTable`. + :class:`LineSegmentHistory`, :class:`StaticProfile`, or + :class:`NaturalModes` when the layout is recognized, otherwise a plain + :class:`OutputTable`. Raises ------ @@ -1681,28 +2185,10 @@ def read_output(path: str | os.PathLike[str]) -> OutputTable: elif len(channels) != len(set(channels)): raise OutputFormatError(f"{table_path}:{header_index + 1}: duplicate channel name") title = "\n".join(line for line in lines[:header_index] if line.strip()) - cursor = header_index + 1 - units: tuple[str, ...] | None = None - if cursor < len(lines): - tokens = tuple(lines[cursor].split()) - if tokens and all(token.startswith("(") and token.endswith(")") for token in tokens): - if len(tokens) != len(channels): - raise OutputFormatError( - f"{table_path}:{cursor + 1}: expected {len(channels)} units, got {len(tokens)}" - ) - units = tokens - cursor += 1 - - rows: list[list[float]] = [] - for i in range(cursor, len(lines)): - fields = lines[i].split() - if not fields: - continue - if len(fields) != len(channels): - raise OutputFormatError( - f"{table_path}:{i + 1}: expected {len(channels)} fields, got {len(fields)}" - ) - rows.append([_parse_float(field, table_path, i + 1) for field in fields]) + if channels[: len(_MODE_FREQUENCY_CHANNELS)] == _MODE_FREQUENCY_CHANNELS: + return _read_natural_modes(table_path, lines, header_index, channels, title) + units, cursor = _read_units(table_path, lines, header_index + 1, channels) + rows = _read_rows(table_path, lines, cursor, len(lines), channels) if not rows: raise OutputFormatError(f"{table_path}: table has no data rows") values = np.asarray(rows, dtype=np.float64) diff --git a/python/tests/test_modes_output.py b/python/tests/test_modes_output.py new file mode 100644 index 00000000..d069f034 --- /dev/null +++ b/python/tests/test_modes_output.py @@ -0,0 +1,394 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The reader of ``.modes.out``, on files the native driver really writes. + +The driver gates are skipped unless ``CABLEDYN_DRIVER`` or ``CABLEDYN_TEST_DRIVER`` names a +built driver. The malformed files are built from the layout of the tables, row by row. +""" + +from __future__ import annotations + +import math +import os +import shutil +from pathlib import Path + +import numpy as np +import pytest + +from cabledyn import ( + CableDynDriver, + DriverResult, + ModeShapes, + NaturalModes, + OutputFormatError, + OutputTable, + read_output, +) +from cabledyn.formats import read_table + +EXAMPLES = Path(__file__).resolve().parents[2] / "examples" +_DRIVER = ( + os.environ.get("CABLEDYN_DRIVER") or os.environ.get("CABLEDYN_TEST_DRIVER") or "" +).strip() + +needs_driver = pytest.mark.skipif( + not _DRIVER or not Path(_DRIVER).is_file(), + reason="set CABLEDYN_DRIVER to a built native driver to run the modal output gates", +) + +RHO_W, DIAM = 1025.0, 0.1 +# Neutrally buoyant, without added mass: a taut line stays straight. +MASS = RHO_W * math.pi * DIAM**2 / 4.0 +# An EI = 0 line must have weight: this one sags by about a centimetre. +EI0_MASS = 1.01 * MASS +EA, TENSION = 1.0e6, 1000.0 +BAR = "-" * 21 + + +def taut_deck( + lines: list[tuple[float, int]], + *, + ei: float = 0.0, + torsion: tuple[str, ...] = (), + n_modes: int = 6, +) -> str: + """Taut straight lines of (length, segments), side by side, from Coupled to Fixed points. + + ``ei`` above 0 makes a dynamic finite-EI deck, ``torsion`` names the TorsStiffness of the + two ends of each line. + """ + points, line_rows, sections, ends = [], [], [], [] + for index, (length, segments) in enumerate(lines): + line_id = index + 1 + span = length * (1.0 + TENSION / EA) + y = 20.0 * index + points.append(f"{2 * index + 1} Coupled 0.0 {y!r} -100.0") + points.append(f"{2 * index + 2} Fixed {span!r} {y!r} -100.0") + line_rows.append(f"{line_id} {2 * index + 1} {2 * index + 2} -") + sections.append(f"{line_id} cab {length!r} {segments}") + if torsion: + for end in "AB": + ends.append(f"{line_id} {end} Rigid 1 0 0 {torsion[index]} 0 0 1 0") + if ei > 0.0: + types = "Name Diam Mass EA BA EI GAs GJ Irt Irn Cdn Cdt Can Cat\n" + types += f"cab {DIAM!r} {MASS!r} {EA!r} 0.0 {ei!r} 1.0e8 80.0 1.0 0.04 1.2 0.0 0.0 0.0" + march = "0.01 dtM\n0.01 TMax\n" + else: + types = "Name Diam Mass EA BA EI Cdn Cdt Can Cat\n" + types += f"cab {DIAM!r} {EI0_MASS!r} {EA!r} -1.0 0.0 1.2 0.0 0.0 0.0" + march = "" + connections = "" + if ends: + connections = ( + f"{BAR} END CONNECTIONS {BAR}\n" + "LineID End Stiffness EzX EzY EzZ TorsStiffness NxX NxY NxZ Pretwist\n" + + "\n".join(ends) + + "\n" + ) + return ( + f"{BAR} CableDyn Input File {BAR}\n" + "taut straight lines\n" + f"{BAR} LINE TYPES {BAR}\n{types}\n" + f"{BAR} POINTS {BAR}\nID Type X Y Z\n" + "\n".join(points) + "\n" + f"{BAR} LINES {BAR}\nID NodeA NodeB Outputs\n" + "\n".join(line_rows) + "\n" + f"{BAR} SECTIONS {BAR}\nLineID LineType Length NumSegs\n" + + "\n".join(sections) + + "\n" + + connections + + f"{BAR} OPTIONS {BAR}\n9.80665 g\n{RHO_W!r} rhoW\n500.0 WtrDpth\n" + + march + + f"{n_modes} nModes\n{BAR} OUTPUTS {BAR}\nFairTen1\n{BAR} need this line {BAR}\n" + ) + + +def run_modes(tmp_path: Path, deck_text: str, name: str = "modes"): + deck = tmp_path / f"{name}.dat" + deck.write_text(deck_text, encoding="utf-8") + return CableDynDriver(_DRIVER).run(deck, tmp_path / name, timeout=300) + + +@needs_driver +def test_ei0_lines_read_both_tables(tmp_path): + lengths = [(10.0, 20), (20.0, 10)] + result = run_modes(tmp_path, taut_deck(lengths)) + assert result.modes_output == tmp_path / "modes.modes.out" + modes = read_output(result.modes_output) + assert isinstance(modes, NaturalModes) and isinstance(modes, OutputTable) + assert isinstance(modes.shapes, ModeShapes) + assert modes.channels == ("LineID", "Mode", "Frequency", "Period", "Omega") + assert modes.unit("Frequency") == "Hz" and modes.unit("Period") == "s" + assert modes.unit("Omega") == "rad/s" + assert modes.shapes.unit("X") == "m" and not modes.has_twist + assert modes.title.startswith("# CableDyn modal analysis") + assert modes.shapes.title.startswith("# Mode shapes") + assert modes.line_ids == (1, 2) and modes.shapes.line_ids == (1, 2) + assert read_table(result.modes_output).line_ids == (1, 2) + assert result.read_modes().line_ids == (1, 2) + + for line_id, (length, segments) in enumerate(lengths, start=1): + assert modes.mode_numbers(line_id) == (1, 2, 3, 4, 5, 6) + assert modes.shapes.node_ids(line_id) == tuple(range(1, segments + 2)) + frequency = modes.frequencies(line_id) + assert np.all(np.diff(frequency) >= 0.0) and frequency[0] > 0.0 + assert modes.periods(line_id) == pytest.approx(1.0 / frequency, rel=1e-7) + omega = modes.angular_frequencies(line_id) + assert omega == pytest.approx(2.0 * math.pi * frequency, rel=1e-7) + # The two transverse planes of a taut string share each frequency, sqrt(T/m)/(2 L). + string = math.sqrt(TENSION / EI0_MASS) / (2.0 * length * (1.0 + TENSION / EA)) + assert frequency[0] == pytest.approx(string, rel=2e-2) + assert not np.any(modes.polar_shares(line_id)) and modes.torsional_modes(line_id) == () + + xyz = modes.shapes.positions(line_id) + assert xyz.shape == (segments + 1, 3) + assert xyz[0] == pytest.approx([0.0, 20.0 * (line_id - 1), -100.0], abs=1e-6) + for mode in modes.mode_numbers(line_id): + shape = modes.shapes.displacements(line_id, mode) + assert shape.shape == (segments + 1, 3) + assert np.max(np.linalg.norm(shape, axis=1)) == pytest.approx(1.0, rel=1e-7) + assert not np.any(shape[0]) and not np.any(shape[-1]) # held ends + assert not np.any(modes.shapes.twist(line_id, mode)) + # The first mode of a string is a half sine. + arc = np.linspace(0.0, 1.0, segments + 1) + first = np.linalg.norm(modes.shapes.displacements(line_id, 1), axis=1) + assert first == pytest.approx(np.sin(math.pi * arc), abs=2e-2) + + line_2 = modes.line(2) + assert isinstance(line_2, NaturalModes) and line_2.line_ids == (2,) + assert line_2.shapes.line_ids == (2,) + assert line_2.frequencies(2) == pytest.approx(modes.frequencies(2)) + with pytest.raises(KeyError, match="LineID 3"): + modes.line(3) + with pytest.raises(KeyError, match="no mode 7"): + modes.shapes.displacements(1, 7) + + +@needs_driver +def test_finite_ei_lines_read_both_tables(tmp_path): + lengths = [(10.0, 20), (15.0, 30)] + modes = run_modes(tmp_path, taut_deck(lengths, ei=100.0)).read_modes() + assert modes.line_ids == (1, 2) and not modes.has_twist + for line_id, (_, segments) in enumerate(lengths, start=1): + assert len(modes.mode_numbers(line_id)) == 6 + assert np.all(modes.frequencies(line_id) > 0.0) + assert modes.shapes.node_ids(line_id) == tuple(range(1, segments + 2)) + shape = modes.shapes.displacements(line_id, 1) + assert np.max(np.linalg.norm(shape, axis=1)) == pytest.approx(1.0, rel=1e-7) + + +@needs_driver +def test_torsional_modes_on_one_of_several_lines(tmp_path): + deck = taut_deck([(10.0, 40), (10.0, 20)], ei=100.0, torsion=("Rigid", "Free"), n_modes=24) + modes = run_modes(tmp_path, deck).read_modes() + assert modes.has_twist and modes.line_ids == (1, 2) + assert modes.channels[-1] == "PolarShare" and modes.shapes.channels[-1] == "dTwist" + torsional = modes.torsional_modes(1) + assert torsional + assert modes.polar_shares(1)[torsional[0] - 1] > 0.5 + twist = modes.shapes.twist(1, torsional[0]) + assert np.max(np.abs(twist)) == pytest.approx(1.0, rel=1e-7) + assert abs(twist) == pytest.approx(np.sin(math.pi * np.linspace(0.0, 1.0, 41)), abs=1e-3) + # The line without torsion has the columns, at zero. + assert modes.torsional_modes(2) == () and not np.any(modes.polar_shares(2)) + assert not np.any(modes.shapes.twist(2, 1)) + + +@needs_driver +def test_a_line_without_free_nodes_has_no_rows(tmp_path): + result = run_modes(tmp_path, taut_deck([(10.0, 1), (10.0, 8)])) + modes = result.read_modes() + assert modes.line_ids == (2,) and modes.shapes.line_ids == (2,) + with pytest.raises(KeyError, match="LineID 1"): + modes.frequencies(1) + + alone = run_modes(tmp_path, taut_deck([(10.0, 1)]), "alone").read_modes() + assert alone.line_ids == () and alone.values.shape == (0, 5) + assert alone.shapes.values.shape == (0, 9) + + +@needs_driver +def test_a_shipped_modal_example_on_a_seabed(tmp_path): + deck = tmp_path / "chain_modes.dat" + shutil.copyfile(EXAMPLES / deck.name, deck) + modes = CableDynDriver(_DRIVER).run(deck, tmp_path / "chain", timeout=300).read_modes() + assert modes.line_ids == (1,) and len(modes.mode_numbers(1)) == 12 + # doc/tutorial_catenary.rst states the first period. + assert modes.periods(1)[0] == pytest.approx(47.1, abs=0.05) + assert modes.shapes.node_ids(1) == tuple(range(1, 57)) + # Nodes run from End A, the fairlead of this deck. + assert modes.shapes.positions(1)[0] == pytest.approx([0.0, 0.0, 0.0], abs=1e-6) + + +@needs_driver +def test_a_run_without_modes_has_no_modal_output(tmp_path): + deck = taut_deck([(10.0, 8)]).replace("6 nModes\n", "") + result = run_modes(tmp_path, deck) + assert result.modes_output is None + with pytest.raises(FileNotFoundError, match=r"\.modes\.out"): + result.read_modes() + + +HEADER = ( + "# CableDyn modal analysis about the static equilibrium\n" + "# Natural frequencies\n" + "LineID\tMode\tFrequency\tPeriod\tOmega\n" + "(-)\t(-)\t(Hz)\t(s)\t(rad/s)\n" +) +SHAPE_HEADER = ( + "# Mode shapes (nodal translations, unit largest nodal displacement)\n" + "LineID\tMode\tNode\tX\tY\tZ\tdX\tdY\tdZ\n" + "(-)\t(-)\t(-)\t(m)\t(m)\t(m)\t(-)\t(-)\t(-)\n" +) +FREQUENCY_ROWS = "1\t1\t2.0E-1\t5.0E+0\t1.25E+0\n1\t2\t4.0E-1\t2.5E+0\t2.5E+0\n" +SHAPE_ROWS = ( + "1\t1\t1\t0.0\t0.0\t-1.0\t0.0\t0.0\t0.0\n" + "1\t1\t2\t1.0\t0.0\t-1.0\t0.0\t0.0\t1.0\n" + "1\t2\t1\t0.0\t0.0\t-1.0\t0.0\t0.0\t0.0\n" + "1\t2\t2\t1.0\t0.0\t-1.0\t0.0\t1.0\t0.0\n" +) + + +def write(tmp_path: Path, text: str) -> Path: + path = tmp_path / "table.modes.out" + path.write_text(text, encoding="utf-8") + return path + + +def test_a_negative_eigenvalue_reads_as_written(tmp_path): + rows = "1\t1\t-2.0E-1\t0.0E+0\t-1.25E+0\n1\t2\t4.0E-1\t2.5E+0\t2.5E+0\n" + modes = read_output(write(tmp_path, HEADER + rows + SHAPE_HEADER + SHAPE_ROWS)) + assert modes.frequencies(1)[0] == -0.2 and modes.periods(1)[0] == 0.0 + assert modes.angular_frequencies(1)[0] == -1.25 + + +def test_the_accessors_of_a_file_with_twist_columns(tmp_path): + header = HEADER.replace("\tOmega", "\tOmega\tPolarShare").replace("(rad/s)", "(rad/s)\t(-)") + frequency = "1\t1\t2.0E-1\t5.0E+0\t1.25E+0\t0.0E+0\n1\t2\t4.0E-1\t2.5E+0\t2.5E+0\t9.0E-1\n" + shape_header = SHAPE_HEADER.replace("\tdZ", "\tdZ\tdTwist").replace( + "(-)\t(-)\t(-)\n", "(-)\t(-)\t(-)\t(-)\n" + ) + shapes = SHAPE_ROWS.replace("0.0\n", "0.0\t0.0\n").replace("1.0\n", "1.0\t1.0\n") + modes = read_output(write(tmp_path, header + frequency + shape_header + shapes)) + assert modes.has_twist and modes.torsional_modes(1) == (2,) + assert modes.mode_numbers(1) == (1, 2) + assert list(modes.polar_shares(1)) == [0.0, 0.9] + assert list(modes.periods(1)) == [5.0, 2.5] + assert list(modes.frequencies(1)) == [0.2, 0.4] + assert list(modes.angular_frequencies(1)) == [1.25, 2.5] + assert list(modes.shapes.twist(1, 1)) == [0.0, 1.0] + assert modes.shapes.node_ids(1) == (1, 2) + assert modes.shapes.positions(1).tolist() == [[0.0, 0.0, -1.0], [1.0, 0.0, -1.0]] + assert modes.shapes.displacements(1, 2).tolist() == [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0]] + assert modes.line(1).shapes.values.shape == modes.shapes.values.shape + assert modes.values.flags.writeable is False + + +def test_the_accessors_of_a_file_without_twist_columns(tmp_path): + modes = read_output(write(tmp_path, HEADER + FREQUENCY_ROWS + SHAPE_HEADER + SHAPE_ROWS)) + assert not modes.has_twist and modes.torsional_modes(1) == () + assert list(modes.polar_shares(1)) == [0.0, 0.0] + assert list(modes.shapes.twist(1, 1)) == [0.0, 0.0] + with pytest.raises(KeyError, match="LineID 2"): + modes.frequencies(2) + with pytest.raises(KeyError, match="LineID 2"): + modes.shapes.positions(2) + + +def test_read_modes_refuses_a_file_of_another_kind(tmp_path): + other = tmp_path / "other.out" + other.write_text("Time(s) FairTen1\n0.0 1.0\n", encoding="utf-8") + result = DriverResult( + executable=tmp_path / "driver", + deck=tmp_path / "deck.dat", + output_root=tmp_path / "run", + main_output=tmp_path / "run.out", + static_output=None, + elements_output=None, + line_outputs=(), + rod_outputs=(), + stdout="", + stderr="", + returncode=0, + modes_output=other, + ) + with pytest.raises(OutputFormatError, match="no modal tables"): + result.read_modes() + + +def test_a_table_built_without_the_frequency_columns_is_refused(tmp_path): + shapes = read_output( + write(tmp_path, HEADER + FREQUENCY_ROWS + SHAPE_HEADER + SHAPE_ROWS) + ).shapes + with pytest.raises(OutputFormatError, match="frequency table missing Omega"): + NaturalModes( + tmp_path / "table.modes.out", + "", + ("LineID", "Mode", "Frequency", "Period"), + None, + np.array([[1.0, 1.0, 0.2, 5.0], [1.0, 2.0, 0.4, 2.5]]), + shapes, + ) + + +def test_the_tables_are_found_by_layout_not_by_file_name(tmp_path): + path = tmp_path / "renamed.txt" + path.write_text(HEADER + FREQUENCY_ROWS + SHAPE_HEADER + SHAPE_ROWS, encoding="utf-8") + assert isinstance(read_output(path), NaturalModes) + + +@pytest.mark.parametrize( + ("text", "match"), + [ + (HEADER + FREQUENCY_ROWS, "no mode-shape table"), + (HEADER + FREQUENCY_ROWS + SHAPE_HEADER.splitlines()[0], "no mode-shape table"), + (HEADER + FREQUENCY_ROWS + SHAPE_HEADER, "same lines"), + ( + HEADER + FREQUENCY_ROWS + SHAPE_HEADER.replace("\tdY", "\tdX") + SHAPE_ROWS, + "duplicate channel name", + ), + # Cut after a whole mode, inside a mode, and inside a row. + ( + HEADER + FREQUENCY_ROWS + SHAPE_HEADER + "".join(SHAPE_ROWS.splitlines(True)[:2]), + "2 frequency rows but 1 mode shapes", + ), + ( + HEADER + FREQUENCY_ROWS + SHAPE_HEADER + "".join(SHAPE_ROWS.splitlines(True)[:3]), + "not the nodes", + ), + (HEADER + FREQUENCY_ROWS + SHAPE_HEADER + SHAPE_ROWS[:-6], "expected 9 fields"), + ( + HEADER + FREQUENCY_ROWS.splitlines(True)[1] + SHAPE_HEADER + SHAPE_ROWS, + "modes are not numbered", + ), + ( + HEADER + "1\t1\tNaN\t5.0\t1.25\n" + SHAPE_HEADER + SHAPE_ROWS, + "nonnumeric", + ), + ( + HEADER + + FREQUENCY_ROWS + + SHAPE_HEADER + + SHAPE_ROWS.replace("1\t2\t2\t1.0", "1\t2\t2\t2.0"), + "static positions differ", + ), + ( + HEADER + FREQUENCY_ROWS + SHAPE_HEADER.replace("\tdZ", "\tdQ") + SHAPE_ROWS, + "missing dZ", + ), + ( + HEADER.replace("\tOmega", "\tOmega\tPolarShare").replace("(rad/s)", "(rad/s)\t(-)") + + FREQUENCY_ROWS.replace("\n", "\t0.0\n") + + SHAPE_HEADER + + SHAPE_ROWS, + "must appear together", + ), + ], +) +def test_malformed_modal_files_are_refused(tmp_path, text, match): + with pytest.raises(OutputFormatError, match=match): + read_output(write(tmp_path, text)) + + +def test_a_line_split_between_rows_is_refused(tmp_path): + frequency = "1\t1\t0.2\t5.0\t1.25\n2\t1\t0.2\t5.0\t1.25\n1\t2\t0.4\t2.5\t2.5\n" + with pytest.raises(OutputFormatError, match="not contiguous"): + read_output(write(tmp_path, HEADER + frequency + SHAPE_HEADER + SHAPE_ROWS)) From ae1204f9d3635d18ca329bc722b877bc38d1e80f Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 7 Nov 2026 22:58:17 +0900 Subject: [PATCH 2/2] fix(python): annotate the modal row masks for the type check Signed-off-by: Jae Hoon Seo --- python/cabledyn/results.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/python/cabledyn/results.py b/python/cabledyn/results.py index b8e5fc4d..02c3bcef 100644 --- a/python/cabledyn/results.py +++ b/python/cabledyn/results.py @@ -1588,7 +1588,7 @@ def line_ids(self) -> tuple[int, ...]: return tuple(dict.fromkeys(int(value) for value in self.column("LineID"))) def _line_rows(self, line_id: int) -> npt.NDArray[np.bool_]: - mask = self.column("LineID") == int(line_id) + mask: npt.NDArray[np.bool_] = self.column("LineID") == int(line_id) if not np.any(mask): raise KeyError( f"LineID {line_id} is not in {self.path.name}; available: {self.line_ids}" @@ -1596,7 +1596,7 @@ def _line_rows(self, line_id: int) -> npt.NDArray[np.bool_]: return mask def _mode_rows(self, line_id: int, mode: int) -> npt.NDArray[np.bool_]: - mask = self._line_rows(line_id) & (self.column("Mode") == int(mode)) + mask: npt.NDArray[np.bool_] = self._line_rows(line_id) & (self.column("Mode") == int(mode)) if not np.any(mask): raise KeyError(f"LineID {line_id} has no mode {mode} in {self.path.name}") return mask @@ -1794,7 +1794,8 @@ def _line_column(self, channel: str, line_id: int) -> npt.NDArray[Any]: raise KeyError( f"LineID {line_id} is not in {self.path.name}; available: {self.line_ids}" ) - return self.column(channel)[mask].copy() + values: npt.NDArray[Any] = self.column(channel)[mask].copy() + return values def line(self, line_id: int) -> NaturalModes: """Return the frequency and shape rows of one line.