stacknordic 0.1.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.
@@ -0,0 +1,561 @@
1
+ """Concurrent OpenFOAM time reconstruction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ import tempfile
10
+ from collections.abc import Sequence
11
+ from concurrent.futures import ThreadPoolExecutor, as_completed
12
+ from contextlib import contextmanager
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+ from time import perf_counter
16
+
17
+ from ._progress import finish_progress, start_progress
18
+ from .openfoam.environment import _Toolchain, toolchain
19
+ from .resources import workers as _workers
20
+ from .selection import TimeSelection
21
+ from .selection import select_times as _select_times
22
+
23
+ _PROCESSOR = re.compile(r"processor(\d+)$")
24
+ _PROCESSORS = re.compile(r"processors(\d+)(?:_(\d+)-(\d+))?$")
25
+ _VERSION = re.compile(rb"\bVersion\s*:\s*([A-Za-z0-9_.+-]+)")
26
+ _BOUNDARY_COUNT = re.compile(r"\b(\d+)\s*\(")
27
+
28
+
29
+ @dataclass(frozen=True, slots=True)
30
+ class _Layout:
31
+ case_dir: Path
32
+ processors: tuple[Path, ...]
33
+ processor_count: int
34
+ collated: bool
35
+ time_names: dict[float, str]
36
+ partial_times: tuple[float, ...]
37
+ source_family: str
38
+ source_versions: tuple[str, ...]
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class _Runtime:
43
+ family: str
44
+ version: str
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class Reconstruction:
49
+ """Summary of one reconstruction request."""
50
+
51
+ case_dir: Path
52
+ output_dir: Path
53
+ processor_count: int
54
+ reconstructed_times: tuple[float, ...]
55
+ skipped_times: tuple[float, ...]
56
+ fields: tuple[str, ...] | None
57
+ source_family: str
58
+ source_versions: tuple[str, ...]
59
+ runtime_family: str
60
+ runtime_version: str
61
+ n_jobs: int
62
+ elapsed_seconds: float
63
+
64
+
65
+ def _numeric_directories(directory: Path) -> dict[float, str]:
66
+ result: dict[float, str] = {}
67
+ for path in directory.iterdir():
68
+ if not path.is_dir():
69
+ continue
70
+ try:
71
+ value = float(path.name)
72
+ except ValueError:
73
+ continue
74
+ if not math.isfinite(value):
75
+ continue
76
+ if value in result and result[value] != path.name:
77
+ raise ValueError(
78
+ f"OpenFOAM directory {directory} contains duplicate physical time {value:g}"
79
+ )
80
+ result[value] = path.name
81
+ return result
82
+
83
+
84
+ def _processor_directories(case_dir: Path) -> tuple[tuple[Path, ...], int, bool]:
85
+ indexed = []
86
+ collated: dict[int, list[tuple[int, int, Path]]] = {}
87
+ for path in case_dir.iterdir():
88
+ match = _PROCESSOR.fullmatch(path.name)
89
+ if path.is_dir() and match is not None:
90
+ indexed.append((int(match.group(1)), path))
91
+ continue
92
+ grouped = _PROCESSORS.fullmatch(path.name)
93
+ if path.is_dir() and grouped is not None:
94
+ total = int(grouped.group(1))
95
+ first = int(grouped.group(2) or 0)
96
+ last = int(grouped.group(3) or total - 1)
97
+ collated.setdefault(total, []).append((first, last, path))
98
+ if indexed and collated:
99
+ raise ValueError("case contains both processorN and collated processorsN layouts")
100
+ if collated:
101
+ if len(collated) != 1:
102
+ raise ValueError("case contains more than one collated processor count")
103
+ total, ranges = next(iter(collated.items()))
104
+ ranges.sort()
105
+ expected = 0
106
+ for first, last, _ in ranges:
107
+ if first != expected or last < first:
108
+ raise ValueError("collated processor ranges are incomplete or overlap")
109
+ expected = last + 1
110
+ if expected != total:
111
+ raise ValueError("collated processor ranges do not cover their declared count")
112
+ return tuple(path for _, _, path in ranges), total, True
113
+ indexed.sort()
114
+ indices = [index for index, _ in indexed]
115
+ if not indices:
116
+ raise FileNotFoundError(f"No processor directories were found in {case_dir}")
117
+ if indices != list(range(len(indices))):
118
+ raise ValueError("processor directories must be consecutively numbered from processor0")
119
+ return tuple(path for _, path in indexed), len(indexed), False
120
+
121
+
122
+ def _source_identity(case_dir: Path, processors: tuple[Path, ...]) -> tuple[str, tuple[str, ...]]:
123
+ candidates = [case_dir / "system/controlDict"]
124
+ for field in ("U", "p", "T"):
125
+ candidates.append(processors[0] / "0" / field)
126
+ payloads = [path.read_bytes()[:8192] for path in candidates if path.is_file()]
127
+ joined = b"\n".join(payloads).lower()
128
+ if b"openfoam.org" in joined or b"openfoam foundation" in joined:
129
+ family = "foundation"
130
+ elif b"openfoam.com" in joined:
131
+ family = "esi"
132
+ else:
133
+ family = "unknown"
134
+ versions = {
135
+ match.group(1).decode("ascii", errors="replace").strip()
136
+ for payload in payloads
137
+ for match in _VERSION.finditer(payload)
138
+ }
139
+ return family, tuple(sorted(versions))
140
+
141
+
142
+ def _inspect(case_dir: str | Path) -> _Layout:
143
+ selected = Path(case_dir).expanduser().resolve()
144
+ if not selected.is_dir():
145
+ raise FileNotFoundError(f"OpenFOAM case directory does not exist: {selected}")
146
+ for required in (selected / "system/controlDict", selected / "constant"):
147
+ if not required.exists():
148
+ raise FileNotFoundError(f"OpenFOAM case entry is missing: {required}")
149
+ processors, processor_count, collated = _processor_directories(selected)
150
+ rank_times = [_numeric_directories(processor) for processor in processors]
151
+ common = set(rank_times[0])
152
+ union = set(rank_times[0])
153
+ for values in rank_times[1:]:
154
+ common.intersection_update(values)
155
+ union.update(values)
156
+ if not common:
157
+ raise ValueError("processor directories have no common physical times")
158
+ names = {}
159
+ for physical_time in sorted(common):
160
+ rank_names = {values[physical_time] for values in rank_times}
161
+ if len(rank_names) != 1:
162
+ raise ValueError(
163
+ f"processor directories use inconsistent names for time {physical_time:g}"
164
+ )
165
+ names[physical_time] = rank_names.pop()
166
+ family, versions = _source_identity(selected, processors)
167
+ return _Layout(
168
+ case_dir=selected,
169
+ processors=processors,
170
+ processor_count=processor_count,
171
+ collated=collated,
172
+ time_names=names,
173
+ partial_times=tuple(sorted(union.difference(common))),
174
+ source_family=family,
175
+ source_versions=versions,
176
+ )
177
+
178
+
179
+ def _normalise_fields(fields: Sequence[str] | None) -> tuple[str, ...] | None:
180
+ if fields is None:
181
+ return None
182
+ selected = tuple(fields)
183
+ if not selected:
184
+ raise ValueError("fields must contain at least one field name")
185
+ for field in selected:
186
+ if not field or Path(field).name != field:
187
+ raise ValueError("each field must be one non-empty path component")
188
+ if len(set(selected)) != len(selected):
189
+ raise ValueError("fields must not contain duplicates")
190
+ return selected
191
+
192
+
193
+ def _command(
194
+ case_dir: Path,
195
+ time_name: str,
196
+ fields: tuple[str, ...] | None,
197
+ runtime: _Toolchain,
198
+ collated: bool,
199
+ ) -> tuple[str, ...]:
200
+ command = ["reconstructPar", "-case", str(case_dir), "-time", time_name]
201
+ if collated:
202
+ command.extend(("-fileHandler", "collated"))
203
+ if fields is not None:
204
+ command.extend(("-fields", f"({' '.join(fields)})"))
205
+ return runtime.wrap(tuple(command))
206
+
207
+
208
+ def _control_value(payload: str, name: str, default: str) -> str:
209
+ match = re.search(rf"(?m)^\s*{re.escape(name)}\s+([^;]+);", payload)
210
+ return match.group(1).strip() if match is not None else default
211
+
212
+
213
+ def _minimal_control_dict(source: Path) -> str:
214
+ payload = source.read_text(encoding="utf-8", errors="replace")
215
+ values = {
216
+ "writeFormat": _control_value(payload, "writeFormat", "ascii"),
217
+ "writePrecision": _control_value(payload, "writePrecision", "12"),
218
+ "writeCompression": _control_value(payload, "writeCompression", "off"),
219
+ "timeFormat": _control_value(payload, "timeFormat", "general"),
220
+ "timePrecision": _control_value(payload, "timePrecision", "12"),
221
+ }
222
+ return (
223
+ "FoamFile\n"
224
+ "{\n"
225
+ " format ascii;\n"
226
+ " class dictionary;\n"
227
+ " location \"system\";\n"
228
+ " object controlDict;\n"
229
+ "}\n\n"
230
+ "application reconstructPar;\n"
231
+ "startFrom latestTime;\n"
232
+ "startTime 0;\n"
233
+ "stopAt endTime;\n"
234
+ "endTime 1;\n"
235
+ "deltaT 1;\n"
236
+ "writeControl timeStep;\n"
237
+ "writeInterval 1;\n"
238
+ f"writeFormat {values['writeFormat']};\n"
239
+ f"writePrecision {values['writePrecision']};\n"
240
+ f"writeCompression {values['writeCompression']};\n"
241
+ f"timeFormat {values['timeFormat']};\n"
242
+ f"timePrecision {values['timePrecision']};\n"
243
+ "runTimeModifiable false;\n"
244
+ "functions {};\n"
245
+ )
246
+
247
+
248
+ def _matching_brace(payload: str, start: int) -> int:
249
+ depth = 0
250
+ for index in range(start, len(payload)):
251
+ if payload[index] == "{":
252
+ depth += 1
253
+ elif payload[index] == "}":
254
+ depth -= 1
255
+ if depth == 0:
256
+ return index
257
+ raise ValueError("unterminated OpenFOAM dictionary block")
258
+
259
+
260
+ def _boundary_patches(path: Path) -> tuple[tuple[str, str], ...]:
261
+ payload = path.read_text(encoding="utf-8", errors="strict")
262
+ payload = re.sub(r"/\*.*?\*/", "", payload, flags=re.DOTALL)
263
+ payload = re.sub(r"//[^\r\n]*", "", payload)
264
+ count_match = _BOUNDARY_COUNT.search(payload)
265
+ if count_match is None:
266
+ raise ValueError(f"cannot read boundary patch count from {path}")
267
+ count = int(count_match.group(1))
268
+ cursor = count_match.end()
269
+ patches: list[tuple[str, str]] = []
270
+ name_pattern = re.compile(r"\s*([^\s{}();]+)\s*\{")
271
+ while len(patches) < count:
272
+ name_match = name_pattern.match(payload, cursor)
273
+ if name_match is None:
274
+ raise ValueError(f"cannot read boundary patch {len(patches)} from {path}")
275
+ start = payload.find("{", name_match.start())
276
+ end = _matching_brace(payload, start)
277
+ body = payload[start + 1 : end]
278
+ type_match = re.search(r"(?m)^\s*type\s+([^;]+);", body)
279
+ if type_match is None:
280
+ raise ValueError(f"boundary patch {name_match.group(1)} has no type in {path}")
281
+ patches.append((name_match.group(1), type_match.group(1).strip()))
282
+ cursor = end + 1
283
+ return tuple(patches)
284
+
285
+
286
+ def _write_boundary_addressing(source_case: Path, processor: Path, destination: Path) -> None:
287
+ root_patches = _boundary_patches(source_case / "constant/polyMesh/boundary")
288
+ root_indices = {name: index for index, (name, _) in enumerate(root_patches)}
289
+ processor_patches = _boundary_patches(processor / "constant/polyMesh/boundary")
290
+ addressing = []
291
+ for name, patch_type in processor_patches:
292
+ if patch_type.startswith("processor"):
293
+ addressing.append(-1)
294
+ elif name in root_indices:
295
+ addressing.append(root_indices[name])
296
+ else:
297
+ raise ValueError(f"processor boundary patch {name!r} has no root-mesh match")
298
+ values = "\n".join(str(value) for value in addressing)
299
+ destination.write_text(
300
+ "FoamFile\n"
301
+ "{\n"
302
+ " format ascii;\n"
303
+ " class labelList;\n"
304
+ " location \"constant/polyMesh\";\n"
305
+ " object boundaryProcAddressing;\n"
306
+ "}\n\n"
307
+ f"{len(addressing)}\n(\n{values}\n)\n",
308
+ encoding="utf-8",
309
+ )
310
+
311
+
312
+ def _link_processor_view(
313
+ source_case: Path,
314
+ processor: Path,
315
+ destination: Path,
316
+ runtime_family: str,
317
+ ) -> None:
318
+ destination.mkdir()
319
+ for entry in processor.iterdir():
320
+ if entry.name != "constant":
321
+ (destination / entry.name).symlink_to(entry, target_is_directory=entry.is_dir())
322
+ source_constant = processor / "constant"
323
+ destination_constant = destination / "constant"
324
+ destination_constant.mkdir()
325
+ for entry in source_constant.iterdir():
326
+ if entry.name != "polyMesh":
327
+ (destination_constant / entry.name).symlink_to(
328
+ entry,
329
+ target_is_directory=entry.is_dir(),
330
+ )
331
+ source_mesh = source_constant / "polyMesh"
332
+ destination_mesh = destination_constant / "polyMesh"
333
+ destination_mesh.mkdir()
334
+ for entry in source_mesh.iterdir():
335
+ if entry.name != "boundaryProcAddressing":
336
+ (destination_mesh / entry.name).symlink_to(
337
+ entry,
338
+ target_is_directory=entry.is_dir(),
339
+ )
340
+ source_addressing = source_mesh / "boundaryProcAddressing"
341
+ destination_addressing = destination_mesh / "boundaryProcAddressing"
342
+ if source_addressing.is_file():
343
+ destination_addressing.symlink_to(source_addressing)
344
+ elif runtime_family == "esi":
345
+ _write_boundary_addressing(source_case, processor, destination_addressing)
346
+
347
+
348
+ @contextmanager
349
+ def _staging_case(case_dir: Path, staging_parent: Path, runtime_family: str):
350
+ stage = Path(tempfile.mkdtemp(prefix=".stacknordic-reconstruct-", dir=staging_parent))
351
+ try:
352
+ (stage / "system").mkdir()
353
+ for entry in (case_dir / "system").iterdir():
354
+ if entry.name != "controlDict":
355
+ (stage / "system" / entry.name).symlink_to(
356
+ entry,
357
+ target_is_directory=entry.is_dir(),
358
+ )
359
+ (stage / "system" / "controlDict").write_text(
360
+ _minimal_control_dict(case_dir / "system" / "controlDict"),
361
+ encoding="utf-8",
362
+ )
363
+ (stage / "constant").symlink_to(case_dir / "constant", target_is_directory=True)
364
+ processors, _, collated = _processor_directories(case_dir)
365
+ for processor in processors:
366
+ if collated:
367
+ (stage / processor.name).symlink_to(processor, target_is_directory=True)
368
+ else:
369
+ _link_processor_view(
370
+ case_dir,
371
+ processor,
372
+ stage / processor.name,
373
+ runtime_family,
374
+ )
375
+ yield stage
376
+ finally:
377
+ shutil.rmtree(stage, ignore_errors=True)
378
+
379
+
380
+ def _execute(command: tuple[str, ...]) -> subprocess.CompletedProcess[str]:
381
+ return subprocess.run(
382
+ command,
383
+ check=False,
384
+ stdout=subprocess.PIPE,
385
+ stderr=subprocess.STDOUT,
386
+ text=True,
387
+ )
388
+
389
+
390
+ def _runtime_identity(toolchain: _Toolchain) -> _Runtime:
391
+ command = toolchain.wrap(("reconstructPar", "-help"))
392
+ try:
393
+ result = _execute(command)
394
+ except OSError as error:
395
+ raise RuntimeError(f"OpenFOAM runtime preflight failed: {error}") from error
396
+ if result.returncode != 0:
397
+ detail = result.stdout.strip().splitlines()
398
+ tail = "\n".join(detail[-20:]) if detail else "reconstructPar is unavailable"
399
+ raise RuntimeError(f"OpenFOAM runtime preflight failed:\n{tail}")
400
+ lowered = result.stdout.lower()
401
+ if "openfoam.com" in lowered:
402
+ family = "esi"
403
+ elif "openfoam.org" in lowered or "openfoam foundation" in lowered:
404
+ family = "foundation"
405
+ else:
406
+ family = "unknown"
407
+ versions = _VERSION.findall(result.stdout.encode())
408
+ if versions:
409
+ version = versions[-1].decode("ascii", errors="replace")
410
+ else:
411
+ match = re.search(
412
+ r"\bOpenFOAM(?: Foundation version|-)[ ]?v?(\d+(?:\.\d+)*)",
413
+ result.stdout,
414
+ re.IGNORECASE,
415
+ )
416
+ version = match.group(1) if match is not None else "unknown"
417
+ return _Runtime(family=family, version=version)
418
+
419
+
420
+ def _reconstruct_one(
421
+ case_dir: Path,
422
+ output_dir: Path,
423
+ runtime_family: str,
424
+ physical_time: float,
425
+ time_name: str,
426
+ fields: tuple[str, ...] | None,
427
+ toolchain: _Toolchain,
428
+ collated: bool,
429
+ ) -> float:
430
+ target = output_dir / time_name
431
+ with _staging_case(case_dir, output_dir.parent, runtime_family) as stage:
432
+ result = _execute(_command(stage, time_name, fields, toolchain, collated))
433
+ staged_target = stage / time_name
434
+ if result.returncode != 0:
435
+ detail = result.stdout.strip().splitlines()
436
+ tail = "\n".join(detail[-20:]) if detail else "reconstructPar failed without output"
437
+ raise RuntimeError(f"reconstructPar failed at time {time_name}:\n{tail}")
438
+ if not staged_target.is_dir():
439
+ raise RuntimeError(f"reconstructPar completed without producing time {time_name}")
440
+ if target.exists():
441
+ raise FileExistsError(f"reconstructed time already exists: {target}")
442
+ staged_target.replace(target)
443
+ return physical_time
444
+
445
+
446
+ def reconstruct(
447
+ *,
448
+ case_dir: str | Path,
449
+ output_dir: str | Path | None = None,
450
+ times: TimeSelection = None,
451
+ fields: Sequence[str] | None = None,
452
+ n_jobs: int | None = None,
453
+ progress: bool = False,
454
+ _toolchain_override: _Toolchain | None = None,
455
+ ) -> Reconstruction:
456
+ """Reconstruct complete processor times with the configured OpenFOAM runtime."""
457
+
458
+ if not isinstance(progress, bool):
459
+ raise TypeError("progress must be a boolean")
460
+ layout = _inspect(case_dir)
461
+ destination = (
462
+ layout.case_dir
463
+ if output_dir is None
464
+ else Path(output_dir).expanduser().resolve()
465
+ )
466
+ if destination.exists() and not destination.is_dir():
467
+ raise NotADirectoryError(f"reconstruction output is not a directory: {destination}")
468
+ destination.mkdir(parents=True, exist_ok=True)
469
+ selected_fields = _normalise_fields(fields)
470
+ selected_times = _select_times(tuple(layout.time_names), times)
471
+ root_times = _numeric_directories(destination)
472
+ pending = tuple(value for value in selected_times if value not in root_times)
473
+ skipped = tuple(value for value in selected_times if value in root_times)
474
+ workers = _workers(n_jobs, len(pending)) if pending else 0
475
+ selected_toolchain = _toolchain_override or toolchain()
476
+ runtime = (
477
+ _runtime_identity(selected_toolchain)
478
+ if pending
479
+ else _Runtime("unknown", "unknown")
480
+ )
481
+ if pending and runtime.family == "unknown":
482
+ print(
483
+ "[StackNordic] Warning: reconstructPar is available, but its OpenFOAM "
484
+ "distribution could not be identified."
485
+ )
486
+ if (
487
+ pending
488
+ and layout.source_family != "unknown"
489
+ and runtime.family != "unknown"
490
+ and layout.source_family != runtime.family
491
+ ):
492
+ source_versions = ", ".join(layout.source_versions) or "unknown"
493
+ print(
494
+ f"[StackNordic] Warning: source case uses {layout.source_family} OpenFOAM "
495
+ f"{source_versions}; reconstruction uses {runtime.family} OpenFOAM "
496
+ f"{runtime.version}."
497
+ )
498
+ if layout.partial_times:
499
+ values = ", ".join(f"{value:g}" for value in layout.partial_times)
500
+ print(f"[StackNordic] Skipping incomplete processor times: {values}.")
501
+ started = perf_counter()
502
+ completed: list[float] = []
503
+ reporter = (
504
+ start_progress(len(pending), "StackNordic reconstruction")
505
+ if progress and pending
506
+ else None
507
+ )
508
+ try:
509
+ if workers == 1:
510
+ for physical_time in pending:
511
+ completed.append(
512
+ _reconstruct_one(
513
+ layout.case_dir,
514
+ destination,
515
+ runtime.family,
516
+ physical_time,
517
+ layout.time_names[physical_time],
518
+ selected_fields,
519
+ selected_toolchain,
520
+ layout.collated,
521
+ )
522
+ )
523
+ if reporter is not None:
524
+ reporter.update()
525
+ elif workers > 1:
526
+ with ThreadPoolExecutor(max_workers=workers) as executor:
527
+ futures = {
528
+ executor.submit(
529
+ _reconstruct_one,
530
+ layout.case_dir,
531
+ destination,
532
+ runtime.family,
533
+ physical_time,
534
+ layout.time_names[physical_time],
535
+ selected_fields,
536
+ selected_toolchain,
537
+ layout.collated,
538
+ ): physical_time
539
+ for physical_time in pending
540
+ }
541
+ for future in as_completed(futures):
542
+ completed.append(future.result())
543
+ if reporter is not None:
544
+ reporter.update()
545
+ finally:
546
+ if reporter is not None:
547
+ finish_progress(reporter)
548
+ return Reconstruction(
549
+ case_dir=layout.case_dir,
550
+ output_dir=destination,
551
+ processor_count=layout.processor_count,
552
+ reconstructed_times=tuple(sorted(completed)),
553
+ skipped_times=skipped,
554
+ fields=selected_fields,
555
+ source_family=layout.source_family,
556
+ source_versions=layout.source_versions,
557
+ runtime_family=runtime.family,
558
+ runtime_version=runtime.version,
559
+ n_jobs=workers,
560
+ elapsed_seconds=perf_counter() - started,
561
+ )
@@ -0,0 +1,88 @@
1
+ """Shared local execution-resource policy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+
9
+ def available_cpus() -> int:
10
+ """Return the smallest CPU allowance visible to the current process."""
11
+
12
+ limits = [os.cpu_count() or 1]
13
+ try:
14
+ limits.append(len(os.sched_getaffinity(0)))
15
+ except AttributeError:
16
+ pass
17
+ for name in ("SLURM_CPUS_PER_TASK", "SLURM_CPUS_ON_NODE"):
18
+ try:
19
+ value = int(os.environ.get(name, ""))
20
+ except ValueError:
21
+ continue
22
+ if value > 0:
23
+ limits.append(value)
24
+ return max(1, min(limits))
25
+
26
+
27
+ def workers(n_jobs: int | None, work_count: int) -> int:
28
+ """Resolve a requested worker count against available independent work."""
29
+
30
+ if n_jobs is None:
31
+ return 1
32
+ if isinstance(n_jobs, bool) or not isinstance(n_jobs, int) or n_jobs == 0 or n_jobs < -1:
33
+ raise ValueError("n_jobs must be -1, a positive integer, or None")
34
+ if n_jobs == -1:
35
+ return min(work_count, available_cpus())
36
+ return min(work_count, n_jobs)
37
+
38
+
39
+ def available_memory() -> int | None:
40
+ """Return the smallest observable process or host memory allowance."""
41
+
42
+ limits: list[int] = []
43
+ paths = [
44
+ Path("/sys/fs/cgroup/memory.max"),
45
+ Path("/sys/fs/cgroup/memory/memory.limit_in_bytes"),
46
+ ]
47
+ try:
48
+ for line in Path("/proc/self/cgroup").read_text().splitlines():
49
+ hierarchy, controllers, relative = line.split(":", 2)
50
+ if hierarchy == "0" and not controllers:
51
+ current = Path("/sys/fs/cgroup") / relative.lstrip("/")
52
+ while True:
53
+ paths.insert(0, current / "memory.max")
54
+ if current == Path("/sys/fs/cgroup"):
55
+ break
56
+ current = current.parent
57
+ break
58
+ except (FileNotFoundError, PermissionError, ValueError):
59
+ pass
60
+ for path in paths:
61
+ try:
62
+ value = path.read_text().strip()
63
+ if value != "max":
64
+ limits.append(int(value))
65
+ except (FileNotFoundError, PermissionError, ValueError):
66
+ continue
67
+ try:
68
+ limits.append(int(os.sysconf("SC_AVPHYS_PAGES") * os.sysconf("SC_PAGE_SIZE")))
69
+ except (AttributeError, OSError, ValueError):
70
+ pass
71
+ return min(limits) if limits else None
72
+
73
+
74
+ def memory_bounded_workers(
75
+ n_jobs: int | None,
76
+ work_count: int,
77
+ estimated_worker_bytes: int,
78
+ ) -> int:
79
+ """Resolve workers and constrain automatic execution by available memory."""
80
+
81
+ selected = workers(n_jobs, work_count)
82
+ if n_jobs != -1:
83
+ return selected
84
+ available = available_memory()
85
+ if available is None:
86
+ return selected
87
+ safe = max(1, int(available * 0.70) // max(estimated_worker_bytes, 1))
88
+ return min(selected, safe)
@@ -0,0 +1,52 @@
1
+ """Shared physical-time selection policy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+
7
+ TimeSelection = list[float] | tuple[float, float] | None
8
+
9
+
10
+ def select_times(available: tuple[float, ...], times: TimeSelection) -> tuple[float, ...]:
11
+ """Select all times, an inclusive tuple range, or exact list members."""
12
+
13
+ if times is None:
14
+ return available
15
+ if isinstance(times, tuple):
16
+ if len(times) != 2:
17
+ raise ValueError("a time range must be a two-value tuple")
18
+ requested = tuple(float(value) for value in times)
19
+ start, end = requested
20
+ if not all(math.isfinite(value) for value in requested):
21
+ raise ValueError("times must contain finite physical times")
22
+ if start > end:
23
+ raise ValueError("time range start must not exceed its end")
24
+ selected = tuple(value for value in available if start <= value <= end)
25
+ elif isinstance(times, list):
26
+ requested = tuple(float(value) for value in times)
27
+ if not requested or any(not math.isfinite(value) for value in requested):
28
+ raise ValueError("times must contain finite physical times")
29
+ selected = tuple(
30
+ value
31
+ for value in available
32
+ if any(
33
+ math.isclose(value, item, rel_tol=1.0e-12, abs_tol=1.0e-14)
34
+ for item in requested
35
+ )
36
+ )
37
+ missing = [
38
+ item
39
+ for item in requested
40
+ if not any(
41
+ math.isclose(value, item, rel_tol=1.0e-12, abs_tol=1.0e-14)
42
+ for value in available
43
+ )
44
+ ]
45
+ if missing:
46
+ values = ", ".join(f"{value:g}" for value in missing)
47
+ raise KeyError(f"requested times are incomplete or unavailable: {values}")
48
+ else:
49
+ raise TypeError("times must be None, an exact list, or a two-value range tuple")
50
+ if not selected:
51
+ raise ValueError("times selected no complete processor results")
52
+ return selected