cfdbender 0.4.2__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.
Files changed (77) hide show
  1. cfdbender/__init__.py +7 -0
  2. cfdbender/_pyfs.py +92 -0
  3. cfdbender/core/__init__.py +13 -0
  4. cfdbender/core/adapter.py +148 -0
  5. cfdbender/core/executables.py +157 -0
  6. cfdbender/core/flight.py +346 -0
  7. cfdbender/core/matrix.py +354 -0
  8. cfdbender/core/naming.py +172 -0
  9. cfdbender/core/plan.py +463 -0
  10. cfdbender/core/registry.py +735 -0
  11. cfdbender/core/results.py +117 -0
  12. cfdbender/core/run.py +150 -0
  13. cfdbender/core/settings.py +92 -0
  14. cfdbender/core/workspace.py +93 -0
  15. cfdbender/geometry/__init__.py +1 -0
  16. cfdbender/geometry/blade_slicing.py +355 -0
  17. cfdbender/hpc/__init__.py +21 -0
  18. cfdbender/hpc/_plan.py +266 -0
  19. cfdbender/hpc/_profiles.py +305 -0
  20. cfdbender/hpc/_render.py +271 -0
  21. cfdbender/hpc/_submit.py +96 -0
  22. cfdbender/hpc/_walltime.py +301 -0
  23. cfdbender/matrix/__init__.py +1 -0
  24. cfdbender/matrix/cli.py +228 -0
  25. cfdbender/matrix/collection.py +251 -0
  26. cfdbender/matrix/exports.py +122 -0
  27. cfdbender/matrix/rerun.py +126 -0
  28. cfdbender/matrix/selection.py +62 -0
  29. cfdbender/matrix/submission.py +272 -0
  30. cfdbender/solvers/__init__.py +47 -0
  31. cfdbender/solvers/_host/__init__.py +1 -0
  32. cfdbender/solvers/_host/_config.py +10 -0
  33. cfdbender/solvers/_host/_execute.py +52 -0
  34. cfdbender/solvers/_host/_mesh.py +62 -0
  35. cfdbender/solvers/_host/_ram.py +69 -0
  36. cfdbender/solvers/_host/_single.py +63 -0
  37. cfdbender/solvers/flightstream/__init__.py +114 -0
  38. cfdbender/solvers/flightstream/reader.py +191 -0
  39. cfdbender/solvers/mock/__init__.py +273 -0
  40. cfdbender/solvers/openfoam/__init__.py +201 -0
  41. cfdbender/solvers/openfoam/_config.py +410 -0
  42. cfdbender/solvers/openfoam/_execute.py +162 -0
  43. cfdbender/solvers/openfoam/_history.py +158 -0
  44. cfdbender/solvers/pyfr/__init__.py +118 -0
  45. cfdbender/solvers/pyfr/_config.py +196 -0
  46. cfdbender/solvers/pyfr/_execute.py +127 -0
  47. cfdbender/solvers/pyfr/_history.py +88 -0
  48. cfdbender/solvers/qprop/__init__.py +303 -0
  49. cfdbender/solvers/qprop/_config.py +259 -0
  50. cfdbender/solvers/qprop/_execute.py +269 -0
  51. cfdbender/solvers/qprop/_output.py +64 -0
  52. cfdbender/solvers/qprop/_polar.py +98 -0
  53. cfdbender/solvers/qprop/_prop.py +81 -0
  54. cfdbender/solvers/qprop/_sections.py +193 -0
  55. cfdbender/solvers/su2/__init__.py +210 -0
  56. cfdbender/solvers/su2/_config.py +290 -0
  57. cfdbender/solvers/su2/_execute.py +196 -0
  58. cfdbender/solvers/su2/_history.py +117 -0
  59. cfdbender/solvers/su2/_pysu2_worker.py +25 -0
  60. cfdbender/solvers/su2/_ram.py +13 -0
  61. cfdbender/solvers/su2/_reference.py +79 -0
  62. cfdbender/solvers/su2/_single.py +3 -0
  63. cfdbender/solvers/su2/routes.py +61 -0
  64. cfdbender/solvers/xfoil/__init__.py +171 -0
  65. cfdbender/solvers/xfoil/_config.py +144 -0
  66. cfdbender/solvers/xfoil/_execute.py +227 -0
  67. cfdbender/solvers/xfoil/_polar.py +88 -0
  68. cfdbender/testing/__init__.py +301 -0
  69. cfdbender/workspace/__init__.py +1 -0
  70. cfdbender/workspace/cli.py +99 -0
  71. cfdbender/workspace/planning.py +38 -0
  72. cfdbender-0.4.2.dist-info/METADATA +57 -0
  73. cfdbender-0.4.2.dist-info/RECORD +77 -0
  74. cfdbender-0.4.2.dist-info/WHEEL +5 -0
  75. cfdbender-0.4.2.dist-info/entry_points.txt +3 -0
  76. cfdbender-0.4.2.dist-info/licenses/LICENSE +21 -0
  77. cfdbender-0.4.2.dist-info/top_level.txt +1 -0
@@ -0,0 +1,355 @@
1
+ """Slice a three-dimensional rotor blade into radial sections.
2
+
3
+ Convention, each choice an argument with this default:
4
+
5
+ - the rotation axis is ``x`` and thrust points along +x;
6
+ - the hub centre is the origin;
7
+ - the rotor turns counter-clockwise seen from +x looking aft (``ccw_from_front``);
8
+ - the blade is the largest connected mesh component;
9
+ - the radial direction runs from the axis to the blade centroid;
10
+ - a station is cut on the cylinder r = const, unrolled to (arc length, axial),
11
+ or on the plane normal to the radial direction (``cut="plane"``);
12
+ - the leading edge is the section point farthest ahead along the rotation
13
+ direction, the trailing edge is the section point farthest from it, and the
14
+ chord is that distance;
15
+ - beta is the angle in degrees between the chord line and the rotation plane,
16
+ positive when the leading edge sits ahead along the thrust axis (nose up into
17
+ the oncoming relative flow);
18
+ - the shape is expressed in unit-chord coordinates with x running from the
19
+ leading edge (0) to the trailing edge (1) and y positive on the thrust side,
20
+ ordered from the trailing edge over the upper side and back under the lower.
21
+
22
+ Only the standard library is used.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import math
28
+ from dataclasses import dataclass
29
+
30
+ Vec = tuple[float, float, float]
31
+ AXES: dict[str, Vec] = {"x": (1.0, 0.0, 0.0), "y": (0.0, 1.0, 0.0), "z": (0.0, 0.0, 1.0)}
32
+ SPACINGS = ("cosine", "uniform")
33
+ CUTS = ("cylinder", "plane")
34
+ ROTATIONS = ("ccw_from_front", "cw_from_front")
35
+
36
+
37
+ class BladeSliceError(ValueError):
38
+ """The blade cannot be sliced with the requested convention."""
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class BladeSection:
43
+ """One radial station: radius and chord in model units, beta in degrees."""
44
+
45
+ radius: float
46
+ chord: float
47
+ beta_deg: float
48
+ shape: tuple[tuple[float, float], ...]
49
+
50
+
51
+ def _sub(a: Vec, b: Vec) -> Vec:
52
+ return (a[0] - b[0], a[1] - b[1], a[2] - b[2])
53
+
54
+
55
+ def _dot(a: Vec, b: Vec) -> float:
56
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
57
+
58
+
59
+ def _cross(a: Vec, b: Vec) -> Vec:
60
+ return (
61
+ a[1] * b[2] - a[2] * b[1],
62
+ a[2] * b[0] - a[0] * b[2],
63
+ a[0] * b[1] - a[1] * b[0],
64
+ )
65
+
66
+
67
+ def _scale(a: Vec, k: float) -> Vec:
68
+ return (a[0] * k, a[1] * k, a[2] * k)
69
+
70
+
71
+ def parse_obj(text: str) -> tuple[list[Vec], list[tuple[int, int, int]]]:
72
+ """Read vertices and triangulated faces from Wavefront OBJ text.
73
+
74
+ Parameters
75
+ ----------
76
+ text : str
77
+ OBJ content. Only ``v`` and ``f`` records are read; polygons are fanned
78
+ into triangles and negative indices count back from the last vertex.
79
+
80
+ Returns
81
+ -------
82
+ tuple
83
+ Vertex list and zero-based triangle index triples.
84
+ """
85
+ vertices: list[Vec] = []
86
+ faces: list[tuple[int, int, int]] = []
87
+ for number, line in enumerate(text.splitlines(), 1):
88
+ parts = line.split()
89
+ if not parts:
90
+ continue
91
+ try:
92
+ if parts[0] == "v":
93
+ vertices.append((float(parts[1]), float(parts[2]), float(parts[3])))
94
+ elif parts[0] == "f":
95
+ ids = []
96
+ for token in parts[1:]:
97
+ index = int(token.split("/")[0])
98
+ ids.append(index - 1 if index > 0 else len(vertices) + index)
99
+ if len(ids) < 3 or any(not 0 <= i < len(vertices) for i in ids):
100
+ raise ValueError("face needs three valid vertex references")
101
+ faces.extend((ids[0], ids[k], ids[k + 1]) for k in range(1, len(ids) - 1))
102
+ except (ValueError, IndexError) as error:
103
+ raise BladeSliceError(f"OBJ line {number}: cannot read {line.strip()!r}") from error
104
+ return vertices, faces
105
+
106
+
107
+ def station_radii(r_min: float, r_max: float, count: int, spacing: str) -> list[float]:
108
+ """Return ``count`` cell-centred radii between the extremes, never on the ends.
109
+
110
+ Parameters
111
+ ----------
112
+ r_min, r_max : float
113
+ Inner and outer radius of the blade.
114
+ count : int
115
+ Number of stations.
116
+ spacing : str
117
+ ``"uniform"`` or ``"cosine"`` (clustered toward both ends).
118
+ """
119
+ if spacing not in SPACINGS:
120
+ raise BladeSliceError(f"spacing must be one of: {', '.join(SPACINGS)}")
121
+ if count < 1:
122
+ raise BladeSliceError("n_sections must be a positive integer")
123
+ result = []
124
+ for i in range(count):
125
+ fraction = (i + 0.5) / count
126
+ if spacing == "cosine":
127
+ fraction = 0.5 * (1.0 - math.cos(math.pi * fraction))
128
+ result.append(r_min + (r_max - r_min) * fraction)
129
+ return result
130
+
131
+
132
+ def _largest_component(faces: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
133
+ parent: dict[int, int] = {}
134
+
135
+ def find(i: int) -> int:
136
+ while parent.setdefault(i, i) != i:
137
+ parent[i] = parent[parent[i]]
138
+ i = parent[i]
139
+ return i
140
+
141
+ for face in faces:
142
+ for other in face[1:]:
143
+ parent[find(other)] = find(face[0])
144
+ groups: dict[int, list[tuple[int, int, int]]] = {}
145
+ for face in faces:
146
+ groups.setdefault(find(face[0]), []).append(face)
147
+ return max(groups.values(), key=len)
148
+
149
+
150
+ def _chains(segments: list[tuple[tuple[int, int], tuple[int, int]]]) -> list[list[tuple[int, int]]]:
151
+ adjacency: dict[tuple[int, int], list[tuple[int, int]]] = {}
152
+ for a, b in segments:
153
+ adjacency.setdefault(a, []).append(b)
154
+ adjacency.setdefault(b, []).append(a)
155
+ seen: set[tuple[int, int]] = set()
156
+ chains = []
157
+ starts = [k for k, v in adjacency.items() if len(v) == 1] + list(adjacency)
158
+ for start in starts:
159
+ if start in seen:
160
+ continue
161
+ chain = [start]
162
+ seen.add(start)
163
+ while True:
164
+ following = [n for n in adjacency[chain[-1]] if n not in seen]
165
+ if not following:
166
+ break
167
+ chain.append(following[0])
168
+ seen.add(following[0])
169
+ chains.append(chain)
170
+ return chains
171
+
172
+
173
+ def _section(points: list[tuple[float, float]], closed: bool, label: str) -> BladeSection:
174
+ leading = max(range(len(points)), key=lambda i: (points[i][0], -i))
175
+ le = points[leading]
176
+ trailing = max(range(len(points)), key=lambda i: math.dist(points[i], le))
177
+ te = points[trailing]
178
+ chord = math.dist(le, te)
179
+ if chord <= 0.0:
180
+ raise BladeSliceError(f"{label}: section has zero chord")
181
+ beta = math.degrees(math.atan2(le[1] - te[1], le[0] - te[0]))
182
+ ux, uy = (te[0] - le[0]) / chord, (te[1] - le[1]) / chord
183
+ nx, ny = -uy, ux
184
+ if ny < 0:
185
+ nx, ny = -nx, -ny
186
+ local = [
187
+ (
188
+ ((p[0] - le[0]) * ux + (p[1] - le[1]) * uy) / chord,
189
+ ((p[0] - le[0]) * nx + (p[1] - le[1]) * ny) / chord,
190
+ )
191
+ for p in points
192
+ ]
193
+ count = len(points)
194
+ if closed:
195
+ order = [(trailing + k) % count for k in range(count)] + [trailing]
196
+ else:
197
+ order = list(range(count))
198
+ split = order.index(leading)
199
+ first, second = order[: split + 1], order[split:]
200
+ if not first or not second:
201
+ raise BladeSliceError(f"{label}: cannot split the section at its leading edge")
202
+ mean_first = sum(local[i][1] for i in first) / len(first)
203
+ mean_second = sum(local[i][1] for i in second) / len(second)
204
+ if mean_first >= mean_second:
205
+ walk = first + second[1:]
206
+ else:
207
+ walk = second[::-1] + first[::-1][1:]
208
+ return BladeSection(0.0, chord, beta, tuple(local[i] for i in walk))
209
+
210
+
211
+ def radial_extent(
212
+ obj_text: str, *, axis: str = "x", hub_center: Vec = (0.0, 0.0, 0.0)
213
+ ) -> tuple[float, float]:
214
+ """Return the smallest and largest distance of the blade's vertices from the axis.
215
+
216
+ Parameters
217
+ ----------
218
+ obj_text : str
219
+ Wavefront OBJ text, as for :func:`slice_blade`.
220
+ axis : str
221
+ Rotation axis ``"x"``, ``"y"`` or ``"z"``.
222
+ hub_center : tuple of float
223
+ A point on the rotation axis.
224
+ """
225
+ if axis not in AXES:
226
+ raise BladeSliceError(f"axis must be one of: {', '.join(AXES)}")
227
+ vertices, faces = parse_obj(obj_text)
228
+ if not faces:
229
+ raise BladeSliceError("OBJ has no faces")
230
+ a = AXES[axis]
231
+ radii = []
232
+ for i in {i for face in _largest_component(faces) for i in face}:
233
+ q = _sub(vertices[i], hub_center)
234
+ radii.append(math.sqrt(max(_dot(q, q) - _dot(q, a) ** 2, 0.0)))
235
+ return min(radii), max(radii)
236
+
237
+
238
+ def slice_blade(
239
+ obj_text: str,
240
+ *,
241
+ n_sections: int,
242
+ spacing: str = "cosine",
243
+ cut: str = "cylinder",
244
+ axis: str = "x",
245
+ hub_center: Vec = (0.0, 0.0, 0.0),
246
+ rotation: str = "ccw_from_front",
247
+ ) -> tuple[BladeSection, ...]:
248
+ """Cut a blade OBJ at radial stations and measure radius, chord, beta and shape.
249
+
250
+ Parameters
251
+ ----------
252
+ obj_text : str
253
+ Wavefront OBJ text holding one blade or a mesh whose largest connected
254
+ component is the blade. Lengths stay in the model's own units.
255
+ n_sections : int
256
+ Number of stations between the root and tip radii of the blade.
257
+ spacing : str
258
+ ``"cosine"`` (default) or ``"uniform"`` station distribution.
259
+ cut : str
260
+ ``"cylinder"`` (default, unrolled) or ``"plane"``.
261
+ axis : str
262
+ Rotation axis ``"x"``, ``"y"`` or ``"z"``; thrust points along it.
263
+ hub_center : tuple of float
264
+ A point on the rotation axis.
265
+ rotation : str
266
+ ``"ccw_from_front"`` (default) or ``"cw_from_front"``.
267
+
268
+ Returns
269
+ -------
270
+ tuple of BladeSection
271
+ Sections in ascending radius.
272
+
273
+ Raises
274
+ ------
275
+ BladeSliceError
276
+ Unknown choice, empty geometry or a station whose cut has no outline.
277
+ """
278
+ for value, allowed, name in (
279
+ (spacing, SPACINGS, "spacing"),
280
+ (cut, CUTS, "cut"),
281
+ (rotation, ROTATIONS, "rotation"),
282
+ (axis, tuple(AXES), "axis"),
283
+ ):
284
+ if value not in allowed:
285
+ raise BladeSliceError(f"{name} must be one of: {', '.join(allowed)}")
286
+ if type(n_sections) is not int or n_sections < 1:
287
+ raise BladeSliceError("n_sections must be a positive integer")
288
+ vertices, all_faces = parse_obj(obj_text)
289
+ if not all_faces:
290
+ raise BladeSliceError("OBJ has no faces")
291
+ faces = _largest_component(all_faces)
292
+ used = sorted({i for face in faces for i in face})
293
+ a = AXES[axis]
294
+ local = {i: _sub(vertices[i], hub_center) for i in used}
295
+ centroid = tuple(sum(local[i][k] for i in used) / len(used) for k in range(3))
296
+ perp = _sub(centroid, _scale(a, _dot(centroid, a))) # type: ignore[arg-type]
297
+ length = math.sqrt(_dot(perp, perp))
298
+ if length < 1e-12:
299
+ raise BladeSliceError("radial direction is undefined: blade centroid lies on the axis")
300
+ e_r = _scale(perp, 1.0 / length)
301
+ e_t = _cross(a, e_r)
302
+ if rotation == "cw_from_front":
303
+ e_t = _scale(e_t, -1.0)
304
+ rho = {i: math.sqrt(max(_dot(q, q) - _dot(q, a) ** 2, 0.0)) for i, q in local.items()}
305
+ radial = {i: _dot(local[i], e_r) for i in used}
306
+ measure = rho if cut == "cylinder" else radial
307
+ sections = []
308
+ for station in station_radii(min(measure.values()), max(measure.values()), n_sections, spacing):
309
+ label = f"station r={station:.6g}"
310
+ level = {i: measure[i] - station for i in used}
311
+ points: dict[tuple[int, int], Vec] = {}
312
+ segments = []
313
+ for face in faces:
314
+ crossings = []
315
+ for p, q in ((face[0], face[1]), (face[1], face[2]), (face[2], face[0])):
316
+ if (level[p] >= 0.0) != (level[q] >= 0.0):
317
+ key = (min(p, q), max(p, q))
318
+ if key not in points:
319
+ t = level[key[0]] / (level[key[0]] - level[key[1]])
320
+ u, v = local[key[0]], local[key[1]]
321
+ points[key] = (
322
+ u[0] + t * (v[0] - u[0]),
323
+ u[1] + t * (v[1] - u[1]),
324
+ u[2] + t * (v[2] - u[2]),
325
+ )
326
+ crossings.append(key)
327
+ if len(crossings) == 2:
328
+ segments.append((crossings[0], crossings[1]))
329
+ if not segments:
330
+ raise BladeSliceError(f"{label}: the cut does not meet the blade")
331
+
332
+ flats = {
333
+ k: (
334
+ station * math.atan2(_dot(q, e_t), _dot(q, e_r))
335
+ if cut == "cylinder"
336
+ else _dot(q, e_t),
337
+ _dot(q, a),
338
+ )
339
+ for k, q in points.items()
340
+ }
341
+
342
+ def perimeter(
343
+ chain: list[tuple[int, int]], flats: dict[tuple[int, int], tuple[float, float]] = flats
344
+ ) -> float:
345
+ xy = [flats[k] for k in chain]
346
+ return sum(math.dist(xy[i], xy[i + 1]) for i in range(len(xy) - 1))
347
+
348
+ chain = max(_chains(segments), key=perimeter)
349
+ if len(chain) < 3:
350
+ raise BladeSliceError(f"{label}: the cut outline has fewer than three points")
351
+ closed = (chain[0], chain[-1]) in segments or (chain[-1], chain[0]) in segments
352
+ outline = [flats[k] for k in chain]
353
+ result = _section(outline, closed, label)
354
+ sections.append(BladeSection(station, result.chord, result.beta_deg, result.shape))
355
+ return tuple(sections)
@@ -0,0 +1,21 @@
1
+ """Plan portable HPC jobs without writing files or launching processes.
2
+
3
+ Read ``inputs/hpc/h001.toml`` with :func:`read_hpc_profile`, passing the
4
+ workspace's registered solver versions. :func:`plan_submission` prepares a
5
+ descriptor and argument list for a later executor. Translation tables declare
6
+ scheduler names; they do not verify the version installed on a cluster.
7
+ """
8
+
9
+ from ._plan import SubmissionPlan, plan_submission
10
+ from ._profiles import HpcProfile, read_hpc_profile, resolve_hpc_profile
11
+ from ._render import build_submit_command, render_descriptor
12
+
13
+ __all__ = [
14
+ "HpcProfile",
15
+ "SubmissionPlan",
16
+ "plan_submission",
17
+ "read_hpc_profile",
18
+ "resolve_hpc_profile",
19
+ "build_submit_command",
20
+ "render_descriptor",
21
+ ]
cfdbender/hpc/_plan.py ADDED
@@ -0,0 +1,266 @@
1
+ """Prepare one point or grouped job without writing or submitting anything."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from collections.abc import Mapping, Sequence
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+
11
+ from ._profiles import HpcProfile
12
+ from ._render import build_submit_command, render_descriptor
13
+ from ._walltime import BudgetGroup, BudgetRow, job_walltime, walltime_text
14
+
15
+ _WALLTIME_TEXT = re.compile(
16
+ r"\s*([-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?|[-+]?(?:nan|inf(?:inity)?))\s*([a-z]+)\s*",
17
+ re.IGNORECASE,
18
+ )
19
+ _UNITS = {"s": 1.0, "m": 60.0, "h": 3600.0, "d": 86400.0}
20
+ _UNITS_GLOSS = "s (seconds), m (minutes), h (hours), d (days)"
21
+ _LOCAL_REFUSAL = (
22
+ "a local grouped job needs a limit: state WALLTIME in its rows or timeout_s in "
23
+ "the setup, or give the HPC profile a max_walltime; it would otherwise run unbounded"
24
+ )
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class SubmissionPlan:
29
+ """The descriptor text/path, argv and budget of a job that has not been submitted.
30
+
31
+ ``walltime`` is the descriptor value (text or seconds); ``walltime_s`` is
32
+ the scheduler budget, possibly absent. ``local_time_limit_s`` gives a later
33
+ local executor its deadline when requested. ``warnings`` are returned for
34
+ the caller to print. ``fits`` and ``shortfall_s`` compare recorded estimates
35
+ with the budget; neither claims a measured runtime. ``submitted`` is false.
36
+ """
37
+
38
+ descriptor_text: str
39
+ descriptor_path: Path
40
+ command: list[str]
41
+ walltime: str | int | None
42
+ walltime_s: int | None
43
+ walltime_source: str
44
+ warnings: tuple[str, ...]
45
+ local_time_limit_s: float | None = None
46
+ fits: bool | None = None
47
+ shortfall_s: float | None = None
48
+ submitted: bool = False
49
+
50
+
51
+ def _number(value: object, key: str, row: str, *, zero: bool = False) -> float:
52
+ if isinstance(value, bool) or not isinstance(value, (str, int, float)):
53
+ raise ValueError(f"row {row}: {key} {value!r} is not a number of seconds")
54
+ try:
55
+ result = float(value)
56
+ except ValueError:
57
+ raise ValueError(f"row {row}: {key} {value!r} is not a number of seconds") from None
58
+ if not math.isfinite(result) or result < 0 or (not zero and result == 0):
59
+ raise ValueError(
60
+ f"row {row}: {key} {value!r} must be finite and {'nonnegative' if zero else 'positive'}"
61
+ )
62
+ return result
63
+
64
+
65
+ def _clock(row: str, stated: object, grouped: bool) -> tuple[float | None, str | None, bool]:
66
+ if stated is None or str(stated).strip() in ("", "-"):
67
+ return None, None, False
68
+ text = str(stated).strip()
69
+ if text.upper() == "BEST":
70
+ if not grouped:
71
+ raise ValueError(
72
+ f"row {row} states WALLTIME: {text!r}. BEST asks the package for the walltime, "
73
+ "which grouped modes (--batch or --polar-sweep) compute; write a wall clock "
74
+ "with its unit for the default mode."
75
+ )
76
+ return None, None, True
77
+ matched = _WALLTIME_TEXT.fullmatch(text)
78
+ if matched is None and not text[-1:].isalpha():
79
+ raise ValueError(
80
+ f"row {row} states WALLTIME: {text!r}, which carries no unit. Write the unit with "
81
+ "the number, as 240m or 4h: a bare number read as seconds here and as minutes "
82
+ f"on the scheduler. The units are {_UNITS_GLOSS}."
83
+ )
84
+ if matched is None:
85
+ raise ValueError(
86
+ f"row {row} states WALLTIME: {text!r}, not a number followed by {_UNITS_GLOSS}"
87
+ )
88
+ number, unit = matched.group(1), matched.group(2).lower()
89
+ if unit not in _UNITS:
90
+ raise ValueError(
91
+ f"row {row} states WALLTIME: {text!r}; unit {unit!r} is not one of {_UNITS_GLOSS}"
92
+ )
93
+ return _number(number, "WALLTIME", row) * _UNITS[unit], text, False
94
+
95
+
96
+ def _budget(points: Sequence[Mapping[str, object]], grouped: bool) -> BudgetGroup:
97
+ by_row: dict[str, list[Mapping[str, object]]] = {}
98
+ for point in points:
99
+ row = str(point.get("row_id") or point.get("sim") or "?")
100
+ by_row.setdefault(row, []).append(point)
101
+ units = []
102
+ for row, members in by_row.items():
103
+ first = members[0]
104
+ cell, written, best = _clock(row, first.get("walltime"), grouped)
105
+ if any(member.get("walltime") != first.get("walltime") for member in members):
106
+ raise ValueError(f"row {row} has inconsistent WALLTIME values among its points")
107
+ estimates = tuple(
108
+ _number(p["estimate_s"], "estimate_s", row, zero=True)
109
+ if p.get("estimate_s") is not None
110
+ else None
111
+ for p in members
112
+ )
113
+ margins = [_number(p.get("margin_s", 1200), "margin_s", row, zero=True) for p in members]
114
+ timeouts = [
115
+ _number(p["timeout_s"], "timeout_s", row)
116
+ for p in members
117
+ if p.get("timeout_s") is not None
118
+ ]
119
+ units.append(
120
+ BudgetRow(
121
+ sim_id=row,
122
+ run_ids=tuple(
123
+ str(p.get("run_id") or f"{row}/{p.get('point', '?')}") for p in members
124
+ ),
125
+ point_seconds=estimates,
126
+ walltime_cell_s=cell,
127
+ walltime_cell_text=written,
128
+ best=best,
129
+ margin_s=max(margins),
130
+ timeout_s=max(timeouts) if timeouts else None,
131
+ )
132
+ )
133
+ return BudgetGroup(tuple(units))
134
+
135
+
136
+ def plan_submission(
137
+ points: Sequence[Mapping[str, object]],
138
+ profile: HpcProfile,
139
+ *,
140
+ workdir: str | Path | None = None,
141
+ job_name: str | None = None,
142
+ grouped: bool | None = None,
143
+ local: bool = False,
144
+ estimate_s: float | None = None,
145
+ ) -> SubmissionPlan:
146
+ """Plan one job using only profile declarations and resolved point values.
147
+
148
+ Parameters
149
+ ----------
150
+ points : sequence of mappings
151
+ Each mapping supplies ``row_id``, ``point``, ``solver_version``, ``ncpus``,
152
+ ``workdir`` and ``config_path`` (or ``script_path`` for a prepared group
153
+ launcher). Other descriptor values such as ``solver_type`` and ``cluster``
154
+ are optional unless the template asks for them. ``walltime`` is a row cell
155
+ with s/m/h/d units or BEST. Optional ``estimate_s`` prices a point;
156
+ ``margin_s`` defaults to 1200 and ``timeout_s`` bounds a local point.
157
+ All points in one job must name the same solver version and CPU count.
158
+ profile : HpcProfile
159
+ Descriptor template, version mappings, command and maximum budget.
160
+ workdir : str or Path, optional
161
+ Job folder; defaults to the first point's folder. Supply it for a group
162
+ that runs in a separate folder. No directory is created.
163
+ job_name : str, optional
164
+ Scheduler job name. Defaults to the first row and point joined by '_'.
165
+ grouped : bool, optional
166
+ Defaults to True for multiple points. Set True for a one-point grouped
167
+ plan that may use BEST. This function accepts an already selected group;
168
+ it does not split jobs or construct a solver launcher.
169
+ local : bool, optional
170
+ Compute the deadline a later forced-local executor must enforce.
171
+ estimate_s : float, optional
172
+ Group estimate including caller-measured overheads. Otherwise sum point
173
+ estimates, using cell budgets for gaps. No solver's measured overheads
174
+ are assumed by this solver-independent layer.
175
+
176
+ Returns
177
+ -------
178
+ SubmissionPlan
179
+ Descriptor text and planned path, argv, walltime, and warnings. Nothing
180
+ is written, launched, submitted or printed.
181
+
182
+ Raises
183
+ ------
184
+ ValueError
185
+ Empty or incompatible points, invalid budgets, a row above the maximum,
186
+ an unbounded local group, or an unresolved template value.
187
+ """
188
+ if not points:
189
+ raise ValueError("cannot plan a submission with no points")
190
+ first = points[0]
191
+ for key in ("solver_version", "ncpus"):
192
+ if any(p.get(key) != first.get(key) for p in points):
193
+ raise ValueError(f"a grouped job holds one {key}; the points name different values")
194
+ is_group = len(points) > 1 if grouped is None else grouped
195
+ if len(points) > 1 and not is_group:
196
+ raise ValueError("multiple points require a grouped job")
197
+ group = _budget(points, is_group)
198
+ maximum = profile.max_walltime_s
199
+ if estimate_s is not None:
200
+ estimate_s = _number(estimate_s, "estimate_s", "job", zero=True)
201
+ else:
202
+ costs = [
203
+ s if s is not None else row.walltime_cell_s
204
+ for row in group.units
205
+ for s in row.point_seconds
206
+ ]
207
+ estimate_s = (
208
+ sum(s for s in costs if s is not None) if all(s is not None for s in costs) else None
209
+ )
210
+ seconds, source, fits, shortfall, warnings, refusal = job_walltime(
211
+ group, estimate_s, max_walltime_s=maximum
212
+ )
213
+ if refusal is not None:
214
+ raise ValueError(refusal)
215
+ local_limit = float(seconds) if local and seconds is not None else None
216
+ if local and seconds is None:
217
+ limits = [row.timeout_s for row in group.units if row.timeout_s is not None]
218
+ if limits:
219
+ local_limit = max(limits) * len(points)
220
+ warnings.append(
221
+ f"run on this machine (--local), its time limit is {local_limit:g} s: "
222
+ "no WALLTIME, so the largest solver timeout_s for each point"
223
+ )
224
+ elif maximum:
225
+ seconds, source, local_limit = int(maximum), "max_walltime", float(maximum)
226
+ warnings.append(
227
+ "no WALLTIME and no timeout_s, so the local job takes the profile's "
228
+ f"walltime of {walltime_text(seconds)}."
229
+ )
230
+ else:
231
+ raise ValueError(_LOCAL_REFUSAL)
232
+ values = {k: v for k, v in first.items() if v is not None and v != ""}
233
+ folder = workdir if workdir is not None else first.get("workdir", first.get("work_dir"))
234
+ if folder is None or str(folder).strip() == "":
235
+ raise ValueError("this job cannot supply workdir")
236
+ path = Path(str(folder)) / profile.descriptor_name
237
+ row_ids = list(dict.fromkeys(row.sim_id for row in group.units))
238
+ values.update(
239
+ workdir=Path(str(folder)).as_posix(),
240
+ work_dir=Path(str(folder)).as_posix(),
241
+ descriptor_path=path.as_posix(),
242
+ sim=row_ids[0],
243
+ first_sim=row_ids[0],
244
+ last_sim=row_ids[-1],
245
+ sims=",".join(row_ids),
246
+ )
247
+ name = job_name or first.get("job_name") or f"{row_ids[0]}_{first.get('point', row_ids[0])}"
248
+ values["job_name"] = name
249
+ values["config_paths"] = ",".join(str(p["config_path"]) for p in points if p.get("config_path"))
250
+ wall: str | int | None = None
251
+ if seconds is not None:
252
+ written = (
253
+ group.units[0].walltime_cell_text
254
+ if not is_group and source == "matrix"
255
+ else walltime_text(seconds)
256
+ )
257
+ wall = seconds if profile.walltime_arithmetic == "seconds" else written
258
+ values.update(walltime=wall, walltime_s=seconds, walltime_written=written)
259
+ else:
260
+ # A raw row's absent wall clock must not format as None or inherit another point's.
261
+ values.pop("walltime", None)
262
+ command = build_submit_command(profile, values, path)
263
+ text = render_descriptor(profile, values)
264
+ return SubmissionPlan(
265
+ text, path, command, wall, seconds, source, tuple(warnings), local_limit, fits, shortfall
266
+ )