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
@@ -0,0 +1,265 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Per-diode occupancy for one flight, and SPEC's own noisy-diode test.
3
+
4
+ The brief: *"diode-uniformity report and stuck-bit repair from
5
+ neighbours (the port masks; SODA-2 repairs)"*, and a *"statistical
6
+ noisy-diode detector as a diagnostic"*.
7
+
8
+ **This reports; it repairs nothing and changes no computed number.** The port's
9
+ answer to a bad diode is `masks.py` -- exclude it and say so. Repairing one by
10
+ interpolating its neighbours is a different product, belongs in `enhancements_uiops/`,
11
+ and is **not built here**: see `NOT_BUILT` below for why, which is the same
12
+ reason the m-D registry ships three relations and five declared gaps.
13
+
14
+ ## What a uniformity report is for
15
+
16
+ A diode that is stuck dark shadows every slice it appears in, so it reads as a
17
+ particle edge in every image that crosses it. Nothing in `imgProc_sm` notices:
18
+ each particle is judged on its own silhouette, and a column that is dark in
19
+ *all* of them is perfectly consistent with a stream of narrow particles. The
20
+ signature only exists at flight scale, which is why this is a flight-level
21
+ report rather than a per-particle test.
22
+
23
+ `enhancements.ml_accept_reject`'s Method A attacks the same physics from the
24
+ other end -- `max_col_occ` catches a particle whose *own* window is dominated
25
+ by one column. A diode stuck for the whole flight and a diode stuck for one
26
+ particle are the same fault at different durations, and the two measurements
27
+ are complementary rather than redundant.
28
+
29
+ ## The threshold, and exactly how much of it is quoted
30
+
31
+ The 2D-S Post-Processing Software Manual rev 1.1 (Feb 2011), Appendix B
32
+ pp. 41-45, prints a statistical noisy-diode detector:
33
+
34
+ TH = max(M + 5*sqrt(M), 1.5)
35
+
36
+ over a rolling window of **4,000 images refreshed every 100**. Those three
37
+ numbers -- the 5-sigma coefficient, the 1.5 floor, and the window parameters --
38
+ are transcribed from the manual and are recorded in
39
+ :data:`SPEC_NOISY_DIODE`.
40
+
41
+ **What the manual's own text says `M` counts has not been read here.** This
42
+ module takes it as *the mean per-diode shadowed-image count over the window*,
43
+ which is the reading the formula's shape supports (a Poisson-like count with a
44
+ sqrt-scaled tolerance and a floor for near-empty windows), and it is the only
45
+ reading under which a 1.5 floor means anything. That reading is an inference,
46
+ labelled as one: :data:`SPEC_NOISY_DIODE` carries ``m_definition_established =
47
+ "derived"`` and a note naming what would confirm it. A future reader with the
48
+ manual open should check that field first, and either promote it to
49
+ ``"transcribed"`` or fix the code.
50
+
51
+ Nothing else here is inferred. The occupancy report itself is a count of lit
52
+ slices per diode, which needs no source at all.
53
+ """
54
+ from __future__ import annotations
55
+
56
+ import math
57
+ from dataclasses import dataclass
58
+
59
+ import numpy as np
60
+
61
+ __all__ = [
62
+ "DiodeReport",
63
+ "NOT_BUILT",
64
+ "SPEC_NOISY_DIODE",
65
+ "SpecNoisyDiodeCriterion",
66
+ "accumulate_occupancy",
67
+ "flag_noisy_diodes",
68
+ "report_from_files",
69
+ ]
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class SpecNoisyDiodeCriterion:
74
+ """The manufacturer's detector, with each number's provenance attached."""
75
+
76
+ sigma_coefficient: float
77
+ """The 5 in ``M + 5*sqrt(M)``. Transcribed."""
78
+
79
+ floor: float
80
+ """The 1.5 a threshold may not fall below. Transcribed."""
81
+
82
+ window_images: int
83
+ """4,000. Transcribed."""
84
+
85
+ refresh_every: int
86
+ """100. Transcribed."""
87
+
88
+ source: str
89
+ m_definition_established: str
90
+ """``transcribed`` or ``derived``. It is ``derived``: see the note."""
91
+
92
+ m_definition_note: str
93
+
94
+ def threshold(self, mean_count: float) -> float:
95
+ """``TH = max(M + 5*sqrt(M), 1.5)`` for one window's mean count.
96
+
97
+ A negative ``mean_count`` is a caller error rather than a physical
98
+ state, so it raises instead of returning a NaN that would quietly
99
+ become a threshold nothing exceeds.
100
+ """
101
+ if mean_count < 0:
102
+ raise ValueError(f"mean count must be >= 0, got {mean_count}")
103
+ return max(mean_count + self.sigma_coefficient * math.sqrt(mean_count),
104
+ self.floor)
105
+
106
+
107
+ SPEC_NOISY_DIODE = SpecNoisyDiodeCriterion(
108
+ sigma_coefficient=5.0,
109
+ floor=1.5,
110
+ window_images=4000,
111
+ refresh_every=100,
112
+ source="2D-S Post-Processing Software Manual rev 1.1 (Feb 2011), "
113
+ "Appendix B pp. 41-45",
114
+ m_definition_established="derived",
115
+ m_definition_note=(
116
+ "The formula, the 5-sigma coefficient, the 1.5 floor and the "
117
+ "4,000/100 window are transcribed from the manual. What the manual "
118
+ "says M counts is NOT read here; this module takes it as the mean "
119
+ "per-diode shadowed-image count over the window, which is the reading "
120
+ "the formula's shape supports and the only one under which a 1.5 floor "
121
+ "is meaningful. Confirm against App. B's own wording and either "
122
+ "promote this field to 'transcribed' or fix the code."),
123
+ )
124
+
125
+ #: Deliberately absent, and why. Same pattern as the m-D registry's declared
126
+ #: gaps: a capability nobody has the source for is recorded as a gap, never
127
+ #: approximated.
128
+ NOT_BUILT: dict[str, str] = {
129
+ "stuck_bit_repair": (
130
+ "Both briefs ask for the manufacturer's masked-diode filling (2D-S PP "
131
+ "manual sec 1.1, p. 5) and dead-diode replacement (sec 1.2, p. 6). "
132
+ "Those two sections' algorithms have not been read in this project -- "
133
+ "only their existence and page numbers are recorded. Repair means "
134
+ "writing values into a particle's silhouette, so an invented rule "
135
+ "would put fabricated pixels into every downstream size, area and "
136
+ "habit. Read sec 1.1-1.2, then build it in enhancements_uiops/ with an A/B "
137
+ "against an unrepaired run."),
138
+ }
139
+
140
+
141
+ @dataclass(frozen=True)
142
+ class DiodeReport:
143
+ """One flight's per-diode occupancy, and what it implies."""
144
+
145
+ shadowed_slices: np.ndarray
146
+ """Per diode: how many slices, over every particle counted, were shadowed."""
147
+
148
+ images_present: np.ndarray
149
+ """Per diode: how many particle images the diode was shadowed in at all.
150
+ This, not the slice count, is what the SPEC criterion counts over."""
151
+
152
+ total_slices: int
153
+ total_images: int
154
+
155
+ @property
156
+ def occupancy(self) -> np.ndarray:
157
+ """Shadowed fraction per diode, over every slice counted.
158
+
159
+ The uniformity report proper. A healthy array is flat to within the
160
+ cloud's own inhomogeneity; a stuck diode stands out as a spike that no
161
+ particle population explains.
162
+ """
163
+ if self.total_slices == 0:
164
+ return np.zeros_like(self.shadowed_slices, dtype=float)
165
+ return self.shadowed_slices / float(self.total_slices)
166
+
167
+ def summary(self) -> str:
168
+ """The report in the form a person reads before deciding anything."""
169
+ occ = self.occupancy
170
+ if occ.size == 0 or self.total_images == 0:
171
+ return "no particles counted -- nothing to report"
172
+ worst = int(np.argmax(occ))
173
+ return (f"{self.total_images:,} image(s), {self.total_slices:,} slice(s), "
174
+ f"{occ.size} diodes\n"
175
+ f" occupancy min {occ.min():.4f} median {np.median(occ):.4f} "
176
+ f"max {occ.max():.4f} (diode {worst + 1}, 1-based)")
177
+
178
+
179
+ def accumulate_occupancy(shadows) -> DiodeReport:
180
+ """Count shadowed slices and images per diode over an iterable of silhouettes.
181
+
182
+ Each element is the boolean ``(n_slices, n_diodes)`` array
183
+ :func:`arrayprobe.render.reconstruct_particle_image` returns. An iterable
184
+ rather than an array because a flight's particles do not fit in memory at
185
+ once and a report must not require that they do.
186
+
187
+ A particle with no slices contributes nothing rather than raising: a proc
188
+ file's own ``position`` bounds should prevent it, and a report is the wrong
189
+ place to discover otherwise.
190
+ """
191
+ shadowed: np.ndarray | None = None
192
+ present: np.ndarray | None = None
193
+ total_slices = 0
194
+ total_images = 0
195
+ for shadow in shadows:
196
+ shadow = np.asarray(shadow, dtype=bool)
197
+ if shadow.ndim != 2 or shadow.shape[0] == 0:
198
+ continue
199
+ if shadowed is None:
200
+ shadowed = np.zeros(shadow.shape[1], dtype=np.int64)
201
+ present = np.zeros(shadow.shape[1], dtype=np.int64)
202
+ elif shadow.shape[1] != shadowed.size:
203
+ raise ValueError(
204
+ f"diode count changed mid-flight: {shadow.shape[1]} after "
205
+ f"{shadowed.size}. One report cannot span two array widths.")
206
+ assert present is not None # set with `shadowed`, one line apart
207
+ shadowed = shadowed + shadow.sum(axis=0)
208
+ present = present + shadow.any(axis=0)
209
+ total_slices += shadow.shape[0]
210
+ total_images += 1
211
+ if shadowed is None or present is None:
212
+ return DiodeReport(np.zeros(0, dtype=np.int64), np.zeros(0, dtype=np.int64),
213
+ 0, 0)
214
+ return DiodeReport(shadowed, present, total_slices, total_images)
215
+
216
+
217
+ def flag_noisy_diodes(report: DiodeReport,
218
+ criterion: SpecNoisyDiodeCriterion = SPEC_NOISY_DIODE):
219
+ """Diodes whose image count exceeds the manufacturer's threshold.
220
+
221
+ Returns ``(flagged_indices_0based, threshold, mean_count)``.
222
+
223
+ The threshold is computed from the mean over **all** diodes, which is the
224
+ whole-flight form of the manual's rolling window: with fewer images than
225
+ ``criterion.window_images`` there is only one window, and with more, a
226
+ whole-flight mean is the conservative reading -- a diode noisy for part of
227
+ the flight is diluted, so this under-reports rather than over-reports.
228
+ A rolling implementation needs the per-image arrival order, which this
229
+ accumulation deliberately does not keep; say so rather than implying the
230
+ manual's exact procedure has been reproduced.
231
+ """
232
+ if report.images_present.size == 0:
233
+ return np.zeros(0, dtype=int), criterion.floor, 0.0
234
+ mean_count = float(report.images_present.mean())
235
+ threshold = criterion.threshold(mean_count)
236
+ flagged = np.flatnonzero(report.images_present > threshold)
237
+ return flagged, threshold, mean_count
238
+
239
+
240
+ def report_from_files(image_path, proc_path, *, limit: int | None = None,
241
+ stride: int = 1) -> DiodeReport:
242
+ """Build a report straight from a decoded ``.cdf`` and its ``proc`` file.
243
+
244
+ ``stride`` samples every n-th particle and ``limit`` caps the count: a dense
245
+ flight holds tens of millions of images, and a uniformity report converges
246
+ long before all of them. Both are recorded by the caller, not here -- a
247
+ sampled report is still a report, but the sampling is part of the number.
248
+ """
249
+ import netCDF4
250
+
251
+ from .render import reconstruct_particle_image
252
+
253
+ with netCDF4.Dataset(str(image_path)) as image_ds, \
254
+ netCDF4.Dataset(str(proc_path)) as proc_ds:
255
+ proc_ds.set_auto_maskandscale(False)
256
+ n = proc_ds.dimensions["time"].size
257
+ indices = list(range(0, n, max(1, stride)))
258
+ if limit is not None:
259
+ indices = indices[:limit]
260
+
261
+ def shadows():
262
+ for i in indices:
263
+ yield reconstruct_particle_image(image_ds, proc_ds, int(i))
264
+
265
+ return accumulate_occupancy(shadows())
@@ -0,0 +1,5 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """The flight driver: ``run_flight`` (the per-flight batch driver), ``reprocess``,
3
+ and the three helpers it reaches (``_load_record``, ``preflight_inputs``,
4
+ ``tas_from_probe_housekeeping``). ``scripts/<name>.py`` stays the entry point scripts
5
+ and hooks name; each executes this package's source in its own namespace."""
@@ -0,0 +1,331 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """What else the machine was doing while a timing ran.
3
+
4
+ The rule: *a wall-clock figure is quotable only from a run whose harness recorded
5
+ the machine's other processes and load while it ran.* The incident behind it
6
+ : a 1.22x speed-up was withdrawn after its timed arms were found
7
+ to have run beside the full test suite -- 913.4 s against 168.2 s for the same
8
+ configuration -- and nothing the harness wrote could show it.
9
+
10
+ ``LoadRecorder`` is a context manager a timing harness wraps its timed window
11
+ in. It samples every process on the machine at entry, every ``interval``
12
+ seconds (default 60) from a daemon thread, and at exit, and records for each *other*
13
+ process (not this one, and by default not its descendants, which are the work
14
+ being timed) the CPU seconds it used inside the window. At exit it writes the
15
+ record as JSON (``path``) and prints one line::
16
+
17
+ LOAD RECORD: CLEAN|CONTAMINATED|UNRECORDED -- <why> (<path>)
18
+
19
+ **Threshold.** CONTAMINATED when any single other process averaged at least
20
+ ``PROCESS_CORE_LIMIT`` (0.25) of a core over the window, or all other
21
+ processes together at least ``TOTAL_CORE_LIMIT`` (1.0) core. That incident's
22
+ contaminant was a full test suite, which holds one core or more for its whole
23
+ run; a quarter core sustained over a window is well above an idle desktop's
24
+ background (antivirus, browser tabs) yet catches a competing python, Octave or
25
+ GDL run long before it can move a figure by 1.22x. The limits are recorded in
26
+ the JSON so a reader can re-judge from the per-process table.
27
+
28
+ **Cost.** One snapshot reads every process's CPU times, measured at about
29
+ 3.3 s of CPU on this Windows machine (531 processes, 2026-09-24), almost all
30
+ of it psutil's fallback for processes it may not open. At the default 60 s
31
+ interval that is ~0.06 core of load the recorder itself adds; it is this
32
+ process, so it is excluded from its own record, and it is stated here so a
33
+ reader can weigh it.
34
+
35
+ Needs ``psutil`` (in the venv). Without it the record says UNRECORDED and the
36
+ timing is not quotable under that rule -- the recorder never pretends.
37
+
38
+ **It never fails the run it wraps.** Any error while sampling or writing is
39
+ caught and the record says UNRECORDED with the reason; the timed work carries
40
+ on. ``enabled=False`` makes it a no-op that writes and prints nothing, for a
41
+ process that is itself a worker of a recorded parent (``run_flight.py --jobs``).
42
+ ``run_flight.py`` also passes ``enabled=False`` when the environment sets
43
+ ``ARRAYPROBE_LOAD_RECORD=off``: set only by ``make_demo_reference.py``'s v3.5 demo build,
44
+ whose time is a budget and never a quoted figure. A run with it off is not quotable.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import json
50
+ import os
51
+ import struct
52
+ import threading
53
+ import time
54
+ from pathlib import Path
55
+
56
+ try: # pragma: no cover - exercised by whichever branch the venv has
57
+ import psutil
58
+ except ImportError: # pragma: no cover
59
+ psutil = None
60
+
61
+ PROCESS_CORE_LIMIT = 0.25
62
+ TOTAL_CORE_LIMIT = 1.0
63
+ NOTABLE_CORE = 0.02 # processes below this average are summarised, not listed
64
+ # Windows kernel pseudo-processes: recorded (``kernel_avg_cores``) but kept out
65
+ # of the verdict. On the author's machine "System" (pid 4) alone averaged
66
+ # 1.87 core over a quiet 5 s with nothing launched (measured 2026-09-24), so
67
+ # judging it would call every run CONTAMINATED and the verdict would mean nothing.
68
+ KERNEL = {"System", "Registry", "Memory Compression", "Secure System"}
69
+
70
+
71
+ # FILETIME (100 ns ticks since 1601-01-01) to seconds since the Unix epoch,
72
+ # the constant psutil's C extension uses for the same conversion.
73
+ _EPOCH_AS_FILETIME = 116444736000000000
74
+ _SYSTEM_PROCESS_INFORMATION = 5
75
+ _STATUS_INFO_LENGTH_MISMATCH = 0xC0000004
76
+
77
+
78
+ def _table_snapshot_windows(
79
+ exclude: set[int]) -> dict[tuple[int, float], tuple[str, float]]:
80
+ """Read the whole process table once through ``NtQuerySystemInformation``.
81
+
82
+ psutil's Windows fallback for a process it may not open re-reads this
83
+ same table once per such process (~200 per snapshot, ~2-3 s); this reads
84
+ it once. Fields and units match psutil's: create time as FILETIME
85
+ converted to Unix seconds, user + kernel time in 100 ns units / 1e7, and
86
+ the image name. Layout offsets are those of 64-bit Windows; any other
87
+ layout raises, and the caller falls back to psutil.
88
+ """
89
+ import ctypes
90
+ import sys
91
+ if sys.platform != "win32": # also what lets mypy check WinDLL off Windows
92
+ raise OSError("table snapshot needs Windows")
93
+ if ctypes.sizeof(ctypes.c_void_p) != 8:
94
+ raise OSError("table snapshot needs 64-bit Windows")
95
+ ntdll = ctypes.WinDLL("ntdll")
96
+ fn = ntdll.NtQuerySystemInformation
97
+ fn.restype = ctypes.c_ulong
98
+ fn.argtypes = [ctypes.c_ulong, ctypes.c_void_p, ctypes.c_ulong,
99
+ ctypes.POINTER(ctypes.c_ulong)]
100
+ size = 1 << 20
101
+ for _ in range(8):
102
+ buf = ctypes.create_string_buffer(size)
103
+ need = ctypes.c_ulong(0)
104
+ status = fn(_SYSTEM_PROCESS_INFORMATION, buf, size, ctypes.byref(need))
105
+ if status == _STATUS_INFO_LENGTH_MISMATCH:
106
+ size = max(size * 2, need.value + (64 << 10))
107
+ continue
108
+ if status != 0:
109
+ raise OSError(f"NtQuerySystemInformation status 0x{status:08X}")
110
+ break
111
+ else:
112
+ raise OSError("NtQuerySystemInformation: buffer never large enough")
113
+ base = ctypes.addressof(buf)
114
+ raw = buf.raw
115
+ out: dict[tuple[int, float], tuple[str, float]] = {}
116
+ off = 0
117
+ while True:
118
+ nxt = struct.unpack_from("<I", raw, off)[0]
119
+ create, user, kernel = struct.unpack_from("<qqq", raw, off + 32)
120
+ name_len, _maxlen, name_ptr = struct.unpack_from("<HH4xQ", raw, off + 56)
121
+ pid = struct.unpack_from("<Q", raw, off + 80)[0]
122
+ if pid != 0 and pid not in exclude:
123
+ if pid == 4:
124
+ name = "System"
125
+ elif name_len and name_ptr:
126
+ if not base <= name_ptr < base + len(raw):
127
+ raise OSError("image name points outside the table buffer")
128
+ name = ctypes.wstring_at(name_ptr, name_len // 2)
129
+ else:
130
+ name = "?"
131
+ # psutil reports pid 4's create time as 0.0; match it so the key
132
+ # is the same whichever path took the snapshot.
133
+ ct = ((create - _EPOCH_AS_FILETIME) / 10000000.0
134
+ if create and pid != 4 else 0.0)
135
+ out[(pid, ct)] = (name or "?", (user + kernel) / 10000000.0)
136
+ if nxt == 0:
137
+ return out
138
+ off += nxt
139
+
140
+
141
+ def _snapshot(exclude: set[int]) -> dict[tuple[int, float], tuple[str, float]]:
142
+ if os.name == "nt":
143
+ try:
144
+ return _table_snapshot_windows(exclude)
145
+ except (OSError, ValueError, struct.error):
146
+ pass # fall back to psutil
147
+ return _psutil_snapshot(exclude)
148
+
149
+
150
+ def _psutil_snapshot(
151
+ exclude: set[int]) -> dict[tuple[int, float], tuple[str, float]]:
152
+ out: dict[tuple[int, float], tuple[str, float]] = {}
153
+ for p in psutil.process_iter(["pid", "name", "create_time", "cpu_times"]):
154
+ info = p.info
155
+ # pid 0 is the "System Idle Process" on Windows: its CPU time is idle time.
156
+ if info["pid"] in exclude or info["pid"] == 0 or info["cpu_times"] is None:
157
+ continue
158
+ ct = info["cpu_times"]
159
+ out[(info["pid"], info["create_time"] or 0.0)] = (
160
+ info["name"] or "?", float(ct.user + ct.system))
161
+ return out
162
+
163
+
164
+ class LoadRecorder:
165
+ """Record other processes' CPU use across a timed window; see module doc."""
166
+
167
+ def __init__(self, path, *, interval: float = 60.0,
168
+ exclude_descendants: bool = True, label: str = "",
169
+ enabled: bool = True):
170
+ self.path = Path(path)
171
+ self.enabled = enabled
172
+ self._error: str | None = None
173
+ self._thread: threading.Thread | None = None
174
+ self.interval = interval
175
+ self.exclude_descendants = exclude_descendants
176
+ self.label = label
177
+ self.record: dict = {}
178
+ self._stop = threading.Event()
179
+ self._lock = threading.Lock()
180
+ self._first: dict = {}
181
+ self._last: dict = {}
182
+ self._samples: list[dict] = []
183
+
184
+ # -- sampling -----------------------------------------------------------
185
+ def _exclude(self) -> set[int]:
186
+ me = psutil.Process(os.getpid())
187
+ ex = {me.pid}
188
+ if self.exclude_descendants:
189
+ try:
190
+ ex |= {c.pid for c in me.children(recursive=True)}
191
+ except psutil.Error:
192
+ pass
193
+ return ex
194
+
195
+ def _sample(self, first: bool = False) -> None:
196
+ snap = _snapshot(self._exclude())
197
+ with self._lock:
198
+ for key, (name, cpu) in snap.items():
199
+ if key not in self._first:
200
+ # Present at entry: its baseline is its CPU then. Born later:
201
+ # everything it used was used inside the window.
202
+ self._first[key] = (name, cpu if first else 0.0)
203
+ self._last[key] = (name, cpu)
204
+ load = None
205
+ if hasattr(psutil, "getloadavg"):
206
+ try:
207
+ load = psutil.getloadavg()[0]
208
+ except (OSError, psutil.Error):
209
+ load = None
210
+ self._samples.append({
211
+ "t": round(time.time(), 1),
212
+ "cpu_percent": psutil.cpu_percent(interval=None),
213
+ "loadavg_1min": load,
214
+ "n_processes": len(snap),
215
+ })
216
+
217
+ def _loop(self) -> None:
218
+ while not self._stop.wait(self.interval):
219
+ try:
220
+ self._sample()
221
+ except Exception: # noqa: BLE001 - a sampler must never kill the timed run
222
+ pass
223
+
224
+ # -- context ------------------------------------------------------------
225
+ def __enter__(self):
226
+ self._t0 = time.time()
227
+ self._p0 = time.perf_counter()
228
+ if psutil is None or not self.enabled:
229
+ return self
230
+ try:
231
+ psutil.cpu_percent(interval=None) # prime the system-wide counter
232
+ self._span0 = time.perf_counter()
233
+ self._sample(first=True)
234
+ self._thread = threading.Thread(target=self._loop, daemon=True)
235
+ self._thread.start()
236
+ except Exception as e: # noqa: BLE001 - never fail the wrapped run
237
+ self._error = f"entry snapshot failed: {type(e).__name__}: {e}"
238
+ return self
239
+
240
+ def __exit__(self, *exc):
241
+ if not self.enabled:
242
+ return False
243
+ try:
244
+ self._finish()
245
+ except Exception as e: # noqa: BLE001 - never fail the wrapped run
246
+ try:
247
+ print(f"LOAD RECORD: UNRECORDED -- recorder error "
248
+ f"{type(e).__name__}: {e} ({self.path})", flush=True)
249
+ except Exception: # noqa: BLE001
250
+ pass
251
+ return False
252
+
253
+ def _finish(self) -> None:
254
+ wall = time.perf_counter() - self._p0
255
+ rec: dict = {
256
+ "rule": "a timing records concurrent load",
257
+ "label": self.label,
258
+ "started": time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(self._t0)),
259
+ "wall_s": round(wall, 3),
260
+ "cpu_count": os.cpu_count(),
261
+ "interval_s": self.interval,
262
+ "exclude_descendants": self.exclude_descendants,
263
+ "process_core_limit": PROCESS_CORE_LIMIT,
264
+ "total_core_limit": TOTAL_CORE_LIMIT,
265
+ }
266
+ if psutil is None:
267
+ rec["verdict"] = "UNRECORDED"
268
+ rec["why"] = ("note: the load record is optional and needs psutil, from the "
269
+ "[extra] install; nothing was recorded")
270
+ elif self._error is not None:
271
+ self._stop.set()
272
+ rec["verdict"] = "UNRECORDED"
273
+ rec["why"] = self._error
274
+ else:
275
+ self._stop.set()
276
+ # __enter__ sets _error whenever it does not start the thread, and _finish runs only
277
+ # from __exit__ when enabled, so with psutil present and no error the thread exists.
278
+ assert self._thread is not None
279
+ self._thread.join(timeout=5)
280
+ try:
281
+ self._sample()
282
+ except Exception: # noqa: BLE001
283
+ pass
284
+ # CPU deltas run from the entry snapshot to the exit one, which
285
+ # bracket the timed window; divide by that span, not the window.
286
+ span = time.perf_counter() - self._span0
287
+ rec["sampled_span_s"] = round(span, 3)
288
+ rows = []
289
+ total = kernel = 0.0
290
+ with self._lock:
291
+ for key, (name, base) in self._first.items():
292
+ cpu = self._last[key][1] - base
293
+ if cpu <= 0:
294
+ continue
295
+ cores = cpu / max(span, 1e-9)
296
+ if name in KERNEL:
297
+ kernel += cpu
298
+ continue
299
+ total += cpu
300
+ if cores >= NOTABLE_CORE:
301
+ rows.append({"pid": key[0], "name": name,
302
+ "cpu_s": round(cpu, 2),
303
+ "avg_cores": round(cores, 3)})
304
+ samples = list(self._samples)
305
+ rows.sort(key=lambda r: -r["cpu_s"])
306
+ total_cores = total / max(span, 1e-9)
307
+ worst = rows[0] if rows else None
308
+ rec["other_processes"] = rows
309
+ rec["other_total_cpu_s"] = round(total, 2)
310
+ rec["other_total_avg_cores"] = round(total_cores, 3)
311
+ rec["kernel_avg_cores"] = round(kernel / max(span, 1e-9), 3)
312
+ rec["samples"] = samples
313
+ if worst and worst["avg_cores"] >= PROCESS_CORE_LIMIT:
314
+ rec["verdict"] = "CONTAMINATED"
315
+ rec["why"] = (f"{worst['name']} (pid {worst['pid']}) averaged "
316
+ f"{worst['avg_cores']:.2f} core")
317
+ elif total_cores >= TOTAL_CORE_LIMIT:
318
+ rec["verdict"] = "CONTAMINATED"
319
+ rec["why"] = f"other processes together averaged {total_cores:.2f} core"
320
+ else:
321
+ rec["verdict"] = "CLEAN"
322
+ rec["why"] = (f"other processes averaged {total_cores:.2f} core in "
323
+ f"total, none >= {PROCESS_CORE_LIMIT}")
324
+ rec["why"] += f"; kernel {rec['kernel_avg_cores']:.2f} core, not judged"
325
+ self.record = rec
326
+ try:
327
+ self.path.parent.mkdir(parents=True, exist_ok=True)
328
+ self.path.write_text(json.dumps(rec, indent=2) + "\n", encoding="utf-8")
329
+ except OSError as e:
330
+ print(f"LOAD RECORD: could not write {self.path}: {e}", flush=True)
331
+ print(f"LOAD RECORD: {rec['verdict']} -- {rec['why']} ({self.path})", flush=True)