arrayprobe 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.
Files changed (189) hide show
  1. arrayprobe/__init__.py +219 -0
  2. arrayprobe/__main__.py +19 -0
  3. arrayprobe/_v314_lazy.py +48 -0
  4. arrayprobe/ai_ready.py +212 -0
  5. arrayprobe/attributed_export.py +1333 -0
  6. arrayprobe/authordefaults.py +267 -0
  7. arrayprobe/cli.py +3510 -0
  8. arrayprobe/combine.py +12 -0
  9. arrayprobe/compare.py +950 -0
  10. arrayprobe/config.py +1239 -0
  11. arrayprobe/constants.py +12 -0
  12. arrayprobe/count_closure.py +204 -0
  13. arrayprobe/diagnostic_views.py +769 -0
  14. arrayprobe/diode_report.py +265 -0
  15. arrayprobe/driver/__init__.py +5 -0
  16. arrayprobe/driver/_load_record.py +331 -0
  17. arrayprobe/driver/preflight_inputs.py +250 -0
  18. arrayprobe/driver/reprocess.py +553 -0
  19. arrayprobe/driver/run_flight.py +8166 -0
  20. arrayprobe/driver/tas_from_probe_housekeeping.py +124 -0
  21. arrayprobe/dropsize.py +519 -0
  22. arrayprobe/friendly.py +206 -0
  23. arrayprobe/geometry/__init__.py +77 -0
  24. arrayprobe/geometry/min_rectangle.py +92 -0
  25. arrayprobe/intarr.py +12 -0
  26. arrayprobe/intarr_analysis.py +16 -0
  27. arrayprobe/intarr_plots.py +12 -0
  28. arrayprobe/inventory.py +129 -0
  29. arrayprobe/jit_kernels.py +344 -0
  30. arrayprobe/lwc.py +44 -0
  31. arrayprobe/masks.py +349 -0
  32. arrayprobe/matio.py +410 -0
  33. arrayprobe/matlab_compat.py +13 -0
  34. arrayprobe/ncio.py +26 -0
  35. arrayprobe/particle.py +55 -0
  36. arrayprobe/particle_perimeter.py +12 -0
  37. arrayprobe/products.py +78 -0
  38. arrayprobe/profiles.py +179 -0
  39. arrayprobe/provenance.py +21 -0
  40. arrayprobe/py.typed +11 -0
  41. arrayprobe/readers/__init__.py +9 -0
  42. arrayprobe/readers/dmt.py +603 -0
  43. arrayprobe/readers/mask_csv.py +12 -0
  44. arrayprobe/readers/pms.py +12 -0
  45. arrayprobe/readers/sea.py +433 -0
  46. arrayprobe/readers/tasinfo.py +12 -0
  47. arrayprobe/regimes.py +507 -0
  48. arrayprobe/render.py +728 -0
  49. arrayprobe/reproduce_report.py +149 -0
  50. arrayprobe/review_agreement.py +135 -0
  51. arrayprobe/review_sampling.py +327 -0
  52. arrayprobe/run_page.py +624 -0
  53. arrayprobe/sample_area.py +12 -0
  54. arrayprobe/selector.py +206 -0
  55. arrayprobe/sizing.py +151 -0
  56. arrayprobe/time_convert.py +12 -0
  57. arrayprobe/timing_closure.py +141 -0
  58. arrayprobe/tools/__init__.py +27 -0
  59. arrayprobe/tools/make_demo_flight.py +1089 -0
  60. arrayprobe/tools/make_tas_file.py +760 -0
  61. arrayprobe/tools/probe_comparison.py +569 -0
  62. arrayprobe/tools/synthetic_truth.py +698 -0
  63. arrayprobe/tools/tas_sources.py +705 -0
  64. arrayprobe/triage_context.py +488 -0
  65. arrayprobe/triage_server.py +5215 -0
  66. arrayprobe/tune/__init__.py +15 -0
  67. arrayprobe/tune/diodes.py +400 -0
  68. arrayprobe/tune/distributions.py +300 -0
  69. arrayprobe/tune/sample.py +243 -0
  70. arrayprobe/tune/score.py +230 -0
  71. arrayprobe/tune/settings.py +354 -0
  72. arrayprobe/validate_by_condition.py +208 -0
  73. arrayprobe/validation_report.py +166 -0
  74. arrayprobe-0.1.0.dist-info/METADATA +260 -0
  75. arrayprobe-0.1.0.dist-info/RECORD +189 -0
  76. arrayprobe-0.1.0.dist-info/WHEEL +5 -0
  77. arrayprobe-0.1.0.dist-info/entry_points.txt +2 -0
  78. arrayprobe-0.1.0.dist-info/licenses/LICENSE +31 -0
  79. arrayprobe-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
  80. arrayprobe-0.1.0.dist-info/licenses/NOTICE.md +369 -0
  81. arrayprobe-0.1.0.dist-info/top_level.txt +4 -0
  82. arrayprobe_soda2/__init__.py +131 -0
  83. arrayprobe_soda2/angles.py +143 -0
  84. arrayprobe_soda2/aspect_ratio.py +541 -0
  85. arrayprobe_soda2/backfill.py +100 -0
  86. arrayprobe_soda2/binary_dof.py +181 -0
  87. arrayprobe_soda2/buildindex.py +113 -0
  88. arrayprobe_soda2/decompress_dmt.py +285 -0
  89. arrayprobe_soda2/enhancement_hooks.py +275 -0
  90. arrayprobe_soda2/export_ascii.py +732 -0
  91. arrayprobe_soda2/export_ncdf.py +683 -0
  92. arrayprobe_soda2/export_ncdf_raf.py +396 -0
  93. arrayprobe_soda2/fillholes.py +161 -0
  94. arrayprobe_soda2/find_radius.py +105 -0
  95. arrayprobe_soda2/findsize.py +407 -0
  96. arrayprobe_soda2/fit_poisson.py +170 -0
  97. arrayprobe_soda2/fix2dimage.py +63 -0
  98. arrayprobe_soda2/fixraking.py +162 -0
  99. arrayprobe_soda2/fixstuckbits.py +146 -0
  100. arrayprobe_soda2/hvps4_read_frame.py +121 -0
  101. arrayprobe_soda2/jit_kernels.py +152 -0
  102. arrayprobe_soda2/label_blobs.py +177 -0
  103. arrayprobe_soda2/min_circle_fast.py +320 -0
  104. arrayprobe_soda2/particlesort.py +703 -0
  105. arrayprobe_soda2/pbp_writer.py +558 -0
  106. arrayprobe_soda2/poisson_spot_correct.py +183 -0
  107. arrayprobe_soda2/princomp.py +107 -0
  108. arrayprobe_soda2/probespecs.py +361 -0
  109. arrayprobe_soda2/process_2d.py +1364 -0
  110. arrayprobe_soda2/process_2d_parallel.py +626 -0
  111. arrayprobe_soda2/process_hk.py +512 -0
  112. arrayprobe_soda2/processbuffer_2dc.py +155 -0
  113. arrayprobe_soda2/processbuffer_cip.py +213 -0
  114. arrayprobe_soda2/processbuffer_f2dc.py +139 -0
  115. arrayprobe_soda2/processbuffer_spec.py +441 -0
  116. arrayprobe_soda2/processbuffer_tail.py +350 -0
  117. arrayprobe_soda2/pth_readers.py +245 -0
  118. arrayprobe_soda2/py.typed +11 -0
  119. arrayprobe_soda2/read2dbuffer.py +371 -0
  120. arrayprobe_soda2/reject.py +246 -0
  121. arrayprobe_soda2/reprocess_pbp.py +156 -0
  122. arrayprobe_soda2/sample_area.py +264 -0
  123. arrayprobe_soda2/save_writer.py +480 -0
  124. arrayprobe_soda2/sea.py +324 -0
  125. arrayprobe_soda2/spec_absolutepointers.py +109 -0
  126. arrayprobe_soda2/spec_decompress.py +203 -0
  127. arrayprobe_soda2/spec_index.py +476 -0
  128. arrayprobe_soda2/spec_read_frame.py +286 -0
  129. arrayprobe_soda2/spec_read_hk.py +301 -0
  130. arrayprobe_soda2/spec_readint.py +127 -0
  131. arrayprobe_soda2/timeconv.py +77 -0
  132. arrayprobe_soda2/update_op.py +101 -0
  133. arrayprobe_uiops/__init__.py +45 -0
  134. arrayprobe_uiops/combine.py +192 -0
  135. arrayprobe_uiops/combine_fork.py +359 -0
  136. arrayprobe_uiops/constants.py +830 -0
  137. arrayprobe_uiops/decode_naming.py +113 -0
  138. arrayprobe_uiops/diode_mask.py +250 -0
  139. arrayprobe_uiops/engine_absence.py +41 -0
  140. arrayprobe_uiops/export_oap.py +325 -0
  141. arrayprobe_uiops/geometry_core.py +366 -0
  142. arrayprobe_uiops/habit.py +749 -0
  143. arrayprobe_uiops/habit_core.py +248 -0
  144. arrayprobe_uiops/hollow_size_rule.py +376 -0
  145. arrayprobe_uiops/imgproc.py +2081 -0
  146. arrayprobe_uiops/imgproc_core.py +275 -0
  147. arrayprobe_uiops/intarr.py +167 -0
  148. arrayprobe_uiops/intarr_analysis.py +569 -0
  149. arrayprobe_uiops/intarr_plots.py +119 -0
  150. arrayprobe_uiops/jit_kernels.py +430 -0
  151. arrayprobe_uiops/lwc.py +70 -0
  152. arrayprobe_uiops/matlab_compat.py +860 -0
  153. arrayprobe_uiops/measure.py +346 -0
  154. arrayprobe_uiops/min_circle.py +204 -0
  155. arrayprobe_uiops/min_ellipse.py +161 -0
  156. arrayprobe_uiops/min_rectangle.py +200 -0
  157. arrayprobe_uiops/ncar_2dc_timing.py +100 -0
  158. arrayprobe_uiops/ncio.py +810 -0
  159. arrayprobe_uiops/oap_read.py +228 -0
  160. arrayprobe_uiops/particle.py +51 -0
  161. arrayprobe_uiops/particle_perimeter.py +94 -0
  162. arrayprobe_uiops/particle_physics.py +199 -0
  163. arrayprobe_uiops/pecan_params.py +134 -0
  164. arrayprobe_uiops/probe_cases.py +298 -0
  165. arrayprobe_uiops/product_sanity.py +337 -0
  166. arrayprobe_uiops/profile.py +71 -0
  167. arrayprobe_uiops/profiles.py +756 -0
  168. arrayprobe_uiops/provenance.py +804 -0
  169. arrayprobe_uiops/py.typed +11 -0
  170. arrayprobe_uiops/qc.py +169 -0
  171. arrayprobe_uiops/readers/__init__.py +8 -0
  172. arrayprobe_uiops/readers/mask_csv.py +74 -0
  173. arrayprobe_uiops/readers/pms.py +239 -0
  174. arrayprobe_uiops/readers/tasinfo.py +57 -0
  175. arrayprobe_uiops/rect_ellipse.py +129 -0
  176. arrayprobe_uiops/register_image_assisted.py +25 -0
  177. arrayprobe_uiops/reject.py +501 -0
  178. arrayprobe_uiops/reject_core.py +220 -0
  179. arrayprobe_uiops/sample_area.py +93 -0
  180. arrayprobe_uiops/sizedist.py +1923 -0
  181. arrayprobe_uiops/sizedist_core.py +814 -0
  182. arrayprobe_uiops/sizedist_tables.py +642 -0
  183. arrayprobe_uiops/spec.py +1094 -0
  184. arrayprobe_uiops/spec_core.py +703 -0
  185. arrayprobe_uiops/stray_pixel.py +103 -0
  186. arrayprobe_uiops/tas.py +191 -0
  187. arrayprobe_uiops/time_convert.py +41 -0
  188. uiops/__init__.py +402 -0
  189. uiops/py.typed +11 -0
arrayprobe/run_page.py ADDED
@@ -0,0 +1,624 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """The triage server's Run page: the pure core (form -> TOML -> argv).
3
+
4
+ Design: ``RUN_PAGE_PLAN.md`` (local session notes, not shipped). The page writes the same
5
+ TOML a command-line run reads and launches the documented entry point (``arrayprobe run
6
+ <config.toml>`` for the UIOOPS engines, ``arrayprobe soda2 run <config.toml>`` for SODA-2). It
7
+ holds **no processing rule**: it validates only shape and whitelists (engine, preset, profile,
8
+ probe, paths, run name), and the driver's own ``--dry-run`` preflight is the authority on
9
+ everything else, so a refusal added to the driver reaches the page with no edit here.
10
+
11
+ Slice 2 adds the dry-run validator, the detached launch, run records and run status; the
12
+ routes and HTML are slice 3.
13
+ Every argv this module builds is a list with ``sys.executable`` as its program -- never a shell
14
+ string.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import re
22
+ import sys
23
+ from collections.abc import Iterable, Mapping
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ __all__ = ["ENGINES", "PROTECTIVE_MODES", "preset_choices", "profile_choices",
28
+ "probe_choices_v35", "probe_choices_soda2", "build_toml", "build_argv",
29
+ "validate_form", "raw_list", "dry_run", "launch_detached", "new_run_id",
30
+ "start_run", "write_record", "read_record", "list_runs", "run_status"]
31
+
32
+ #: The three engines a run may name (``config._ENGINES``); 3.5 is the default.
33
+ ENGINES = ("3.5", "soda2", "3.1.4")
34
+ PROTECTIVE_MODES = ("auto", "on", "off")
35
+ #: ``[soda2]`` fields the form may set beyond the probe row, ``fn`` and ``outdir``; anything
36
+ #: else stays in the written file for the user to edit (plan section 0, SODA-2 GUI subset).
37
+ SODA2_FORM_FIELDS = ("date", "starttime", "stoptime", "timeoffset")
38
+ _STAGES_OK = re.compile(r"^[234]+$")
39
+ _NAME_OK = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
40
+ #: The driver's own sentence (``run_flight.main``), so the page and the driver say the same thing.
41
+ REFUSAL_314 = ("--engine 3.1.4 needs --port-validation: v3.1.4 is the ORACLES-validation "
42
+ "anchor only, and its output is stamped port validation, not for quoting")
43
+
44
+
45
+ def preset_choices() -> tuple[str, ...]:
46
+ """``run_flight.PRESETS`` keys, through the CLI's one loader of the driver."""
47
+ from .cli import _load_run_flight
48
+ return tuple(_load_run_flight().PRESETS)
49
+
50
+
51
+ def profile_choices() -> tuple[str, ...]:
52
+ """Every profile name a config file may select (``config.PROFILES``)."""
53
+ from .config import PROFILES
54
+ return tuple(sorted(PROFILES))
55
+
56
+
57
+ def probe_choices_v35() -> tuple[str, ...]:
58
+ """``arrayprobe_uiops.imgproc.PROBES_V35`` keys -- the UIOOPS ``[run].probe`` names."""
59
+ from arrayprobe_uiops.imgproc import PROBES_V35
60
+ return tuple(PROBES_V35)
61
+
62
+
63
+ def probe_choices_soda2() -> tuple[str, ...]:
64
+ """SODA-2's probe table: ``arrayprobe_soda2.probespecs.PROBE_NAMES``
65
+ (``soda2_probespecs.pro``'s ``probename`` column)."""
66
+ from arrayprobe_soda2.probespecs import PROBE_NAMES
67
+ return tuple(PROBE_NAMES)
68
+
69
+
70
+ def raw_list(value: Any) -> list[str]:
71
+ """The form's raw field -- a list, or one path per line -- as a list of non-blank strings."""
72
+ items: Iterable[Any] = value.splitlines() if isinstance(value, str) else (value or [])
73
+ return [str(s).strip() for s in items if str(s).strip()]
74
+
75
+
76
+ def _toml_value(value: Any) -> str:
77
+ """A TOML literal for a str/int/float/bool or a list of them. ``json.dumps`` quoting is
78
+ valid TOML for basic strings (backslashes and ``\\uXXXX`` escapes included)."""
79
+ if isinstance(value, bool):
80
+ return "true" if value else "false"
81
+ if isinstance(value, (list, tuple)):
82
+ return "[" + ", ".join(_toml_value(v) for v in value) + "]"
83
+ if isinstance(value, (int, float, str)):
84
+ return json.dumps(value)
85
+ raise TypeError(f"no TOML literal for {type(value).__name__}: {value!r}")
86
+
87
+
88
+ def _plain(value: Any) -> Any:
89
+ """A probe-table value as a Python scalar/list. float32 goes through its shortest repr so
90
+ ``5.1e-08`` is written as typed in ``soda2_probespecs.pro``, not as a widened double."""
91
+ import numpy as np
92
+ if isinstance(value, np.ndarray):
93
+ return [_plain(v) for v in value.tolist()]
94
+ if isinstance(value, np.floating):
95
+ return float(str(value))
96
+ if isinstance(value, np.integer):
97
+ return int(value)
98
+ return value
99
+
100
+
101
+ def _table(name: str, rows: Mapping[str, Any]) -> list[str]:
102
+ return [f"[{name}]", *(f"{k} = {_toml_value(v)}" for k, v in rows.items()), ""]
103
+
104
+
105
+ def build_toml(form: Mapping[str, Any]) -> str:
106
+ """The configuration file a validated form describes. Pure; raw and out are written
107
+ resolved and absolute, so the file reads the same wherever it is saved."""
108
+ engine = str(form["engine"])
109
+ raws = [str(Path(p).resolve()) for p in raw_list(form.get("raw"))]
110
+ out = str(Path(str(form["out"])).resolve())
111
+ lines = ["# Written by the triage server's Run page; edit and re-run with the same command.",
112
+ ""]
113
+ if engine == "soda2":
114
+ from arrayprobe_soda2.probespecs import soda2_probespecs
115
+ row = soda2_probespecs(name=str(form["probe"]))
116
+ assert isinstance(row, dict), "a scalar name returns one row"
117
+ lines += _table("run", {"engine": "soda2", "jit": bool(form.get("jit", False))})
118
+ soda2: dict[str, Any] = {k: _plain(v) for k, v in row.items()}
119
+ soda2["fn"] = raws[0] if len(raws) == 1 else raws
120
+ soda2["outdir"] = out + os.sep
121
+ for key in SODA2_FORM_FIELDS:
122
+ if form.get(key) not in (None, ""):
123
+ soda2[key] = form[key]
124
+ lines += _table("soda2", soda2)
125
+ return "\n".join(lines)
126
+ lines += _table("fidelity", {"profile": str(form["profile"])})
127
+ run: dict[str, Any] = {"engine": engine, "preset": str(form["preset"]), "raw": raws,
128
+ "out": out, "stages": str(form.get("stages") or "234")}
129
+ if form.get("probe"):
130
+ run["probe"] = str(form["probe"])
131
+ if form.get("tas_file"):
132
+ run["tas_file"] = str(Path(str(form["tas_file"])).resolve())
133
+ lines += _table("run", run)
134
+ return "\n".join(lines)
135
+
136
+
137
+ def _int(form: Mapping[str, Any], key: str, default: int = 1) -> int:
138
+ return int(form.get(key) or default)
139
+
140
+
141
+ def build_argv(form: Mapping[str, Any], toml_path: Path | str, *, dry_run: bool) -> list[str]:
142
+ """The documented entry point's argv for a validated form. Always a list, program
143
+ ``sys.executable``; run-shape flags (``--jobs`` and friends) ride on the argv, not the file,
144
+ exactly as ``arrayprobe run`` treats them.
145
+
146
+ SODA-2 has no ``--dry-run``; its preflight is ``arrayprobe soda2 enhancements <config>``,
147
+ which loads and checks the file (and its enhancement table) and runs nothing.
148
+ """
149
+ base = [sys.executable, "-m", "arrayprobe"]
150
+ toml_s = str(toml_path)
151
+ engine = str(form["engine"])
152
+ if engine == "soda2":
153
+ protective = str(form.get("protective") or "auto")
154
+ if dry_run:
155
+ return [*base, "soda2", "enhancements", toml_s, "--protective", protective]
156
+ argv = [*base, "soda2", "run", toml_s, "--out", str(Path(str(form["out"])).resolve()),
157
+ "--jobs", str(_int(form, "jobs"))]
158
+ if _int(form, "chunks", 0) > 1:
159
+ argv += ["--chunks", str(_int(form, "chunks"))]
160
+ if form.get("jit"):
161
+ argv.append("--jit")
162
+ return argv + ["--protective", protective]
163
+ # --yes is mandatory: a detached run has no terminal to answer the confirmation gate.
164
+ argv = [*base, "run", toml_s, "--yes"]
165
+ for key in ("jobs", "s2_jobs", "chunks"):
166
+ argv += [f"--{key.replace('_', '-')}", str(_int(form, key))]
167
+ if form.get("jit"):
168
+ argv.append("--jit")
169
+ if form.get("port_validation"):
170
+ # Forwarded as ticked, never added from the engine: the driver's refusal is the last word.
171
+ argv.append("--port-validation")
172
+ if dry_run:
173
+ argv.append("--dry-run")
174
+ return argv
175
+
176
+
177
+ def validate_form(form: Mapping[str, Any], *, presets: Iterable[str] | None = None,
178
+ profiles: Iterable[str] | None = None,
179
+ probes_v35: Iterable[str] | None = None,
180
+ soda2_probes: Iterable[str] | None = None) -> list[str]:
181
+ """Every whitelist and shape problem with ``form``, empty when the form may be written.
182
+ The tables default to the discovered ones; tests inject their own."""
183
+ errors: list[str] = []
184
+ engine = form.get("engine")
185
+ if engine not in ENGINES:
186
+ return [f"engine must be one of {list(ENGINES)}; got {engine!r}"]
187
+ name = form.get("name", "")
188
+ if not isinstance(name, str) or not _NAME_OK.match(name):
189
+ errors.append(f"run name must be 1-64 of letters, digits, '.', '_', '-'; got {name!r}")
190
+ raws = raw_list(form.get("raw"))
191
+ if not raws:
192
+ errors.append("give at least one raw file, one path per line")
193
+ for p in raws:
194
+ if not Path(p).is_file():
195
+ errors.append(f"raw file not found: {p}")
196
+ out = form.get("out")
197
+ if not isinstance(out, str) or not out.strip():
198
+ errors.append("give an output folder")
199
+ else:
200
+ po = Path(out).resolve()
201
+ if po.exists() and not po.is_dir():
202
+ errors.append(f"output folder is a file: {out}")
203
+ elif not po.exists() and not po.parent.is_dir():
204
+ errors.append(f"output folder's parent does not exist: {po.parent}")
205
+ for key in ("jobs", "s2_jobs", "chunks"):
206
+ value = form.get(key, 1)
207
+ if isinstance(value, bool) or not isinstance(value, (int, str)) \
208
+ or not str(value).isdigit() or int(value) < 1:
209
+ errors.append(f"{key} must be a whole number >= 1; got {value!r}")
210
+ protective = form.get("protective") or "auto"
211
+ if protective not in PROTECTIVE_MODES:
212
+ errors.append(f"protective must be one of {list(PROTECTIVE_MODES)}; got {protective!r}")
213
+ if engine == "soda2":
214
+ table = soda2_probes if soda2_probes is not None else probe_choices_soda2()
215
+ if form.get("probe") not in set(table):
216
+ errors.append(f"SODA-2 probe {form.get('probe')!r} is not in soda2_probespecs")
217
+ if form.get("port_validation"):
218
+ errors.append("--port-validation applies to engine 3.1.4 only")
219
+ return errors
220
+ # UIOOPS engines.
221
+ if protective != "auto":
222
+ # `arrayprobe run` takes no --protective; the driver applies its own default ("auto").
223
+ errors.append("protective is set by the driver for UIOPS runs; `arrayprobe run` has no "
224
+ "--protective, so only 'auto' can be honoured")
225
+ if engine == "3.1.4" and not form.get("port_validation"):
226
+ errors.append(REFUSAL_314)
227
+ if engine != "3.1.4" and form.get("port_validation"):
228
+ errors.append("--port-validation applies to engine 3.1.4 only")
229
+ if form.get("preset") not in set(presets if presets is not None else preset_choices()):
230
+ errors.append(f"unknown preset {form.get('preset')!r}")
231
+ if form.get("profile") not in set(profiles if profiles is not None else profile_choices()):
232
+ errors.append(f"unknown profile {form.get('profile')!r}")
233
+ probe = form.get("probe")
234
+ if probe not in (None, "") and probe not in set(
235
+ probes_v35 if probes_v35 is not None else probe_choices_v35()):
236
+ errors.append(f"unknown probe {probe!r}")
237
+ stages = str(form.get("stages") or "234")
238
+ if not _STAGES_OK.match(stages):
239
+ errors.append(f"stages must use only 2, 3 and 4; got {stages!r}")
240
+ tas = form.get("tas_file")
241
+ if tas not in (None, "") and not Path(str(tas)).is_file():
242
+ errors.append(f"tas file not found: {tas}")
243
+ return errors
244
+
245
+
246
+ # ---------------------------------------------------------------------------------------------
247
+ # Slice 2: dry run, detached launch, run records, run status.
248
+ # ---------------------------------------------------------------------------------------------
249
+
250
+ #: The directory under the chosen output folder that holds one folder per launched run.
251
+ RUNS_DIR = "_runs"
252
+ _RUN_ID_OK = re.compile(r"^\d{8}-\d{6}-[A-Za-z0-9_.-]{1,64}$")
253
+ #: The wrapper's last line. The header
254
+ #: written at launch never contains the marker word, so a grep cannot match a run that has not
255
+ #: ended (``tests/test_launch_detached.py::TheCompletionMarkerIsNotCounterfeited``).
256
+ _EXIT_LINE = re.compile(r"^=== (?P<run_id>\S+) exited (?P<code>-?\d+) ")
257
+ _VERDICT_LINE = re.compile(r"^(OK\b|FAILED\b|Traceback\b|.*\brefus(ed|es)\b)", re.IGNORECASE)
258
+ #: Windows process-creation flags for a run that must outlive the server (``subprocess``'s
259
+ #: constants, spelled out so the module imports on POSIX).
260
+ CREATE_NEW_PROCESS_GROUP = 0x00000200
261
+ DETACHED_PROCESS = 0x00000008
262
+
263
+
264
+ def dry_run(argv: list[str], cwd: Path | str, *, timeout: float = 120,
265
+ launcher: Any = None) -> tuple[int, str]:
266
+ """Run the driver's preflight (``argv`` from ``build_argv(..., dry_run=True)``) in the
267
+ foreground and return ``(returncode, combined output)`` verbatim. A timeout is reported as
268
+ returncode -1 with what was captured. ``launcher`` defaults to ``subprocess.run``."""
269
+ import subprocess
270
+ run = launcher if launcher is not None else subprocess.run
271
+ if not isinstance(argv, list):
272
+ raise TypeError("argv must be a list; no shell string is ever run")
273
+ try:
274
+ done = run(argv, cwd=str(cwd), capture_output=True, text=True, timeout=timeout,
275
+ stdin=subprocess.DEVNULL)
276
+ except subprocess.TimeoutExpired as exc:
277
+ partial = exc.stdout if isinstance(exc.stdout, str) else ""
278
+ return -1, partial + f"\n[dry run did not finish within {timeout:g} s]"
279
+ return int(done.returncode), (done.stdout or "") + (done.stderr or "")
280
+
281
+
282
+ def _wrapped(run_id: str, argv: list[str]) -> list[str]:
283
+ """``argv`` behind this module's wrapper, which writes the exit line when the run ends."""
284
+ return [sys.executable, "-m", "arrayprobe.run_page", "_wrap", run_id, "--", *argv]
285
+
286
+
287
+ def launch_detached(argv: list[str], log_path: Path | str, cwd: Path | str, *,
288
+ run_id: str, popen: Any = None) -> int:
289
+ """Start ``argv`` so it outlives the server: its own
290
+ session (Windows: a new process group, detached from the console), stdin from the null
291
+ device, stdout and stderr straight to ``log_path`` (never a pipe: it can hang), and
292
+ a wrapper that writes ``=== <run_id> exited <code> <date> ===`` as the log's last line.
293
+ Returns the wrapper's PID; the wrapper lives exactly as long as the run.
294
+ ``popen`` defaults to ``subprocess.Popen``."""
295
+ import subprocess
296
+ if not isinstance(argv, list):
297
+ raise TypeError("argv must be a list; no shell string is ever run")
298
+ if not _RUN_ID_OK.match(run_id):
299
+ raise ValueError(f"run id {run_id!r} is not one new_run_id makes")
300
+ start = popen if popen is not None else subprocess.Popen
301
+ log_path = Path(log_path)
302
+ log_path.parent.mkdir(parents=True, exist_ok=True)
303
+ kwargs: dict[str, Any] = {"cwd": str(cwd), "stdin": subprocess.DEVNULL,
304
+ "stderr": subprocess.STDOUT, "close_fds": True}
305
+ if os.name == "nt":
306
+ kwargs["creationflags"] = CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS
307
+ else:
308
+ kwargs["start_new_session"] = True
309
+ with open(log_path, "ab") as log:
310
+ log.write((f"=== {run_id} launched detached {_now_iso()} ===\n"
311
+ f"=== command: {' '.join(argv)} ===\n").encode())
312
+ log.flush()
313
+ proc = start(_wrapped(run_id, argv), stdout=log, **kwargs)
314
+ pid = int(proc.pid)
315
+ with open(log_path, "ab") as log:
316
+ log.write((f"=== pid: {pid} (the wrapper; its python child does the work) ===\n"
317
+ "=== a log that stopped growing is not a dead run: the run has ended only "
318
+ "once a final line here reports its exit code ===\n").encode())
319
+ return pid
320
+
321
+
322
+ def _hold_wakelock() -> None:
323
+ """Keep Windows from sleeping while this process lives (``_detached_wrapper.sh``'s
324
+ ES_CONTINUOUS|ES_SYSTEM_REQUIRED); released when the process exits. No-op elsewhere."""
325
+ if os.name != "nt":
326
+ return
327
+ try:
328
+ import ctypes
329
+ ctypes.windll.kernel32.SetThreadExecutionState(0x80000001) # type: ignore[attr-defined]
330
+ except Exception: # noqa: BLE001 -- a wakelock must never be the reason a run fails
331
+ pass
332
+
333
+
334
+ def _wrap(args: list[str]) -> int:
335
+ """``python -m arrayprobe.run_page _wrap <run_id> -- <argv...>``: run argv with this
336
+ process's stdout and stderr (the log), then print the exit line."""
337
+ import subprocess
338
+ if len(args) < 3 or args[1] != "--" or not _RUN_ID_OK.match(args[0]):
339
+ print("usage: python -m arrayprobe.run_page _wrap <run_id> -- <command> [args...]",
340
+ file=sys.stderr)
341
+ return 2
342
+ run_id, argv = args[0], args[2:]
343
+ _hold_wakelock()
344
+ sys.stdout.flush()
345
+ try:
346
+ code = subprocess.call(argv, stdin=subprocess.DEVNULL)
347
+ except OSError as exc:
348
+ print(f"could not start {argv[0]!r}: {exc}", flush=True)
349
+ code = 127
350
+ print(f"=== {run_id} exited {code} {_now_iso()} ===", flush=True)
351
+ return code
352
+
353
+
354
+ def _now_iso() -> str:
355
+ import datetime as _dt
356
+ return _dt.datetime.now().astimezone().isoformat(timespec="seconds")
357
+
358
+
359
+ def new_run_id(name: str, now: Any = None) -> str:
360
+ """``<YYYYMMDD-HHMMSS>-<name>``; ``name`` must satisfy the form's whitelist."""
361
+ import datetime as _dt
362
+ if not isinstance(name, str) or not _NAME_OK.match(name):
363
+ raise ValueError(f"run name {name!r} is not whitelisted")
364
+ stamp = (now or _dt.datetime.now()).strftime("%Y%m%d-%H%M%S")
365
+ return f"{stamp}-{name}"
366
+
367
+
368
+ def _runs_root(out: Path | str) -> Path:
369
+ return Path(out).resolve() / RUNS_DIR
370
+
371
+
372
+ def write_record(out: Path | str, record: Mapping[str, Any]) -> Path:
373
+ """Write ``record`` as ``<out>/_runs/<run_id>/run.json``; returns the path."""
374
+ run_id = str(record["run_id"])
375
+ if not _RUN_ID_OK.match(run_id):
376
+ raise ValueError(f"run id {run_id!r} is not one new_run_id makes")
377
+ path = _runs_root(out) / run_id / "run.json"
378
+ path.parent.mkdir(parents=True, exist_ok=True)
379
+ path.write_text(json.dumps(dict(record), indent=2), encoding="utf-8")
380
+ return path
381
+
382
+
383
+ def list_runs(out: Path | str) -> list[str]:
384
+ """Run ids recorded under ``out``, newest first: folders whose name has the run-id shape
385
+ and which hold a ``run.json``."""
386
+ root = _runs_root(out)
387
+ if not root.is_dir():
388
+ return []
389
+ ids = [p.name for p in root.iterdir()
390
+ if p.is_dir() and _RUN_ID_OK.match(p.name) and (p / "run.json").is_file()]
391
+ return sorted(ids, reverse=True)
392
+
393
+
394
+ def read_record(out: Path | str, run_id: str) -> dict[str, Any] | None:
395
+ """The record for ``run_id``, or None. ``run_id`` reaches a path only after it matched an
396
+ entry ``list_runs`` found on disk (the ``_valid_flight`` doctrine)."""
397
+ if run_id not in list_runs(out):
398
+ return None
399
+ loaded: dict[str, Any] = json.loads(
400
+ (_runs_root(out) / run_id / "run.json").read_text(encoding="utf-8"))
401
+ return loaded
402
+
403
+
404
+ def start_run(form: Mapping[str, Any], *, cwd: Path | str | None = None, popen: Any = None,
405
+ now: Any = None) -> dict[str, Any]:
406
+ """Write the form's TOML into a new run folder, launch it detached and record it. The form
407
+ must already have passed ``validate_form``; the run name is checked again here because it
408
+ becomes a path."""
409
+ run_id = new_run_id(str(form.get("name", "")), now)
410
+ out = Path(str(form["out"])).resolve()
411
+ run_dir = _runs_root(out) / run_id
412
+ run_dir.mkdir(parents=True, exist_ok=False)
413
+ toml_path = run_dir / "config.toml"
414
+ toml_path.write_text(build_toml(form), encoding="utf-8")
415
+ log_path = run_dir / "run.log"
416
+ argv = build_argv(form, toml_path, dry_run=False)
417
+ started = _now_iso()
418
+ pid = launch_detached(argv, log_path, cwd if cwd is not None else out, run_id=run_id,
419
+ popen=popen)
420
+ record = {"run_id": run_id, "pid": pid, "argv": argv, "toml": str(toml_path),
421
+ "log": str(log_path), "out": str(out), "engine": str(form["engine"]),
422
+ "started": started}
423
+ write_record(out, record)
424
+ return record
425
+
426
+
427
+ def _pid_alive(pid: int) -> bool:
428
+ """Whether ``pid`` is running. Windows asks the kernel (MSYS ``ps`` misses native
429
+ grandchildren, 2026-09-13); POSIX uses signal 0."""
430
+ if pid <= 0:
431
+ return False
432
+ if os.name == "nt":
433
+ import ctypes
434
+ kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
435
+ handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
436
+ if not handle:
437
+ return False
438
+ try:
439
+ code = ctypes.c_ulong()
440
+ ok = kernel32.GetExitCodeProcess(handle, ctypes.byref(code))
441
+ return bool(ok) and code.value == 259 # STILL_ACTIVE
442
+ finally:
443
+ kernel32.CloseHandle(handle)
444
+ try:
445
+ os.kill(pid, 0)
446
+ except ProcessLookupError:
447
+ return False
448
+ except PermissionError:
449
+ return True
450
+ return True
451
+
452
+
453
+ def _started_epoch(record: Mapping[str, Any]) -> float:
454
+ import datetime as _dt
455
+ try:
456
+ return _dt.datetime.fromisoformat(str(record["started"])).timestamp()
457
+ except (KeyError, ValueError):
458
+ return 0.0
459
+
460
+
461
+ def run_status(record: Mapping[str, Any], *, tail_lines: int = 40,
462
+ alive: Any = None) -> dict[str, Any]:
463
+ """What the page shows for one run: state, exit code (from the wrapper's exit line), the
464
+ log's tail, verdict lines (OK / FAILED / Traceback / refused), the ``.call`` stamps written
465
+ under ``out`` since the start, and the newest output file's mtime -- a chunked or ``--jobs``
466
+ run is silent in its log for long stretches, so that mtime is the heartbeat.
467
+ ``alive`` defaults to a process-table check of ``record['pid']``."""
468
+ check = alive if alive is not None else _pid_alive
469
+ log = Path(str(record["log"]))
470
+ text = log.read_text(encoding="utf-8", errors="replace") if log.is_file() else ""
471
+ lines = text.splitlines()
472
+ exit_code: int | None = None
473
+ for line in reversed(lines):
474
+ m = _EXIT_LINE.match(line)
475
+ if m and m.group("run_id") == record.get("run_id"):
476
+ exit_code = int(m.group("code"))
477
+ break
478
+ out = Path(str(record["out"]))
479
+ since = _started_epoch(record)
480
+ calls: list[str] = []
481
+ newest = 0.0
482
+ if out.is_dir():
483
+ for p in out.rglob("*"):
484
+ rel = p.relative_to(out)
485
+ if rel.parts[:1] == (RUNS_DIR,) or not p.is_file():
486
+ continue
487
+ mtime = p.stat().st_mtime
488
+ newest = max(newest, mtime)
489
+ if p.suffix == ".call" and mtime >= since - 1:
490
+ calls.append(rel.as_posix())
491
+ is_alive = exit_code is None and bool(check(int(record.get("pid", 0))))
492
+ if exit_code is not None:
493
+ state = "finished" if exit_code == 0 else "failed"
494
+ else:
495
+ state = "running" if is_alive else "ended without an exit line"
496
+ return {"run_id": record.get("run_id"), "state": state, "alive": is_alive,
497
+ "exit_code": exit_code, "log_tail": lines[-tail_lines:],
498
+ "verdict_lines": [ln for ln in lines if _VERDICT_LINE.match(ln)],
499
+ "call_files": sorted(calls), "newest_output_mtime": newest or None}
500
+
501
+
502
+ if __name__ == "__main__":
503
+ if len(sys.argv) > 1 and sys.argv[1] == "_wrap":
504
+ sys.exit(_wrap(sys.argv[2:]))
505
+ print("usage: python -m arrayprobe.run_page _wrap <run_id> -- <command> [args...]",
506
+ file=sys.stderr)
507
+ sys.exit(2)
508
+
509
+
510
+ # --- HTTP surface (slice 3): the triage server's /run and /runs routes call these --------------
511
+
512
+ def _esc(value: Any) -> str:
513
+ import html
514
+ return html.escape(str(value))
515
+
516
+
517
+ def _options(values: Iterable[str]) -> str:
518
+ return "".join(f'<option value="{_esc(v)}">{_esc(v)}</option>' for v in values)
519
+
520
+
521
+ def render_form() -> str:
522
+ """The Run page: the form, posted as JSON to ``/run`` (``dry_run`` true first)."""
523
+ return f"""<!doctype html><html><head><meta charset="utf-8"><title>Run a flight</title></head>
524
+ <body><h1>Run a flight</h1><p><a href="/">index</a> · <a href="/runs">runs</a></p>
525
+ <form id="f">
526
+ <label>Engine <select name="engine">{_options(ENGINES)}</select></label><br>
527
+ <label>Preset <select name="preset">{_options(preset_choices())}</select></label><br>
528
+ <label>Profile <select name="profile">
529
+ <option value=""></option>{_options(profile_choices())}</select></label><br>
530
+ <label>Probe (v3.5) <select name="probe">
531
+ <option value=""></option>{_options(probe_choices_v35())}</select></label><br>
532
+ <label>Probe (SODA-2) <select name="soda2_probe">
533
+ <option value=""></option>{_options(probe_choices_soda2())}</select></label><br>
534
+ <label>Raw file(s) <input name="raw" size="80"></label><br>
535
+ <label>Output folder <input name="out" size="80"></label><br>
536
+ <label>Run name <input name="name"></label><br>
537
+ <label>Protective <select name="protective">{_options(PROTECTIVE_MODES)}</select></label><br>
538
+ <button type="button" data-dry="1">Check (dry run)</button>
539
+ <button type="button" data-dry="0">Launch</button>
540
+ </form><pre id="out"></pre>
541
+ <script>
542
+ document.querySelectorAll('#f button').forEach(function (b) {{
543
+ b.onclick = function () {{
544
+ var form = {{}};
545
+ new FormData(document.getElementById('f')).forEach(function (v, k) {{
546
+ if (v !== '') form[k] = v;
547
+ }});
548
+ form.dry_run = b.dataset.dry === '1';
549
+ fetch('/run', {{method: 'POST', headers: {{'Content-Type': 'application/json'}},
550
+ body: JSON.stringify(form)}})
551
+ .then(function (r) {{ return r.json(); }})
552
+ .then(function (j) {{
553
+ if (j.run_id && !form.dry_run) {{ location.href = '/runs/' + j.run_id; return; }}
554
+ document.getElementById('out').textContent =
555
+ (j.errors || []).join('\n') + (j.dry_run_text || '');
556
+ }});
557
+ }};
558
+ }});
559
+ </script></body></html>"""
560
+
561
+
562
+ def render_runs(run_root: Path | str | None) -> str:
563
+ """HTML for ``GET /runs``: the run ids recorded under ``run_root``, newest first, each
564
+ linked to its page; ``None`` (no root yet) lists none."""
565
+ ids = list_runs(run_root) if run_root is not None else []
566
+ rows = "".join(f'<li><a href="/runs/{_esc(i)}">{_esc(i)}</a></li>' for i in ids)
567
+ return (f"<!doctype html><html><head><meta charset=\"utf-8\"><title>Runs</title></head><body>"
568
+ f"<h1>Runs</h1><p><a href=\"/run\">Run a flight</a></p><ul>{rows or '<li>none</li>'}"
569
+ f"</ul></body></html>")
570
+
571
+
572
+ def render_run(record: Mapping[str, Any], status: Mapping[str, Any]) -> str:
573
+ """HTML for ``GET /runs/<run_id>``: state, exit code, ``.call`` stamps and the
574
+ HTML-escaped log tail from ``run_status``; the page refreshes every 10 s."""
575
+ tail = "\n".join(_esc(line) for line in status.get("log_tail", []))
576
+ calls = "".join(f"<li>{_esc(c)}</li>" for c in status.get("call_files", []))
577
+ return (f"<!doctype html><html><head><meta charset=\"utf-8\"><title>Run "
578
+ f"{_esc(record.get('run_id'))}</title><meta http-equiv=\"refresh\" content=\"10\">"
579
+ f"</head><body><h1>Run {_esc(record.get('run_id'))}</h1>"
580
+ f"<p><a href=\"/runs\">runs</a></p><p>state: {_esc(status.get('state'))}, exit: "
581
+ f"{_esc(status.get('exit_code'))}</p><h2>Stamps</h2><ul>{calls}</ul>"
582
+ f"<h2>Log tail</h2><pre>{tail}</pre></body></html>")
583
+
584
+
585
+ def same_origin(headers: Any, port: int) -> bool:
586
+ """True when ``Host`` (and ``Origin``, when sent) name this server on the loopback
587
+ address. Guards the one route that starts a process against a page from another origin."""
588
+ allowed_hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}
589
+ if headers.get("Host", "") not in allowed_hosts:
590
+ return False
591
+ origin = headers.get("Origin")
592
+ return origin is None or origin in {f"http://{h}" for h in allowed_hosts}
593
+
594
+
595
+ def handle_post(form: Mapping[str, Any], headers: Any, port: int, *,
596
+ cwd: Path | str | None = None) -> tuple[int, dict[str, Any]]:
597
+ """``(status, JSON body)`` for ``POST /run``: refuse a foreign origin, validate against the
598
+ whitelists, then either dry-run the driver's preflight or launch detached."""
599
+ if not same_origin(headers, port):
600
+ return 403, {"ok": False, "errors": ["cross-origin request refused"]}
601
+ errors = validate_form(form)
602
+ if errors:
603
+ return 400, {"ok": False, "errors": errors}
604
+ if form.get("dry_run"):
605
+ import tempfile
606
+ with tempfile.TemporaryDirectory(prefix="arrayprobe_run_") as tmp:
607
+ toml_path = Path(tmp) / "config.toml"
608
+ toml_path.write_text(build_toml(form), encoding="utf-8")
609
+ code, text = dry_run(build_argv(form, toml_path, dry_run=True),
610
+ cwd if cwd is not None else tmp)
611
+ return 200, {"ok": code == 0, "errors": [], "dry_run_text": text, "run_id": None}
612
+ record = start_run(form, cwd=cwd)
613
+ return 200, {"ok": True, "errors": [], "dry_run_text": "", "run_id": record["run_id"]}
614
+
615
+
616
+ def get_run_page(run_root: Path | str | None, run_id: str) -> tuple[int, str]:
617
+ """``(status, HTML)`` for ``GET /runs/<run_id>``. The id reaches a path only after it
618
+ matched a record listed on disk."""
619
+ if run_root is None or run_id not in list_runs(run_root):
620
+ return 404, f"unknown run {_esc(run_id)!r}"
621
+ record = read_record(run_root, run_id)
622
+ if record is None:
623
+ return 404, f"unknown run {_esc(run_id)!r}"
624
+ return 200, render_run(record, run_status(record))
@@ -0,0 +1,12 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ import sys as _sys
3
+ import typing as _typing
4
+
5
+ from arrayprobe_uiops import sample_area as _impl
6
+
7
+ # Static view for type checkers only: the alias below replaces this module at run time,
8
+ # so mypy would otherwise see an empty module. No run-time effect.
9
+ if _typing.TYPE_CHECKING:
10
+ from arrayprobe_uiops.sample_area import * # noqa: F403
11
+
12
+ _sys.modules[__name__] = _impl