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,300 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Per-particle distributions inside time windows of one proc file, active thresholds marked.
3
+
4
+ For the particles whose image-record header time (``Time``, HHMMSS) falls inside any window
5
+ (seconds of day, both ends included; parsed by :func:`arrayprobe.tune.sample.read_windows`), the
6
+ report gives:
7
+
8
+ * particles per second, all and at or above the review queues' size floor
9
+ (:data:`arrayprobe.tune.sample.SIZE_EDGES_MM`'s first edge), with the fraction of window seconds
10
+ holding more than 100 -- SODA-2's inter-arrival cutoff fit runs only for a period holding more
11
+ than 100 particles (``soda2_particlesort.pro:92``);
12
+ * inter-arrival time in log bins, and the fraction at or below the probe case's shattering
13
+ threshold (``defaultIntArrThresh``), overall and per size bin. The mark says whether the
14
+ case's gate (``applyIntArrThresh``) is on; where it is off the threshold has no effect on this
15
+ probe case. With no probe case given, no shattering threshold is marked;
16
+ * area ratio, ``image_area / (pi/4 * image_diam_minR^2)`` clipped at 1 as v3.5's
17
+ ``sizeDist.m:1161`` does, per size bin, with the fraction below the area-ratio cut. It is
18
+ computed from the proc file's own diameter, so a size ``sizeDist`` later corrects (the hollow
19
+ 'H' division) differs;
20
+ * ``image_axis_ratio`` per size bin, with the fraction above each image-stage aspect-ratio
21
+ ceiling. The reject computes its own aspect ratio, so the reject-code counts, not this
22
+ fraction, say what the reject did;
23
+ * ``image_auto_reject`` codes named in words, ``holroyd_habit`` codes and the hollow fraction,
24
+ per size bin.
25
+
26
+ Diameters that are not finite (zero-area particles among them) get their own bin rather than
27
+ falling into the top one. Every threshold mark carries the place its value was read from; the
28
+ report states no expected value. Read-only: nothing here computes or changes a product.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import math
33
+ from collections.abc import Sequence
34
+ from pathlib import Path
35
+ from typing import Any
36
+
37
+ import numpy as np
38
+
39
+ from arrayprobe.matlab_compat import REJECT_CODE_WORDS
40
+ from arrayprobe.tune import sample
41
+
42
+ __all__ = [
43
+ "SIZE_EDGES_MM",
44
+ "IA_EDGES_S",
45
+ "PERCENTILES",
46
+ "PER_SECOND_LIMIT",
47
+ "NONFINITE_LABEL",
48
+ "BELOW_FLOOR_LABEL",
49
+ "COLUMNS",
50
+ "threshold_marks",
51
+ "size_bins",
52
+ "reject_code_counts",
53
+ "habit_code_counts",
54
+ "per_second_counts",
55
+ "area_ratio",
56
+ "report",
57
+ "read_proc_columns",
58
+ "summary_lines",
59
+ ]
60
+
61
+ #: Size-bin edges, mm; the first bin starts at zero and the last is open-ended.
62
+ SIZE_EDGES_MM: tuple[float, ...] = (0.0, 0.055, 0.1, 0.2, 0.4, 1.0, float("inf"))
63
+ #: Inter-arrival histogram edges, s: 35 log-spaced bins from 1e-7 s to 1 s.
64
+ IA_EDGES_S = np.logspace(-7, 0, 36)
65
+ PERCENTILES = (10, 50, 90)
66
+ #: ``soda2_particlesort.pro:92``: the cutoff fit needs ``total(...) gt 100`` in a period.
67
+ PER_SECOND_LIMIT = 100
68
+ NONFINITE_LABEL = "non-finite diameter"
69
+ BELOW_FLOOR_LABEL = "below the first edge"
70
+ #: The proc-file columns read.
71
+ COLUMNS = ("Time", "image_diam_minR", "image_area", "image_auto_reject", "image_axis_ratio",
72
+ "inter_arrival", "image_hollow", "holroyd_habit")
73
+
74
+ _SIZEDIST_M = "UIOPS-v3.5/joefinlon-UIOPS-039be82/sizeDist.m"
75
+ _REJECT_M = "UIOPS-v3.5/joefinlon-UIOPS-039be82/calculate_reject_unified.m"
76
+
77
+
78
+ def threshold_marks(probe_case: Any = None, area_ratio_z: float | None = None) -> dict:
79
+ """The thresholds that act on the reported quantities, each with where its value came from.
80
+
81
+ ``area_ratio_z`` is a run's ``--area-ratio-z``; ``None`` takes v3.5's stock cut. The
82
+ shattering mark comes from ``probe_case`` through
83
+ :func:`arrayprobe.tune.settings.resolve_probe_defaults`; ``None`` marks none.
84
+ """
85
+ from arrayprobe.tune import settings
86
+ from arrayprobe_uiops import measure as v35_measure
87
+ from arrayprobe_uiops import sizedist as v35_sizedist
88
+
89
+ by_name = settings.settings_by_name()
90
+ if area_ratio_z is None:
91
+ ar = {"value": float(v35_sizedist.AREA_RATIO_Z),
92
+ "source": f"arrayprobe_uiops.sizedist.AREA_RATIO_Z ({_SIZEDIST_M}:1162)"}
93
+ else:
94
+ ar = {"value": float(area_ratio_z), "source": "given (--area-ratio-z)"}
95
+ ar["acts"] = "sizeDist rejects a particle whose area ratio is below this value (code 'z')"
96
+
97
+ rc = v35_measure.STOCK_V35_REJECT_CONFIG
98
+ marks: dict[str, Any] = {
99
+ "area_ratio_z": ar,
100
+ "max_comp_img_ar": {
101
+ "value": float(rc.max_comp_img_ar),
102
+ "source": f"arrayprobe_uiops.measure.STOCK_V35_REJECT_CONFIG ({_REJECT_M}:66)",
103
+ "acts": by_name["max_comp_img_ar"].does},
104
+ "max_edge_img_ar": {
105
+ "value": float(rc.max_edge_img_ar),
106
+ "source": f"arrayprobe_uiops.measure.STOCK_V35_REJECT_CONFIG ({_REJECT_M}:65)",
107
+ "acts": by_name["max_edge_img_ar"].does},
108
+ }
109
+ if probe_case is None:
110
+ marks["shattering"] = {"value": None, "probe_case": None,
111
+ "effect": "not marked: no probe case given (--probe-case)"}
112
+ else:
113
+ pd = settings.resolve_probe_defaults(probe_case)
114
+ name = probe_case if isinstance(probe_case, str) else None
115
+ marks["shattering"] = {
116
+ "value": float(pd.defaultIntArrThresh),
117
+ "probe_case": name,
118
+ "applyIntArrThresh": int(pd.applyIntArrThresh),
119
+ "effect": by_name["defaultIntArrThresh"].effect(pd).reason,
120
+ "source": "the probe case's defaultIntArrThresh "
121
+ "(arrayprobe.tune.settings.resolve_probe_defaults)",
122
+ "acts": by_name["defaultIntArrThresh"].does}
123
+ return marks
124
+
125
+
126
+ def size_bins(diam_mm, edges: Sequence[float] = SIZE_EDGES_MM) -> tuple[np.ndarray, list[str]]:
127
+ """Bin index per particle and the labels; the last two bins are below-floor and non-finite.
128
+
129
+ ``np.digitize`` alone would put NaN and inf in the top bin; here they get their own.
130
+ """
131
+ d = np.asarray(diam_mm, float)
132
+ labels = sample.bin_labels(edges)
133
+ idx = sample.assign_bins(d, edges)
134
+ idx[idx < 0] = len(labels)
135
+ idx[~np.isfinite(d)] = len(labels) + 1
136
+ return idx, labels + [BELOW_FLOOR_LABEL, NONFINITE_LABEL]
137
+
138
+
139
+ def _code_key(v: int) -> str:
140
+ return chr(v) if 32 <= v < 127 else f"#{v}"
141
+
142
+
143
+ def reject_code_counts(codes) -> dict[str, dict]:
144
+ """``{code: {"n", "meaning"}}``, the meaning from :data:`REJECT_CODE_WORDS`."""
145
+ vals, n = np.unique(np.asarray(codes).astype(np.int64), return_counts=True)
146
+ out = {}
147
+ for v, c in zip(vals.tolist(), n.tolist(), strict=True):
148
+ key = _code_key(v)
149
+ out[key] = {"n": int(c), "meaning": REJECT_CODE_WORDS.get(key, "not a known reject code")}
150
+ return out
151
+
152
+
153
+ def habit_code_counts(codes) -> dict[str, int]:
154
+ """``{habit code: n}``."""
155
+ vals, n = np.unique(np.asarray(codes).astype(np.int64), return_counts=True)
156
+ return {_code_key(v): int(c) for v, c in zip(vals.tolist(), n.tolist(), strict=True)}
157
+
158
+
159
+ def per_second_counts(sod, windows: Sequence[tuple[int, int]]) -> np.ndarray:
160
+ """Particles in each distinct window second, in order (a second in two windows counts once)."""
161
+ secs = np.unique(np.concatenate([np.arange(lo, hi + 1) for lo, hi in windows]))
162
+ s = np.sort(np.asarray(sod, np.int64))
163
+ return np.searchsorted(s, secs, "right") - np.searchsorted(s, secs, "left")
164
+
165
+
166
+ def area_ratio(image_area, diam_mm) -> np.ndarray:
167
+ """``image_area / (pi/4 * d^2)``, clipped at 1 by v3.5's own ``clip_area_ratio``."""
168
+ from arrayprobe_uiops.sizedist import clip_area_ratio
169
+
170
+ a = np.asarray(image_area, float)
171
+ d = np.asarray(diam_mm, float)
172
+ with np.errstate(divide="ignore", invalid="ignore"):
173
+ return clip_area_ratio(a / (np.pi / 4 * d ** 2))
174
+
175
+
176
+ def _pct(x) -> dict[str, float]:
177
+ x = np.asarray(x, float)
178
+ return {str(p): float(np.percentile(x, p)) for p in PERCENTILES} if x.size else {}
179
+
180
+
181
+ def _frac(mask) -> float | None:
182
+ mask = np.asarray(mask, bool)
183
+ return float(mask.mean()) if mask.size else None
184
+
185
+
186
+ def report(cols: dict[str, np.ndarray], *, windows: Sequence[tuple[int, int]],
187
+ marks: dict, edges: Sequence[float] = SIZE_EDGES_MM, proc_name: str = "") -> dict:
188
+ """The distributions for the particles of ``cols`` (the :data:`COLUMNS`) inside ``windows``."""
189
+ sod_all = sample.hhmmss_to_sod(np.asarray(cols["Time"]).reshape(-1))
190
+ idx = np.flatnonzero(sample.in_windows(sod_all, windows))
191
+
192
+ def get(name, dtype=None):
193
+ a = np.asarray(cols[name]).reshape(-1)[idx]
194
+ return a.astype(dtype) if dtype is not None else a
195
+
196
+ sod = sod_all[idx]
197
+ diam = get("image_diam_minR", float)
198
+ ia = get("inter_arrival", float)
199
+ axis = get("image_axis_ratio", float)
200
+ arat = area_ratio(get("image_area", float), diam)
201
+ rej, habit, hollow = get("image_auto_reject"), get("holroyd_habit"), get("image_hollow")
202
+ sbin, labels = size_bins(diam, edges)
203
+
204
+ floor = sample.SIZE_EDGES_MM[0]
205
+ pa = per_second_counts(sod, windows)
206
+ pb = per_second_counts(sod[diam >= floor], windows)
207
+ ia_thr = marks["shattering"]["value"]
208
+ z = marks["area_ratio_z"]["value"]
209
+ axis_marks = {k: marks[k]["value"] for k in ("max_comp_img_ar", "max_edge_img_ar")}
210
+
211
+ fin = np.isfinite(ia) & (ia > 0)
212
+ ia_block: dict[str, Any] = {
213
+ "edges_s": IA_EDGES_S.tolist(),
214
+ "counts": np.histogram(ia[fin], IA_EDGES_S)[0].tolist(),
215
+ "nonpositive_or_nonfinite": int((~fin).sum()),
216
+ "threshold_s": ia_thr,
217
+ "threshold_effect": marks["shattering"]["effect"],
218
+ }
219
+ if ia_thr is not None:
220
+ ia_block["fraction_at_or_below_threshold"] = _frac(ia[fin] <= ia_thr)
221
+ ia_block["fraction_at_or_below_threshold_by_size"] = {
222
+ lab: _frac(ia[fin & (sbin == b)] <= ia_thr) for b, lab in enumerate(labels)}
223
+
224
+ by_size: dict[str, dict] = {}
225
+ for b, lab in enumerate(labels):
226
+ m = sbin == b
227
+ if not m.any():
228
+ by_size[lab] = {"n": 0}
229
+ continue
230
+ ar = arat[m][np.isfinite(arat[m])]
231
+ ax = axis[m][np.isfinite(axis[m])]
232
+ by_size[lab] = {
233
+ "n": int(m.sum()),
234
+ "area_ratio_percentiles": _pct(ar),
235
+ "area_ratio_not_finite": int(m.sum() - ar.size),
236
+ "area_ratio_fraction_below_cut": _frac(ar < z),
237
+ "area_ratio_hist_0_to_1_by_0.1": np.histogram(ar, np.linspace(0, 1, 11))[0].tolist(),
238
+ "axis_ratio_percentiles": _pct(ax),
239
+ **{f"axis_ratio_fraction_above_{k}": _frac(ax > v) for k, v in axis_marks.items()},
240
+ "reject_codes": reject_code_counts(rej[m]),
241
+ "habit_codes": habit_code_counts(habit[m]),
242
+ "hollow_fraction": _frac(hollow[m] == 1),
243
+ }
244
+
245
+ return {
246
+ "tool": "arrayprobe tune distributions",
247
+ "proc_file": proc_name,
248
+ "window_clock": sample.WINDOW_CLOCK,
249
+ "windows_s_of_day_inclusive": [list(w) for w in windows],
250
+ "window_seconds": int(pa.size),
251
+ "n_particles_file": int(sod_all.size),
252
+ "n_particles_in_windows": int(idx.size),
253
+ "size_edges_mm": [e if math.isfinite(e) else "inf" for e in edges],
254
+ "thresholds": marks,
255
+ "per_second": {
256
+ "all": _pct(pa),
257
+ f"at_or_above_{floor:g}mm": _pct(pb),
258
+ f"fraction_of_window_seconds_over_{PER_SECOND_LIMIT}_all": _frac(pa > PER_SECOND_LIMIT),
259
+ "limit_source": "soda2_particlesort.pro:92 (the inter-arrival cutoff fit needs more "
260
+ f"than {PER_SECOND_LIMIT} particles in a period)",
261
+ },
262
+ "inter_arrival": ia_block,
263
+ "by_size": by_size,
264
+ }
265
+
266
+
267
+ def read_proc_columns(path: Path) -> dict[str, np.ndarray]:
268
+ """The :data:`COLUMNS` of a proc file, flattened, raw (no masking or scaling)."""
269
+ import netCDF4
270
+
271
+ with netCDF4.Dataset(path) as d:
272
+ d.set_auto_mask(False)
273
+ missing = [c for c in COLUMNS if c not in d.variables]
274
+ if missing:
275
+ raise ValueError(f"{Path(path).name} has no {', '.join(missing)}")
276
+ return {c: np.asarray(d[c][:]).reshape(-1) for c in COLUMNS}
277
+
278
+
279
+ def summary_lines(rep: dict) -> list[str]:
280
+ """A few lines for the terminal: counts, the marks and, per size bin, the cut fractions."""
281
+ th = rep["thresholds"]
282
+ lines = [f"{rep['n_particles_in_windows']} of {rep['n_particles_file']} particles in "
283
+ f"{len(rep['windows_s_of_day_inclusive'])} windows ({rep['window_seconds']} s)"]
284
+ sh = th["shattering"]
285
+ lines.append(f"shattering threshold: {sh['value']} s -- {sh['effect']}")
286
+ if sh["value"] is not None:
287
+ lines.append(" inter-arrival at or below it: "
288
+ f"{rep['inter_arrival']['fraction_at_or_below_threshold']}")
289
+ lines.append(f"area-ratio cut {th['area_ratio_z']['value']:g}; aspect-ratio ceilings "
290
+ f"{th['max_comp_img_ar']['value']:g} (contained), "
291
+ f"{th['max_edge_img_ar']['value']:g} (edge)")
292
+ for lab, r in rep["by_size"].items():
293
+ if not r["n"]:
294
+ continue
295
+ below = r["area_ratio_fraction_below_cut"]
296
+ below_s = "n/a" if below is None else f"{below:.3f}"
297
+ codes = ", ".join(f"{k} {v['n']}" for k, v in r["reject_codes"].items())
298
+ lines.append(f" {lab:>20s}: n={r['n']:>8d} area ratio below cut {below_s} "
299
+ f"codes {codes}")
300
+ return lines
@@ -0,0 +1,243 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Review queues drawn from one proc file: particles inside time windows, per size bin.
3
+
4
+ From a proc file's three columns -- the image record's header time (``Time``, HHMMSS),
5
+ ``image_diam_minR`` (mm) and ``image_auto_reject`` -- the particles whose record time falls inside
6
+ any of the given windows (seconds of day, both ends included) and whose size is at least the first
7
+ size edge are split into size bins, and up to ``per_bin`` of each bin are drawn at random with a
8
+ fixed seed. Two queues go into one file:
9
+
10
+ * ``<stem>-accepted-n<per_bin>-s<seed>``: only the image codes ``sizeDist`` counts as accepted
11
+ (:data:`ACCEPTED_CODES`);
12
+ * ``<stem>-all-n<per_bin>-s<seed>``: every image code, drawn independently of the first, so a
13
+ particle can sit in both; the coverage block counts the overlap.
14
+
15
+ The file written has the shape :func:`arrayprobe.triage_server._load_queue_file` reads, with each
16
+ queue's coverage under ``_coverage``, and is merged into an existing queue file rather than
17
+ replacing it. Read-only towards the proc file: nothing here computes or changes a product.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import re
23
+ from collections.abc import Sequence
24
+ from pathlib import Path
25
+
26
+ import numpy as np
27
+
28
+ #: Size-bin edges, mm. The first edge is the size floor; the last bin is open-ended.
29
+ SIZE_EDGES_MM: tuple[float, ...] = (0.055, 0.1, 0.2, 0.4, 1.0, float("inf"))
30
+ PER_BIN = 40
31
+ SEED = 20260930
32
+ #: The image codes ``sizeDist`` counts as accepted.
33
+ ACCEPTED_CODES = "0HhuR"
34
+ #: The key the coverage blocks go under; the triage server skips any key starting with ``_``.
35
+ COVERAGE_KEY = "_coverage"
36
+ WINDOW_CLOCK = "record header Time (HHMMSS)"
37
+
38
+ _WINDOW_RE = re.compile(r"(\d+)\s*-\s*(\d+)")
39
+ _SECONDS_PER_DAY = 86400
40
+
41
+ Windows = tuple[tuple[int, int], ...]
42
+
43
+
44
+ def parse_windows(text: str) -> Windows:
45
+ """Every ``lo-hi`` pair (seconds of day) in ``text``, in order.
46
+
47
+ Pairs may be separated by commas, spaces or new lines; a line starting with ``#`` is a comment.
48
+ Refuses a window that ends before it starts, a second outside the day, and text with no window.
49
+ """
50
+ body = "\n".join(line for line in text.splitlines() if not line.lstrip().startswith("#"))
51
+ out = []
52
+ for a, b in _WINDOW_RE.findall(body):
53
+ lo, hi = int(a), int(b)
54
+ if hi < lo:
55
+ raise ValueError(f"window {lo}-{hi} ends before it starts")
56
+ if hi >= _SECONDS_PER_DAY:
57
+ raise ValueError(f"window {lo}-{hi} is past the end of the day (86399 s)")
58
+ out.append((lo, hi))
59
+ if not out:
60
+ raise ValueError(f"no lo-hi window (seconds of day) in {text!r}")
61
+ return tuple(out)
62
+
63
+
64
+ def read_windows(spec: str | Path) -> Windows:
65
+ """Windows from a file holding ``lo-hi`` pairs, or from the pairs given directly."""
66
+ path = Path(spec)
67
+ try:
68
+ is_file = path.is_file()
69
+ except OSError: # a long window list is not a valid path on every platform
70
+ is_file = False
71
+ if is_file:
72
+ return parse_windows(path.read_text(encoding="utf-8"))
73
+ return parse_windows(str(spec))
74
+
75
+
76
+ def hhmmss_to_sod(hhmmss) -> np.ndarray:
77
+ """A proc file's ``Time`` (HHMMSS) to seconds of day, as int64."""
78
+ t = np.asarray(hhmmss, np.int64)
79
+ return (t // 10000) * 3600 + ((t // 100) % 100) * 60 + t % 100
80
+
81
+
82
+ def in_windows(sod, windows: Sequence[tuple[int, int]]) -> np.ndarray:
83
+ """True where a second of day falls inside any window, both ends included."""
84
+ sod = np.asarray(sod, np.int64)
85
+ mask = np.zeros(sod.shape, bool)
86
+ for lo, hi in windows:
87
+ mask |= (sod >= lo) & (sod <= hi)
88
+ return mask
89
+
90
+
91
+ def bin_labels(edges: Sequence[float] = SIZE_EDGES_MM) -> list[str]:
92
+ """``"55-100um"``-style labels, one per bin; the last is open-ended."""
93
+ out = []
94
+ for lo, hi in zip(edges[:-1], edges[1:], strict=True):
95
+ top = "inf" if hi == float("inf") else f"{hi * 1000:g}"
96
+ out.append(f"{lo * 1000:g}-{top}um")
97
+ return out
98
+
99
+
100
+ def assign_bins(diam_mm, edges: Sequence[float] = SIZE_EDGES_MM) -> np.ndarray:
101
+ """Bin index per particle, ``[lo, hi)``; -1 below the floor or not a number."""
102
+ d = np.asarray(diam_mm, float)
103
+ idx = np.digitize(d, edges) - 1
104
+ idx[~np.isfinite(d) | (d < edges[0])] = -1
105
+ return idx
106
+
107
+
108
+ def check_edges(edges: Sequence[float]) -> tuple[float, ...]:
109
+ """``edges`` as a tuple, refused unless there are at least two and they strictly increase."""
110
+ e = tuple(float(x) for x in edges)
111
+ if len(e) < 2 or any(b <= a for a, b in zip(e[:-1], e[1:], strict=True)):
112
+ raise ValueError(f"size edges must be at least two strictly increasing values, got {e}")
113
+ return e
114
+
115
+
116
+ def draw(time_hhmmss, diam_mm, reject, *, windows: Sequence[tuple[int, int]],
117
+ edges: Sequence[float] = SIZE_EDGES_MM, per_bin: int = PER_BIN, seed: int = SEED,
118
+ accepted_codes: str | None = ACCEPTED_CODES) -> list[dict]:
119
+ """Per bin: ``{"bin", "available", "requested", "taken", "under_filled", "indices"}``.
120
+
121
+ ``accepted_codes=None`` keeps every image code. One generator, bins drawn in order, so the
122
+ same arguments give the same queue on any machine.
123
+ """
124
+ if per_bin < 1:
125
+ raise ValueError("per_bin must be at least 1")
126
+ t = np.asarray(time_hhmmss).reshape(-1)
127
+ d = np.asarray(diam_mm, float).reshape(-1)
128
+ r = np.asarray(reject).reshape(-1)
129
+ if not (t.size == d.size == r.size):
130
+ raise ValueError("Time, image_diam_minR and image_auto_reject differ in length")
131
+ eligible = in_windows(hhmmss_to_sod(t), windows)
132
+ if accepted_codes is not None:
133
+ eligible &= np.isin(r, [ord(c) for c in accepted_codes])
134
+ bins = assign_bins(d, edges)
135
+ rng = np.random.default_rng(seed)
136
+ out = []
137
+ for b, label in enumerate(bin_labels(edges)):
138
+ cand = np.flatnonzero(eligible & (bins == b))
139
+ if cand.size <= per_bin:
140
+ pick = sorted(cand.tolist())
141
+ else:
142
+ pick = sorted(rng.choice(cand, size=per_bin, replace=False).tolist())
143
+ out.append({"bin": label, "available": int(cand.size), "requested": per_bin,
144
+ "taken": len(pick), "under_filled": len(pick) < per_bin, "indices": pick})
145
+ return out
146
+
147
+
148
+ def queue_items(strata, time_hhmmss, diam_mm, reject, flight: str,
149
+ context: str = "window") -> list[dict]:
150
+ """Queue entries in bin order, each with a note the reviewer sees beside the image."""
151
+ items = []
152
+ for s in strata:
153
+ for i in s["indices"]:
154
+ code = int(reject[i])
155
+ code_s = chr(code) if 32 <= code < 127 else f"#{code}"
156
+ size_um = float(diam_mm[i]) * 1000
157
+ items.append({"flight": flight, "particle_index": int(i), "size_bin": s["bin"],
158
+ "note": f"{context}, {s['bin']}, minR {size_um:.0f} um, "
159
+ f"code {code_s}, record time {int(time_hhmmss[i]):06d}"})
160
+ return items
161
+
162
+
163
+ def write_queues(path: Path, queues: dict[str, list[dict]], coverage: dict[str, dict]) -> Path:
164
+ """Add these queues and their coverage to ``path``, keeping every other queue in it."""
165
+ path = Path(path)
166
+ data: dict = {}
167
+ if path.exists():
168
+ data = json.loads(path.read_text(encoding="utf-8"))
169
+ if not isinstance(data, dict):
170
+ raise ValueError(f"{path} is not a queue file; refusing to replace it")
171
+ data.update(queues)
172
+ data.setdefault(COVERAGE_KEY, {}).update(coverage)
173
+ path.parent.mkdir(parents=True, exist_ok=True)
174
+ path.write_text(json.dumps(data, indent=1, sort_keys=True), encoding="utf-8")
175
+ return path
176
+
177
+
178
+ def build(proc_name: str, time_hhmmss, diam_mm, reject, *, route: str, flight: str,
179
+ windows: Sequence[tuple[int, int]], queue_stem: str,
180
+ edges: Sequence[float] = SIZE_EDGES_MM, per_bin: int = PER_BIN, seed: int = SEED,
181
+ accepted_codes: str = ACCEPTED_CODES, tool: str = "arrayprobe tune sample",
182
+ context: str = "window") -> tuple[dict, dict]:
183
+ """The two queues (accepted codes only, every code) and their coverage blocks."""
184
+ in_win = in_windows(hhmmss_to_sod(time_hhmmss), windows)
185
+ queues, coverage, picked = {}, {}, {}
186
+ for kind, codes in (("accepted", accepted_codes), ("all", None)):
187
+ strata = draw(time_hhmmss, diam_mm, reject, windows=windows, edges=edges,
188
+ per_bin=per_bin, seed=seed, accepted_codes=codes)
189
+ name = f"{queue_stem}-{kind}-n{per_bin}-s{seed}"
190
+ queues[name] = queue_items(strata, time_hhmmss, diam_mm, reject, flight, context)
191
+ picked[kind] = {i for s in strata for i in s["indices"]}
192
+ coverage[name] = {
193
+ "tool": tool, "flight": flight,
194
+ "proc_file": proc_name, "route": route, "seed": seed, "per_bin": per_bin,
195
+ "windows_s_of_day_inclusive": [list(w) for w in windows],
196
+ "size_floor_mm": edges[0], "size_edges_mm": [e if e != float("inf") else "inf"
197
+ for e in edges],
198
+ "only_accepted": codes is not None, "accepted_codes": codes,
199
+ "window_clock": WINDOW_CLOCK,
200
+ "n_particles_file": int(np.asarray(time_hhmmss).size),
201
+ "n_particles_in_windows": int(in_win.sum()),
202
+ "n_particles": sum(s["taken"] for s in strata),
203
+ "strata": [{k: v for k, v in s.items() if k != "indices"} for s in strata],
204
+ }
205
+ overlap = len(picked["accepted"] & picked["all"])
206
+ for name in coverage:
207
+ coverage[name]["overlap_between_the_two_queues"] = overlap
208
+ return queues, coverage
209
+
210
+
211
+ def read_proc_columns(path: Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
212
+ """``Time``, ``image_diam_minR`` and ``image_auto_reject`` from a proc file, flattened, raw."""
213
+ import netCDF4
214
+
215
+ with netCDF4.Dataset(path) as d:
216
+ d.set_auto_mask(False)
217
+ t = np.asarray(d["Time"][:]).reshape(-1)
218
+ diam = np.asarray(d["image_diam_minR"][:], float).reshape(-1)
219
+ rej = np.asarray(d["image_auto_reject"][:]).reshape(-1)
220
+ return t, diam, rej
221
+
222
+
223
+ def flight_from_proc_name(name: str) -> str:
224
+ """``proc.base180215125340.H.nc`` -> ``base180215125340.H`` (the triage server's flight)."""
225
+ stem = Path(name).name
226
+ if stem.startswith("proc."):
227
+ stem = stem[len("proc."):]
228
+ if stem.endswith(".nc"):
229
+ stem = stem[:-len(".nc")]
230
+ return stem
231
+
232
+
233
+ def summary_lines(coverage: dict[str, dict]) -> list[str]:
234
+ """Per queue: particles taken, how many were in the windows, and each bin's fill."""
235
+ lines = []
236
+ for name, cov in coverage.items():
237
+ lines.append(f"{name}: {cov['n_particles']} particles "
238
+ f"({cov['n_particles_in_windows']} of {cov['n_particles_file']} in windows)")
239
+ for s in cov["strata"]:
240
+ flag = " UNDER-FILLED" if s["under_filled"] else ""
241
+ lines.append(f" {s['bin']:>12s} available {s['available']:8d} "
242
+ f"taken {s['taken']:3d}{flag}")
243
+ return lines