ibfoamrig 2.0.0__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.
ibfoamrig/__init__.py ADDED
@@ -0,0 +1,37 @@
1
+ """Lambda Utilities: managing and post-processing OpenFOAM cases.
2
+
3
+ Subpackages:
4
+
5
+ * `ibfoamrig.io`: readers for OpenFOAM field files and post-processing tables.
6
+ * `ibfoamrig.core`: cases, data containers, time directories and sampling.
7
+ * `ibfoamrig.plot`: plotting functions, imported separately to avoid loading
8
+ matplotlib on headless machines, e.g.
9
+ ``from ibfoamrig.plot import plot_profile``.
10
+ """
11
+
12
+ from importlib.metadata import PackageNotFoundError
13
+ from importlib.metadata import version
14
+
15
+ from ibfoamrig.core import CaseManager
16
+ from ibfoamrig.core import FieldData
17
+ from ibfoamrig.core import FoamCase
18
+ from ibfoamrig.core import InterpolationData
19
+ from ibfoamrig.core import ResidualData
20
+ from ibfoamrig.core import Sampler
21
+ from ibfoamrig.exceptions import IbfoamrigError
22
+
23
+ try:
24
+ __version__ = version("ibfoamrig")
25
+ except PackageNotFoundError:
26
+ __version__ = "0.0.0"
27
+
28
+ __all__ = [
29
+ "CaseManager",
30
+ "FieldData",
31
+ "FoamCase",
32
+ "InterpolationData",
33
+ "IbfoamrigError",
34
+ "ResidualData",
35
+ "Sampler",
36
+ "__version__",
37
+ ]
ibfoamrig/_typing.py ADDED
@@ -0,0 +1,9 @@
1
+ """Shared type aliases used across ibfoamrig."""
2
+
3
+ import os
4
+
5
+ type StrPath = str | os.PathLike[str]
6
+ """A filesystem path given either as a string or a path-like object."""
7
+
8
+ type Point = tuple[float, float, float]
9
+ """Spatial coordinates of a cell."""
@@ -0,0 +1,40 @@
1
+ """Cases, data containers, time directories and sampling.
2
+
3
+ * `FoamCase` and `CaseManager` locate files in one or several cases.
4
+ * `FieldData`, `ResidualData` and `InterpolationData` hold loaded data.
5
+ * `Sampler` interpolates cell values at arbitrary points.
6
+ """
7
+
8
+ from ibfoamrig.core.case import Distribution
9
+ from ibfoamrig.core.case import FieldStats
10
+ from ibfoamrig.core.case import FoamCase
11
+ from ibfoamrig.core.case import TimeSpec
12
+ from ibfoamrig.core.data import FieldData
13
+ from ibfoamrig.core.data import InterpolationData
14
+ from ibfoamrig.core.data import ResidualData
15
+ from ibfoamrig.core.manager import CaseManager
16
+ from ibfoamrig.core.sampling import line_points
17
+ from ibfoamrig.core.sampling import Method
18
+ from ibfoamrig.core.sampling import Sampler
19
+ from ibfoamrig.core.time_dirs import find_time
20
+ from ibfoamrig.core.time_dirs import latest_time
21
+ from ibfoamrig.core.time_dirs import list_times
22
+ from ibfoamrig.core.time_dirs import TimeDirectory
23
+
24
+ __all__ = [
25
+ "CaseManager",
26
+ "Distribution",
27
+ "FieldData",
28
+ "FieldStats",
29
+ "FoamCase",
30
+ "InterpolationData",
31
+ "Method",
32
+ "ResidualData",
33
+ "Sampler",
34
+ "TimeDirectory",
35
+ "TimeSpec",
36
+ "find_time",
37
+ "latest_time",
38
+ "line_points",
39
+ "list_times",
40
+ ]
ibfoamrig/core/case.py ADDED
@@ -0,0 +1,324 @@
1
+ """Access to the files of a single OpenFOAM case.
2
+
3
+ `FoamCase` knows where things live inside a case directory and returns the
4
+ ibfoamrig containers for them. It is stateless, every method reads from disk and
5
+ returns a new object.
6
+ """
7
+
8
+ import dataclasses
9
+ from pathlib import Path
10
+ import subprocess
11
+ from typing import Literal, NamedTuple
12
+
13
+ import numpy as np
14
+ import polars as pl
15
+
16
+ from ibfoamrig._typing import StrPath
17
+ from ibfoamrig.core import time_dirs
18
+ from ibfoamrig.core.data import FieldData
19
+ from ibfoamrig.core.data import InterpolationData
20
+ from ibfoamrig.core.data import ResidualData
21
+ from ibfoamrig.core.time_dirs import TimeDirectory
22
+ from ibfoamrig.exceptions import CaseNotFoundError
23
+ from ibfoamrig.exceptions import ScriptError
24
+ from ibfoamrig.io import foam_file
25
+ from ibfoamrig.io import tables
26
+
27
+ type Distribution = Literal["org", "com"]
28
+ """OpenFOAM distribution: ``"org"`` (Foundation, e.g. v8) or ``"com"``
29
+ (ESI, e.g. v2312)."""
30
+
31
+ type TimeSpec = str | float
32
+ """A time directory: ``latest``, a directory name such as ``"3000"``, or
33
+ a time value such as ``0.5``."""
34
+
35
+
36
+ class FieldStats(NamedTuple):
37
+ """Summary statistics of a field over a subset of cells.
38
+
39
+ Attributes:
40
+ cells: Number of cells included.
41
+ mean: Arithemtic mean of the values.
42
+ min: Smallest value.
43
+ max: Largest value.
44
+ """
45
+
46
+ cells: int
47
+ mean: float
48
+ min: float
49
+ max: float
50
+
51
+
52
+ @dataclasses.dataclass(frozen=True, slots=True)
53
+ class FoamCase:
54
+ """An OpenFOAM case directory.
55
+
56
+ Attributes:
57
+ path: Path to the case directory.
58
+ label: Name of the case in plots and messages. Defaults to the name
59
+ of the case directory.
60
+ distribution: OpenFOAM distribution that ran the case.
61
+ """
62
+
63
+ path: Path
64
+ label: str = ""
65
+ distribution: Distribution = "org"
66
+
67
+ def __post_init__(self) -> None:
68
+ """Normalises the path and label and checks the case exists.
69
+
70
+ Raises:
71
+ CaseNotFoundError: If ``path`` is not a directory.
72
+ """
73
+ path = Path(self.path)
74
+ if not path.is_dir():
75
+ raise CaseNotFoundError(f"case not found: {path}")
76
+ # class is frozen, fields set through object
77
+ object.__setattr__(self, "path", path)
78
+ if not self.label:
79
+ object.__setattr__(self, "label", path.resolve().name)
80
+
81
+ def times(self, *, no_zero: bool = False) -> list[TimeDirectory]:
82
+ """Lists the time directories in ascending order.
83
+
84
+ Args:
85
+ no_zero: If True, the zero time directory is left out.
86
+
87
+ Returns:
88
+ The time directories, empty if there are none.
89
+ """
90
+ return time_dirs.list_times(self.path, no_zero=no_zero)
91
+
92
+ def time(self, time: TimeSpec = "latest") -> TimeDirectory:
93
+ """Finds a time directory.
94
+
95
+ Args:
96
+ time: ``"latest"``, a directory name or a time value.
97
+
98
+ Returns:
99
+ The matching time directory.
100
+
101
+ Raises:
102
+ TimeNotFoundError: If no time directory matches.
103
+ """
104
+ if time == "latest":
105
+ return time_dirs.latest_time(self.path)
106
+ return time_dirs.find_time(self.path, time)
107
+
108
+ def read_field(
109
+ self, name: str, time: TimeSpec = "latest"
110
+ ) -> foam_file.FoamField:
111
+ """Reads a field file from a time directory.
112
+
113
+ Args:
114
+ name: Field name.
115
+ time: The time directory, see `time`.
116
+
117
+ Returns:
118
+ The internal field.
119
+
120
+ Raises:
121
+ TimeNotFoundError: If the time directory does not exist.
122
+ FileNotFoundError: If the field file does not exist.
123
+ FoamParseError: If the file cannot be parsed.
124
+ """
125
+ return foam_file.read_field(self.time(time).path / name)
126
+
127
+ def fields_at(
128
+ self,
129
+ names: list[str],
130
+ time: TimeSpec = "latest",
131
+ *,
132
+ centres: str = "C",
133
+ volumes: str | None = "V",
134
+ ) -> FieldData:
135
+ """Builds field data from the field files of a time directory.
136
+
137
+ The cell centres come from the ``C`` field, written by
138
+ ``postProcess -func writeCellCentres``. Cell volumes are added if a
139
+ ``V`` field exists.
140
+
141
+ Args:
142
+ names: Fields to include.
143
+ time: The time directory, see `time`.
144
+ centres: Name of the cell-centre field.
145
+ volumes: Name of the cell-volume field, or None to skip it.
146
+
147
+ Returns:
148
+ The field data, with cells in mesh order.
149
+
150
+ Raises:
151
+ TimeNotFoundError: If the time directory does not exist.
152
+ FileNotFoundError: If the cell centres or a field are missing.
153
+ ValueError: If a field does not match the number of cells.
154
+ """
155
+ directory = self.time(time)
156
+ if not (directory.path / centres).is_file():
157
+ raise FileNotFoundError(
158
+ f"no cell centres {centres!r} in {directory.path}, write "
159
+ f"them with `postProcess -func writeCellCentres -time "
160
+ f"{directory.name}`"
161
+ )
162
+
163
+ volume_field = None
164
+ if volumes is not None and (directory.path / volumes).is_file():
165
+ volume_field = self.read_field(volumes, directory.name)
166
+
167
+ return FieldData.from_fields(
168
+ self.read_field(centres, directory.name),
169
+ [self.read_field(name, directory.name) for name in names],
170
+ volumes=volume_field,
171
+ )
172
+
173
+ def field_data(
174
+ self, table: StrPath, *, fields: list[str] | None = None
175
+ ) -> FieldData:
176
+ """Loads a table written by a function object.
177
+
178
+ Args:
179
+ table: Path to the table, relative to the case directory.
180
+ fields: Field columns to keep. If None, all are loaded.
181
+
182
+ Returns:
183
+ The loaded field data.
184
+
185
+ Raises:
186
+ FileNotFoundError: If the table does not exist.
187
+ FoamParseError: If a requested column is missing.
188
+ """
189
+ return FieldData.from_file(self.path / table, fields=fields)
190
+
191
+ def residuals(self, function: str = "residuals") -> ResidualData:
192
+ """Loads the residuals written by the residuals function object.
193
+
194
+ A restarted run writes one ``residuals.dat`` per start time. They are
195
+ joined in time order. Where runs overlap, the later run is kept.
196
+
197
+ Args:
198
+ function: Name of the function object.
199
+
200
+ Returns:
201
+ The residuals of the whole run.
202
+
203
+ Raises:
204
+ NotImplementedError: For ``"com"`` cases, whose output format is
205
+ not supported yet.
206
+ FileNotFoundError: If no residual file exists.
207
+ FoamParseError: If a file is malformed.
208
+ """
209
+ if self.distribution != "org":
210
+ raise NotImplementedError(
211
+ f"residuals of {self.distribution!r} cases are not supported"
212
+ )
213
+
214
+ root = self.path / "postProcessing" / function
215
+ files = [
216
+ entry.path / "residuals.dat"
217
+ for entry in _times_or_empty(root)
218
+ if (entry.path / "residuals.dat").is_file()
219
+ ]
220
+ if not files:
221
+ raise FileNotFoundError(f"no rediduals.dat found under {root}")
222
+
223
+ frames = [tables.read_residuals(file) for file in files]
224
+ # Drop rows that are overwritten by a later time
225
+ for index, later in enumerate(frames[1:]):
226
+ if not later.is_empty():
227
+ start = later.get_column("Time")[0]
228
+ frames[index] = frames[index].filter(pl.col("Time") < start)
229
+
230
+ return ResidualData(frame=pl.concat(frames, how="diagonal_relaxed"))
231
+
232
+ def interpolation(
233
+ self, table: StrPath, cells: FieldData
234
+ ) -> InterpolationData:
235
+ """Loads IBM interpolation info and joins the cell centres.
236
+
237
+ Args:
238
+ table: Path to the interpolation info, relative to the case
239
+ directory.
240
+ cells: Field data of this case providing the cell centres.
241
+
242
+ Returns:
243
+ The interpolation data, one row per boundary cell.
244
+
245
+ Raises:
246
+ FileNotFoundError: If the table does not exist.
247
+ ValueError: If a boundary cell is missing from ``cells``.
248
+ """
249
+ return InterpolationData.from_file(self.path / table, cells)
250
+
251
+ def boundary_stats(
252
+ self, field: str = "yPlusi", time: TimeSpec = "latest"
253
+ ) -> FieldStats:
254
+ """Summarises a field over the IBM boundary cells.
255
+
256
+ The solver writes boundary fields such as with a positive values
257
+ in boundary cells and zero or ``-1`` elsewhere, so only positive
258
+ values are included.
259
+
260
+ Args:
261
+ field: Name of the field.
262
+ time: The time directory, see `time`.
263
+
264
+ Returns:
265
+ Cell count, mean, minimum and maximum over the boundary cells.
266
+
267
+ Raises:
268
+ TimeNotFoundError: If the time directory does not exist.
269
+ FileNotFoundError: If the field file does not exist.
270
+ ValueError: If the field is not a scalar or has no positive
271
+ values.
272
+ """
273
+ values = self.read_field(field, time).values
274
+ if values.ndim != 1:
275
+ raise ValueError(f"field {field!r} is not a scalar field")
276
+ boundary = values[values > 0]
277
+
278
+ if boundary.size == 0:
279
+ raise ValueError(f"field {field!r} has no positive values")
280
+
281
+ return FieldStats(
282
+ cells=int(boundary.size),
283
+ mean=float(np.mean(boundary)),
284
+ min=float(np.min(boundary)),
285
+ max=float(np.max(boundary)),
286
+ )
287
+
288
+ def run(self, script: StrPath, *args: str) -> None:
289
+ """Runs a script with the case directory as working directory.
290
+
291
+ The script's output does to the terminal as usual.
292
+
293
+ Args:
294
+ script: Path to an executable script. A relative path is resolved
295
+ against the case directory, e.g. ``"Allrun"``.
296
+
297
+ Raises:
298
+ FileNotFoundError: If the script does not exist.
299
+ ScriptError: If the script cannot be started ot exits with a
300
+ non-zero code.
301
+ """
302
+ executable = self.path / script
303
+ if not executable.is_file():
304
+ raise FileNotFoundError(f"script not found: {executable}")
305
+ try:
306
+ subprocess.run(
307
+ [str(executable.resolve()), *args], cwd=self.path, check=True
308
+ )
309
+ except subprocess.CalledProcessError as error:
310
+ raise ScriptError(
311
+ f"{executable.name} failed in case {self.label!r} with exit "
312
+ f"code {error.returncode}"
313
+ ) from error
314
+ except OSError as error:
315
+ raise ScriptError(
316
+ f"cannot run {executable} in case {self.label!r}: {error}"
317
+ ) from error
318
+
319
+
320
+ def _times_or_empty(root: Path) -> list[TimeDirectory]:
321
+ """Lists the time directories of ``root``, or none if it is missing."""
322
+ if not root.is_dir():
323
+ return []
324
+ return time_dirs.list_times(root)