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/render.py ADDED
@@ -0,0 +1,728 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Track V -- particle visualisation. Not a port stage: new capability UIOOPS
3
+ does not have, built on files the S2-S4 chain already produces.
4
+
5
+ **The one dependency, already satisfied by S3.** A proc file records
6
+ ``parent_rec_num`` and ``position`` for every particle: which image record it
7
+ came from, and the first/last slice (1-based, inclusive) within that record's
8
+ 1700-slice block. Together with the record's raw ``data`` in the source image
9
+ file, those two reconstruct the exact ``c`` matrix ``imgproc_sm`` saw --
10
+ transcribed here from ``imgProc_sm.m:266-268`` (``ind_matrix = 65535 -
11
+ data(start:j-1,:)``, ``c = dec2bin_concat(...)``), not imported from
12
+ ``imgproc.py``: the reconstruction is four lines, and duplicating it here
13
+ keeps this module from being able to perturb S3's own validated code path by
14
+ accident. See the plan's "Enhancement track V" section for the open scope
15
+ questions this was built against.
16
+
17
+ Convention throughout: ``c`` is a ``(n_slices, n_diodes)`` boolean array,
18
+ ``True`` where a diode was **shadowed** (the particle silhouette) -- matching
19
+ ``c == '0'`` at every UIOOPS call site (``imgProc_sm.m:63`` and the CGAL_minR
20
+ shim's own note), just as a boolean rather than a char array.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from typing import Any
26
+
27
+ import numpy as np
28
+
29
+ from .matlab_compat import HOLROYD_HABITS, REJECT_CODES, dec2bin_concat
30
+
31
+ __all__ = [
32
+ "DRAWABLE_PROBES",
33
+ "reconstruct_particle_image",
34
+ "particle_info",
35
+ "crop_to_content",
36
+ "render_particle",
37
+ "render_contact_sheet",
38
+ "render_gallery_html",
39
+ "particle_thumbnail_png",
40
+ "unverified_placeholder_png",
41
+ "grid_shape",
42
+ "wrap_title",
43
+ "record_slice_um",
44
+ "particle_grid",
45
+ ]
46
+
47
+ _HABIT_BY_CODE = {v: k for k, v in HOLROYD_HABITS.items()}
48
+ _REJECT_BY_CODE = {v: k for k, v in REJECT_CODES.items()}
49
+
50
+
51
+ #: Probes whose framing this module draws. 2DC/2DP stay refused by name even
52
+ #: though ``reconstruct_particle_image`` now applies ``image_slice_offset``
53
+ #: (2026-09-20 fix; their offset is 1, ``data(start+1:j-1,:)``, ``:555``): the
54
+ #: only oracle checked is ``tests/data/s7c_2dc_octave_golden.nc``, a two-
55
+ #: particle hand-built synthetic file, which settles that the *row selection*
56
+ #: now matches ``SliceCount`` exactly (it does not store the pixel content of
57
+ #: ``c`` itself, only per-particle stats), and says nothing about a real 2DC/
58
+ #: 2DP campaign file. That gap, not the offset arithmetic, is why the
59
+ #: exclusion stays -- see ``test_render.py::TestReconstructOffset`` for the
60
+ #: golden comparison this rests on.
61
+ DRAWABLE_PROBES = ("2DS", "HVPS", "CIP", "PIP", "Fast2DC")
62
+
63
+
64
+ def reconstruct_particle_image(image_ds, proc_ds, particle_index: int, *,
65
+ probe: str = "2DS") -> np.ndarray:
66
+ """The boolean ``(n_slices, n_diodes)`` silhouette for one particle.
67
+
68
+ ``image_ds``/``proc_ds`` are open ``netCDF4.Dataset`` handles for the
69
+ image file and ``proc.*.nc`` (the *same* flight -- nothing here
70
+ checks that they match, since the caller already has both open and a
71
+ mismatch would show up immediately as garbage).
72
+
73
+ ``particle_index`` is 0-based into the proc file's particle axis, i.e.
74
+ the row index the rest of the proc file's per-particle variables use
75
+ directly (``image_width[particle_index]`` etc.).
76
+
77
+ ``probe`` selects the framing ``imgproc`` uses for that probe, read from
78
+ :data:`arrayprobe.constants.IMGPROC_CONFIG` rather than restated: 2D-S and
79
+ HVPS invert 16-bit words (``65535 - data``, ``:562``); CIP/PIP/Fast2DC use
80
+ 8-bit words as stored (``:556,:559``). The default is the 2D-S framing, so
81
+ a call without ``probe`` draws a 2D-S image; a CIP image needs
82
+ ``probe="CIP"``, or it comes back as an inverted 128-column picture.
83
+ """
84
+ from .constants import IMGPROC_CONFIG
85
+
86
+ if probe not in DRAWABLE_PROBES:
87
+ raise ValueError(f"probe {probe!r} is not drawable here; drawable: {DRAWABLE_PROBES}")
88
+ cfg = IMGPROC_CONFIG[probe]
89
+ parent_rec = int(proc_ds.variables["parent_rec_num"][particle_index]) # 1-based
90
+ start, end = (int(v) for v in proc_ds.variables["position"][particle_index])
91
+ block = image_ds.variables["data"][parent_rec - 1, :, :] # (1700, n_words)
92
+ # imgproc.py:893's slice_start -- the proc file's stored ``start`` is the
93
+ # raw pre-offset value (``images.position(kk,:) = [start, j-1]``,
94
+ # imgProc_sm.m:575), so the read side must add the same
95
+ # ``cfg.image_slice_offset`` the write side added, or a probe with a
96
+ # nonzero offset (2DC/2DP: 1, imgProc_sm.m:555) gains one extra row at the
97
+ # front -- a header/timing slice imgProc_sm.m never put in the particle.
98
+ # For 2D-S/HVPS (offset 0) this is exactly the prior ``start - 1`` and
99
+ # changes nothing (test_render.py::TestOffsetIsNoopFor2DS).
100
+ slice_start = start - 1 + cfg.image_slice_offset
101
+ data_slice = np.asarray(block[slice_start:end, :]) # :266's data(start:j-1,:)
102
+ # :266 / :562, inverted so '1' bits are lit (2D-S, HVPS); :556,:559 as stored.
103
+ ind_matrix = 65535 - data_slice if cfg.image_invert else data_slice
104
+ c = dec2bin_concat(ind_matrix, cfg.image_word_bits) # :267-268, '0'/'1' per bit
105
+ return c == ord("0") # '0' == shadowed, per the module docstring
106
+
107
+
108
+ def particle_info(proc_ds, particle_index: int) -> dict:
109
+ """The per-particle scalars worth showing alongside the image."""
110
+ def get(name, default=None):
111
+ """One per-particle scalar as a float, or ``default`` if the file has no
112
+ such variable.
113
+
114
+ Absence is normal rather than exceptional here: a proc file's variable
115
+ set depends on the probe type and on ``iRectEllipse``, so a display
116
+ helper that raised on a missing name would fail on perfectly good
117
+ files. This is a viewer, and it never feeds a computed number.
118
+ """
119
+ return (float(proc_ds.variables[name][particle_index])
120
+ if name in proc_ds.variables else default)
121
+
122
+ reject_code = get("image_auto_reject")
123
+ habit_code = get("holroyd_habit")
124
+ return {
125
+ "particle_index": particle_index,
126
+ "parent_rec_num": int(get("parent_rec_num")),
127
+ "particle_num": int(get("particle_num")),
128
+ "image_width": get("image_width"),
129
+ "image_length": get("image_length"),
130
+ "reject_code": _REJECT_BY_CODE.get(int(reject_code)) if reject_code else None,
131
+ "habit_code": _HABIT_BY_CODE.get(int(habit_code)) if habit_code else None,
132
+ "diam_minR": get("image_diam_minR"),
133
+ }
134
+
135
+
136
+ def _label(info: dict) -> str:
137
+ reject = info["reject_code"] or "?"
138
+ habit = info["habit_code"] or "?"
139
+ diam = info["diam_minR"]
140
+ diam_s = f"{diam:.3f}mm" if diam is not None and np.isfinite(diam) else "n/a"
141
+ return (f"rec {info['parent_rec_num']} #{info['particle_num']} "
142
+ f"reject={reject!r} habit={habit!r} diam={diam_s}")
143
+
144
+
145
+ def crop_to_content(c: np.ndarray, pad: int = 3) -> np.ndarray:
146
+ """``c`` (or its shadowed bounding box plus ``pad`` slices/diodes of
147
+ margin on each side), for **display only**.
148
+
149
+ ``reconstruct_particle_image`` is deliberately faithful to what
150
+ ``imgProc_sm.m:266-268`` actually builds: the full slice window between
151
+ consecutive boundary markers, which for a particle immediately after a
152
+ fresh record (``position`` resets to 1) or after an unusually large gap
153
+ can run hundreds of slices while the particle's own shadow -- what
154
+ ``image_width``/``image_length`` measure -- occupies a handful of them
155
+ near one end. At full scale that renders correctly; shrunk into a
156
+ thumbnail, the shadow can fall below a pixel and the particle looks
157
+ blank, which is misleading for visual verification even though nothing
158
+ about the reconstruction or the accept/reject decision is wrong.
159
+
160
+ Cropping is presentation only: it never touches ``reconstruct_particle_image``
161
+ or any value read from the proc file, and every rejected pixel outside the
162
+ returned window was never anything but background in the full array either.
163
+ An all-lit (no shadowed pixel) input is returned unchanged, since there is
164
+ no content to crop to.
165
+ """
166
+ rows = np.any(c, axis=1)
167
+ cols = np.any(c, axis=0)
168
+ if not rows.any():
169
+ return c
170
+ # ``int(...)`` around every ``argmax``: these four are only ever used as slice
171
+ # bounds, and mixing ``np.intp`` with the plain ``0`` / ``c.shape[n] - 1``
172
+ # literals below is what mypy objects to. Slicing is identical either way --
173
+ # this is a presentation-only crop, so no computed number depends on it.
174
+ r0, r1 = int(np.argmax(rows)), len(rows) - 1 - int(np.argmax(rows[::-1]))
175
+ c0, c1 = int(np.argmax(cols)), len(cols) - 1 - int(np.argmax(cols[::-1]))
176
+ r0 = max(0, r0 - pad)
177
+ r1 = min(c.shape[0] - 1, r1 + pad)
178
+ c0 = max(0, c0 - pad)
179
+ c1 = min(c.shape[1] - 1, c1 + pad)
180
+ return c[r0:r1 + 1, c0:c1 + 1]
181
+
182
+
183
+ def render_particle(image_ds, proc_ds, particle_index: int, ax=None, *, crop: bool = False):
184
+ """One particle's silhouette on a matplotlib Axes, labeled with its reject
185
+ code, habit, and min-enclosing-circle diameter. Returns the Figure (a
186
+ fresh one if ``ax`` is None) -- so this is equally usable from a CLI
187
+ (save the Figure), a notebook (let it auto-display), or assembled into a
188
+ contact sheet / HTML gallery (pass an existing ``ax``).
189
+
190
+ ``crop`` (default off, so single-particle/CLI use is unaffected): display
191
+ only the shadow's own bounding box plus a small margin, via
192
+ :func:`crop_to_content`, for the thumbnail-legibility reason documented
193
+ there. Off by default because the full window is sometimes exactly what a
194
+ reader wants (e.g. to see how much of a record a particle actually used).
195
+ """
196
+ import matplotlib.pyplot as plt
197
+
198
+ c = reconstruct_particle_image(image_ds, proc_ds, particle_index)
199
+ if crop:
200
+ c = crop_to_content(c)
201
+ info = particle_info(proc_ds, particle_index)
202
+
203
+ owns_fig = ax is None
204
+ if owns_fig:
205
+ fig, ax = plt.subplots(figsize=(max(2.0, c.shape[1] / 20), max(1.2, c.shape[0] / 20)))
206
+ else:
207
+ fig = ax.figure
208
+
209
+ ax.imshow(c, cmap="Greys", aspect="auto", interpolation="nearest")
210
+ ax.set_title(_label(info), fontsize=8)
211
+ ax.set_xlabel("diode", fontsize=7)
212
+ ax.set_ylabel("slice", fontsize=7)
213
+ ax.tick_params(labelsize=6)
214
+ if owns_fig:
215
+ fig.tight_layout()
216
+ return fig
217
+
218
+
219
+ def render_contact_sheet(image_ds, proc_ds, particle_indices, ncols: int = 5,
220
+ *, crop: bool = False):
221
+ """A grid of several particles' silhouettes, one Axes each -- the broader
222
+ eyeballed sanity check the plan names as track V's second rendering mode.
223
+
224
+ ``crop``: see :func:`render_particle` -- worth turning on here specifically,
225
+ since a contact sheet's whole point is many particles at thumbnail scale,
226
+ where an uncropped large-window particle is the most likely to look blank.
227
+ """
228
+ import matplotlib.pyplot as plt
229
+
230
+ particle_indices = list(particle_indices)
231
+ n = len(particle_indices)
232
+ ncols = max(1, min(ncols, n))
233
+ nrows = -(-n // ncols) # ceil
234
+ fig, axes = plt.subplots(nrows, ncols, figsize=(3.2 * ncols, 2.4 * nrows), squeeze=False)
235
+ for k, idx in enumerate(particle_indices):
236
+ ax = axes[k // ncols][k % ncols]
237
+ render_particle(image_ds, proc_ds, idx, ax=ax, crop=crop)
238
+ for k in range(n, nrows * ncols):
239
+ axes[k // ncols][k % ncols].axis("off")
240
+ fig.tight_layout()
241
+ return fig
242
+
243
+
244
+ # ---- Review figures: particles in a readable grid --------------------------------------------
245
+ # The author, 2026-10-03: "Make them properly in not horizontal one row, but bigger rows so I can
246
+ # actually see the images" and "grids must be vertical, 2x2 or 3x3 panels, so the page is neither
247
+ # too wide nor too long". Every particle figure made for review goes through ``particle_grid``.
248
+ # Presentation only: nothing here reads or changes a computed number.
249
+
250
+ #: Most columns a review grid uses; a 3 x 3 grid of 3.2-inch panels fits one screen or page.
251
+ GRID_MAX_COLS = 3
252
+
253
+
254
+ def grid_shape(n: int, max_cols: int = GRID_MAX_COLS) -> tuple[int, int]:
255
+ """``(rows, cols)`` for ``n`` panels: 1 x 1 for one, two columns up to four (2 x 2), three
256
+ columns beyond. Never one row of more than two panels, so particles stay large."""
257
+ if n <= 0:
258
+ return (0, 0)
259
+ ncols = 1 if n == 1 else (2 if n <= 4 else max_cols)
260
+ ncols = min(ncols, max_cols)
261
+ return (-(-n // ncols), ncols)
262
+
263
+
264
+ def wrap_title(text: str, width: int) -> str:
265
+ """``text`` with every line wrapped to at most ``width`` characters, keeping the caller's own
266
+ line breaks, so a panel title never runs past its panel."""
267
+ import textwrap
268
+
269
+ out: list[str] = []
270
+ for line in str(text).split("\n"):
271
+ out.extend(textwrap.wrap(line, width=max(8, width), break_long_words=True) or [""])
272
+ return "\n".join(out)
273
+
274
+
275
+ def record_slice_um(image_ds, proc_ds, particle_index: int, diode_um: float) -> float | None:
276
+ """Along-track length of one slice, in micrometres, for the record a particle came from:
277
+ ``diode_um / tasRatio``, the convention v3.5's own shape statistics use
278
+ (``holroyd_new.m`` via ``arrayprobe_uiops.habit.calc_stat_new``: ``tx = i / tas_ratio``).
279
+ ``None`` when the image file has no usable ``tasRatio`` for that record, so the caller draws
280
+ the slice as one diode and says the aspect is not true."""
281
+ if "tasRatio" not in image_ds.variables:
282
+ return None
283
+ rec = int(proc_ds.variables["parent_rec_num"][particle_index]) # 1-based
284
+ try:
285
+ r = float(np.ma.filled(image_ds.variables["tasRatio"][rec - 1], np.nan))
286
+ except (IndexError, ValueError, TypeError):
287
+ return None
288
+ if not np.isfinite(r) or r <= 0:
289
+ return None
290
+ return diode_um / r
291
+
292
+
293
+ def _nice_bar_um(span_um: float) -> float:
294
+ """A round scale-bar length no longer than about 40 % of ``span_um``."""
295
+ steps = (10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000)
296
+ fits = [v for v in steps if v <= span_um * 0.4]
297
+ return float(fits[-1] if fits else steps[0])
298
+
299
+
300
+ def particle_grid(images, titles=None, *, diode_um: float = 10.0, slice_um=None,
301
+ title_colors=None, suptitle: str | None = None, panel_in: float = 3.2,
302
+ fontsize: float = 10.0, crop_pad: int = 3, max_cols: int = GRID_MAX_COLS,
303
+ ring_small: int = 0):
304
+ """A review figure: one large panel per particle in a grid (:func:`grid_shape`), each image
305
+ cropped to its shadowed pixels plus ``crop_pad`` (:func:`crop_to_content`), drawn with
306
+ nearest-neighbour pixels, a scale bar in micrometres and a wrapped title of ``fontsize`` pt.
307
+
308
+ ``images``: boolean ``(n_slices, n_diodes)`` arrays, as :func:`reconstruct_particle_image`
309
+ returns. ``slice_um``: the along-track length of one slice, a scalar or one value per image
310
+ (see :func:`record_slice_um`); where it is ``None`` a slice is drawn one diode long and the
311
+ panel title says "aspect not true". ``ring_small``: circle every 8-connected group of at
312
+ most this many pixels, so a single shadowed pixel stays visible at page scale (0: none).
313
+ Returns the Figure.
314
+ """
315
+ import matplotlib.pyplot as plt
316
+
317
+ images = [np.asarray(c) > 0 for c in images]
318
+ n = len(images)
319
+ titles = list(titles) if titles is not None else [""] * n
320
+ colors = list(title_colors) if title_colors is not None else ["black"] * n
321
+ slices: list[Any] # slice lengths in um, or None per panel
322
+ if slice_um is None or np.isscalar(slice_um):
323
+ slices = [slice_um] * n
324
+ else:
325
+ slices = list(slice_um)
326
+ nrows, ncols = grid_shape(n, max_cols)
327
+ nrows, ncols = max(nrows, 1), max(ncols, 1)
328
+ chars = int(panel_in * 72 / (fontsize * 0.58))
329
+ wrapped = []
330
+ for k in range(n):
331
+ s = slices[k]
332
+ note = (f"slice {s:.1f} um (true aspect)" if s is not None
333
+ else "aspect not true: slice drawn 1 diode long")
334
+ wrapped.append(wrap_title(f"{titles[k]}\n{note}" if titles[k] else note, chars))
335
+ lines = max([t.count("\n") + 1 for t in wrapped] or [1])
336
+ title_in = lines * fontsize * 1.35 / 72
337
+ head_in = 0.0
338
+ if suptitle:
339
+ suptitle = wrap_title(suptitle, int(ncols * panel_in * 72 / ((fontsize + 1) * 0.55)))
340
+ head_in = (suptitle.count("\n") + 1) * (fontsize + 1) * 1.4 / 72 + 0.2
341
+ fig, axes = plt.subplots(nrows, ncols, squeeze=False, layout="constrained",
342
+ figsize=(ncols * panel_in + 0.3,
343
+ nrows * (panel_in + title_in + 0.15) + head_in))
344
+ for ax in axes.flat:
345
+ ax.set_axis_off()
346
+ for k, c in enumerate(images):
347
+ ax = axes[k // ncols][k % ncols]
348
+ ax.set_axis_on()
349
+ sub = crop_to_content(c, pad=crop_pad) if c.any() else c
350
+ s = slices[k] if slices[k] is not None else diode_um
351
+ h_um, w_um = sub.shape[0] * s, sub.shape[1] * diode_um
352
+ span = max(h_um, w_um)
353
+ bar = _nice_bar_um(span)
354
+ margin = 0.16 * span
355
+ ax.imshow(sub, cmap="Greys", vmin=0, vmax=1, interpolation="nearest", aspect="equal",
356
+ extent=(0, w_um, h_um, 0))
357
+ # Square view around the image so every panel is the same size; the bar sits below it.
358
+ cx = w_um / 2
359
+ half = (span + margin) / 2
360
+ ax.set_xlim(cx - half, cx + half)
361
+ ax.set_ylim(h_um + margin, h_um + margin - (span + margin))
362
+ y = h_um + margin * 0.55
363
+ x0 = cx - half + 0.05 * span
364
+ ax.plot([x0, x0 + bar], [y, y], color="tab:blue", lw=3, solid_capstyle="butt")
365
+ ax.text(x0 + bar / 2, y - margin * 0.12, f"{bar:g} um", ha="center", va="bottom",
366
+ fontsize=fontsize - 1, color="tab:blue")
367
+ if ring_small > 0 and sub.any():
368
+ from scipy import ndimage
369
+
370
+ lab, nlab = ndimage.label(sub, structure=np.ones((3, 3), dtype=int))
371
+ # Boxes of the pieces too big to ring: a speck inside one (a hole's pixel) is not
372
+ # ringed, only one standing apart.
373
+ objs = ndimage.find_objects(lab)
374
+ boxes = [objs[j - 1] for j in range(1, nlab + 1)
375
+ if (lab == j).sum() > ring_small]
376
+ for j in range(1, nlab + 1):
377
+ rr, cc = np.nonzero(lab == j)
378
+ inside = any(b[0].start <= rr.mean() < b[0].stop
379
+ and b[1].start <= cc.mean() < b[1].stop for b in boxes)
380
+ if rr.size <= ring_small and not inside:
381
+ ax.add_patch(plt.Circle(((cc.mean() + 0.5) * diode_um, (rr.mean() + 0.5) * s),
382
+ radius=max(0.05 * span, 2 * diode_um), fill=False,
383
+ color="tab:red", lw=1.5))
384
+ ax.set_xticks([])
385
+ ax.set_yticks([])
386
+ for sp in ax.spines.values():
387
+ sp.set_color("0.75")
388
+ ax.set_title(wrapped[k], fontsize=fontsize, color=colors[k], loc="center")
389
+ if suptitle:
390
+ fig.suptitle(suptitle, fontsize=fontsize + 1)
391
+ return fig
392
+
393
+
394
+ def render_gallery_html(image_ds, proc_ds, particle_indices, out_path, *,
395
+ title="Particle gallery", crop: bool = False):
396
+ """A self-contained HTML page, one rendered particle per card, base64-
397
+ embedded PNGs -- the third avenue named in the plan (published-artifact
398
+ page), usable without a Python environment to view.
399
+
400
+ ``crop``: see :func:`render_particle`.
401
+ """
402
+ import base64
403
+ import io
404
+
405
+ import matplotlib.pyplot as plt
406
+
407
+ cards = []
408
+ for idx in particle_indices:
409
+ fig = render_particle(image_ds, proc_ds, idx, crop=crop)
410
+ buf = io.BytesIO()
411
+ fig.savefig(buf, format="png", dpi=150)
412
+ plt.close(fig)
413
+ b64 = base64.b64encode(buf.getvalue()).decode("ascii")
414
+ info = particle_info(proc_ds, idx)
415
+ cards.append(
416
+ f'<div class="card"><img src="data:image/png;base64,{b64}" '
417
+ f'alt="particle {idx}"><div class="cap">{_label(info)}</div></div>'
418
+ )
419
+ html = f"""<title>{title}</title>
420
+ <style>
421
+ body {{ font-family: system-ui, sans-serif; background: #f7f8f9; color: #1d2329;
422
+ margin: 1.5rem; }}
423
+ h1 {{ font-size: 1.3rem; }}
424
+ .grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
425
+ gap: 1rem; }}
426
+ .card {{ background: #fff; border: 1px solid #d9dee3; border-radius: 6px; padding: 0.6rem; }}
427
+ .card img {{ width: 100%; height: auto; display: block; }}
428
+ .cap {{ font-size: 0.72rem; color: #5c6672; margin-top: 0.4rem; font-family: monospace; }}
429
+ </style>
430
+ <h1>{title}</h1>
431
+ <div class="grid">
432
+ {"".join(cards)}
433
+ </div>
434
+ """
435
+ with open(out_path, "w", encoding="utf-8") as fh:
436
+ fh.write(html)
437
+ return out_path
438
+
439
+
440
+ # --------------------------------------------------------------------------
441
+ # Whole-flight render to disk
442
+ #
443
+ # The other renderers in this module are viewers: they draw a handful of
444
+ # particles through matplotlib for a person to look at. This one writes an
445
+ # entire flight -- hundreds of thousands of particles -- into a directory tree,
446
+ # so matplotlib is the wrong tool twice over. It is slow per image, and it is
447
+ # not thread-safe (two crashes in the triage server showed
448
+ # that). These functions touch neither matplotlib nor netCDF
449
+ # concurrently, and write PNG bytes directly.
450
+ # --------------------------------------------------------------------------
451
+
452
+ #: How a particle is filed. ``accepted``/``rejected`` are UIOOPS's own verdict,
453
+ #: read from ``image_auto_reject``; ``unsure`` is a *human* verdict from the
454
+ #: triage sidecar and overrides both, because a person marking a particle
455
+ #: unsure is exactly what the word means here. A particle nobody has looked at
456
+ #: is never "unsure" -- it is filed by what the code decided.
457
+ PARTICLE_CLASSES = ("accepted", "rejected", "unsure")
458
+
459
+ #: ``image_auto_reject`` codes of an accepted particle: ``"0HhuR"``, the set sizeDist counts
460
+ #: (``sizeDist.m:1209``; v3.1.4 and v3.5 alike). Hollow ``'H'``/``'h'`` particles are kept, sized
461
+ #: with/without the Korolev correction; the ORACLES production profile switches the hollow test
462
+ #: off, so no ``'H'``/``'h'`` occurs in its products and the set reduces to ``'0'`` there. One
463
+ #: set serves both engines, so no stamp needs reading.
464
+ from arrayprobe_uiops.sizedist_core import GOOD_REJECT_CODES as _GOOD # noqa: E402
465
+
466
+ ACCEPTED_CODES = np.array([ord(c) for c in _GOOD], dtype=np.int64)
467
+
468
+
469
+ def is_accepted_code(codes):
470
+ """Boolean array (or scalar bool): which ``image_auto_reject`` codes are accepted."""
471
+ return np.isin(np.asarray(codes), ACCEPTED_CODES)
472
+
473
+
474
+ def _png_bytes(mask: np.ndarray, scale: int = 1) -> bytes:
475
+ """An 8-bit greyscale PNG of ``mask``: shadowed black, background white.
476
+
477
+ Written with ``zlib`` and ``struct`` rather than a library because this is
478
+ called once per particle for a whole flight, and because it keeps the
479
+ whole-flight renderer free of any dependency the core package does not
480
+ already have.
481
+ """
482
+ import struct
483
+ import zlib
484
+
485
+ img = np.where(np.asarray(mask, dtype=bool), 0, 255).astype(np.uint8)
486
+ if scale > 1:
487
+ img = np.repeat(np.repeat(img, scale, axis=0), scale, axis=1)
488
+ height, width = img.shape
489
+ # Each scanline is prefixed with a filter byte; 0 means "no filter".
490
+ raw = b"".join(b"\x00" + img[row].tobytes() for row in range(height))
491
+
492
+ def chunk(tag: bytes, payload: bytes) -> bytes:
493
+ return (struct.pack(">I", len(payload)) + tag + payload
494
+ + struct.pack(">I", zlib.crc32(tag + payload) & 0xFFFFFFFF))
495
+
496
+ return (b"\x89PNG\r\n\x1a\n"
497
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0))
498
+ + chunk(b"IDAT", zlib.compress(raw, 6))
499
+ + chunk(b"IEND", b""))
500
+
501
+
502
+ def particle_thumbnail_png(image_ds, proc_ds, particle_index: int, *,
503
+ crop: bool = True, scale: int = 1, probe: str = "2DS") -> bytes:
504
+ """One particle's shadow as a matplotlib-free PNG.
505
+
506
+ Wraps :func:`reconstruct_particle_image` and :func:`crop_to_content`
507
+ around :func:`_png_bytes`, the same standard-library writer
508
+ :func:`render_flight_to_disk` already uses for a whole flight -- pulled
509
+ out to a public function so ``arrayprobe.triage_server``'s ``/thumb`` and
510
+ ``/sheet`` routes can call it directly instead of the much slower
511
+ ``matplotlib`` path :func:`render_particle` uses (a private ``Figure`` per
512
+ request, ~50-75 ms measured -- fine for one particle, the reason a
513
+ contact sheet of 200 costs ~10 s). Byte-for-byte what
514
+ ``render_flight_to_disk`` writes to disk for the same particle and the
515
+ same ``crop``/``scale``.
516
+ """
517
+ c = reconstruct_particle_image(image_ds, proc_ds, particle_index, probe=probe)
518
+ if crop:
519
+ c = crop_to_content(c)
520
+ return _png_bytes(c, scale=scale)
521
+
522
+
523
+ def unverified_placeholder_png(size: int = 48) -> bytes:
524
+ """A small placeholder PNG for a probe outside :data:`DRAWABLE_PROBES`.
525
+
526
+ ``arrayprobe.triage_server`` serves this from its ``/thumb`` and grid
527
+ routes instead of calling :func:`reconstruct_particle_image` (and raising
528
+ ``ValueError``) for a probe this module has not verified -- see
529
+ ``DRAWABLE_PROBES``'s own docstring for exactly what is unchecked.
530
+ Matplotlib-free, the same as :func:`particle_thumbnail_png`'s own writer
531
+ and for the same reason: a flight's contact sheet can ask for hundreds of
532
+ these on one page. Text does not fit a bytes-only PNG writer, so this
533
+ carries only a visual "this is not the real image" signal (an X in a
534
+ bordered box); the actual explanation is text in the surrounding page,
535
+ beside wherever this is embedded.
536
+ """
537
+ mask = np.zeros((size, size), dtype=bool)
538
+ idx = np.arange(size)
539
+ mask[idx, idx] = True # \
540
+ mask[idx, size - 1 - idx] = True # /
541
+ mask[0, :] = mask[-1, :] = mask[:, 0] = mask[:, -1] = True # border
542
+ return _png_bytes(mask)
543
+
544
+
545
+ def _hhmmss(time_value: float) -> str:
546
+ """``73928.0`` -> ``"073928"``.
547
+
548
+ The proc file's ``Time`` is MATLAB's HHMMSS packed into a float, not a
549
+ count of seconds, so it is formatted rather than converted.
550
+ """
551
+ return f"{int(round(float(time_value))):06d}"
552
+
553
+
554
+ def classify_particle(reject_code, verdict: str | None) -> str:
555
+ """Which of :data:`PARTICLE_CLASSES` a particle belongs in."""
556
+ if verdict == "unsure":
557
+ return "unsure"
558
+ return "accepted" if bool(is_accepted_code(int(reject_code))) else "rejected"
559
+
560
+
561
+ def render_flight_to_disk(image_ds, proc_ds, out_dir, *, verdicts=None,
562
+ classes=PARTICLE_CLASSES, scale: int = 3,
563
+ crop: bool = True, limit=None, progress=None) -> dict:
564
+ """Write every particle of a flight to ``out_dir/<HHMMSS>/<class>/``.
565
+
566
+ One directory per second, per the author's own description of what this is
567
+ for: looking at a whole second's worth of particles together rather than at
568
+ a sampled gallery.
569
+
570
+ ``classes`` selects which of :data:`PARTICLE_CLASSES` are written, and
571
+ exists because the counts are large -- a single 2017 flight is 436,983
572
+ particles, 87 % of them accepted -- so ``classes=("accepted",)`` is the
573
+ documented way to start.
574
+
575
+ **Resumable**: a particle whose PNG is already on disk is skipped, so an
576
+ interrupted run continues rather than restarting. That matters when the run
577
+ is hours long.
578
+
579
+ Returns counts per class plus ``skipped`` and ``seconds``.
580
+ """
581
+ from pathlib import Path
582
+
583
+ out = Path(out_dir)
584
+ verdicts = verdicts or {}
585
+ wanted = set(classes)
586
+ times = np.asarray(proc_ds.variables["Time"][:])
587
+ rejects = np.asarray(proc_ds.variables["image_auto_reject"][:])
588
+ total = len(times) if limit is None else min(int(limit), len(times))
589
+
590
+ counts = {name: 0 for name in PARTICLE_CLASSES}
591
+ counts["skipped"] = 0
592
+ seconds = set()
593
+
594
+ for i in range(total):
595
+ entry = verdicts.get(str(i)) or verdicts.get(i)
596
+ verdict = entry.get("verdict") if isinstance(entry, dict) else entry
597
+ cls = classify_particle(rejects[i], verdict)
598
+ if cls not in wanted:
599
+ counts["skipped"] += 1
600
+ continue
601
+ second = _hhmmss(times[i])
602
+ seconds.add(second)
603
+ target = out / second / cls / f"p{i:07d}.png"
604
+ if target.exists():
605
+ counts[cls] += 1
606
+ continue
607
+ target.parent.mkdir(parents=True, exist_ok=True)
608
+ target.write_bytes(particle_thumbnail_png(image_ds, proc_ds, i, crop=crop, scale=scale))
609
+ counts[cls] += 1
610
+ if progress is not None and (i + 1) % 1000 == 0:
611
+ progress(i + 1, total, counts)
612
+
613
+ counts["seconds"] = len(seconds)
614
+ return counts
615
+
616
+
617
+ #: Images per index page. A second is not a small unit: on the first real
618
+ #: flight rendered, the per-second count ranges from 0 to **53,926**, median 2.
619
+ #: One page holding fifty thousand ``<img>`` tags is not browsable however lazy
620
+ #: the loading, so a busy second is paginated. Measured, not guessed -- the
621
+ #: spread is the reason this constant exists.
622
+ INDEX_PAGE_SIZE = 500
623
+
624
+
625
+
626
+ def _index_name(page_no: int) -> str:
627
+ """``1`` -> ``index.html``, ``2`` -> ``index-2.html``.
628
+
629
+ Page one keeps the plain name so a link to a second's directory works
630
+ whether or not that second turned out to need paginating.
631
+ """
632
+ return "index.html" if page_no == 1 else f"index-{page_no}.html"
633
+
634
+ def write_flight_index(out_dir, *, title: str | None = None,
635
+ page_size: int = INDEX_PAGE_SIZE) -> list:
636
+ """Index pages for a tree written by :func:`render_flight_to_disk`.
637
+
638
+ One page per second listing that second's particles, and one page for the
639
+ flight listing every second with its per-class counts. Without these the
640
+ tree is only navigable in a file manager, which is not what "look at a
641
+ whole second's particles" means in practice.
642
+
643
+ A second holding more than ``page_size`` images is split across
644
+ ``index.html``, ``index-2.html`` and so on, each linking to the others.
645
+
646
+ Written from what is *on disk* rather than from the render's own return
647
+ value, so an index built after a resumed or partial run describes the tree
648
+ that actually exists.
649
+ """
650
+ from pathlib import Path
651
+
652
+ out = Path(out_dir)
653
+ written = []
654
+ rows = []
655
+ for second_dir in sorted(p for p in out.iterdir() if p.is_dir()):
656
+ per_class = {}
657
+ for cls in PARTICLE_CLASSES:
658
+ files = sorted((second_dir / cls).glob("*.png")) if (second_dir / cls).is_dir() else []
659
+ per_class[cls] = files
660
+ n = sum(len(v) for v in per_class.values())
661
+ if not n:
662
+ continue
663
+ rows.append((second_dir.name, {k: len(v) for k, v in per_class.items()}, n))
664
+
665
+ # Flatten to (class, file) so a page boundary can fall inside a class.
666
+ flat = [(cls, f) for cls in PARTICLE_CLASSES for f in per_class[cls]]
667
+ pages = [flat[i:i + page_size] for i in range(0, len(flat), page_size)] or [[]]
668
+ for page_no, chunk in enumerate(pages, start=1):
669
+ blocks, current = [], None
670
+ for cls, f in chunk:
671
+ if cls != current:
672
+ blocks.append(f'<h2>{cls}</h2><div class="grid">')
673
+ current = cls
674
+ blocks.append(
675
+ f'<figure><img src="{cls}/{f.name}" alt="{f.stem}" loading="lazy">'
676
+ f'<figcaption>{f.stem}</figcaption></figure>')
677
+ body = "".join(blocks) + ("</div>" if blocks else "")
678
+ nav = ""
679
+ if len(pages) > 1:
680
+ links = " ".join(
681
+ f'<b>{i}</b>' if i == page_no
682
+ else f'<a href="{_index_name(i)}">{i}</a>'
683
+ for i in range(1, len(pages) + 1))
684
+ nav = (f'<p>{n} particles in this second, {page_size} per page: {links}</p>')
685
+ page = _index_page(
686
+ f"{second_dir.name} &mdash; {n} particles",
687
+ '<p><a href="../index.html">&larr; all seconds</a></p>' + nav + body + nav)
688
+ target = second_dir / _index_name(page_no)
689
+ target.write_text(page, encoding="utf-8")
690
+ written.append(target)
691
+
692
+ listing = "".join(
693
+ f'<tr><td><a href="{s}/index.html">{s}</a></td>'
694
+ + "".join(f'<td class="n">{c[k] or ""}</td>' for k in PARTICLE_CLASSES)
695
+ + f'<td class="n">{n}</td></tr>'
696
+ for s, c, n in rows)
697
+ head = "".join(f"<th>{k}</th>" for k in PARTICLE_CLASSES)
698
+ total = sum(n for _, _, n in rows)
699
+ body = (f"<p>{len(rows)} seconds, {total} particles. One directory per second; "
700
+ f"within each, one directory per class.</p>"
701
+ f"<table><thead><tr><th>second</th>{head}<th>all</th></tr></thead>"
702
+ f"<tbody>{listing}</tbody></table>")
703
+ (out / "index.html").write_text(
704
+ _index_page(title or out.name, body), encoding="utf-8")
705
+ written.append(out / "index.html")
706
+ return written
707
+
708
+
709
+ def _index_page(title: str, body: str) -> str:
710
+ return f"""<!doctype html><meta charset="utf-8"><title>{title}</title>
711
+ <style>
712
+ body {{ font-family: system-ui, sans-serif; margin: 1.5rem; background: #f7f8f9; color: #1d2329; }}
713
+ h1 {{ font-size: 1.25rem; }} h2 {{ font-size: 0.95rem; margin: 1.4rem 0 0.4rem; }}
714
+ h2 .n {{ color: #5c6672; font-weight: 400; }}
715
+ .grid {{ display: grid; gap: 0.5rem;
716
+ grid-template-columns: repeat(auto-fill, minmax(90px, 1fr)); }}
717
+ figure {{ margin: 0; background: #fff; border: 1px solid #d9dee3;
718
+ border-radius: 4px; padding: 0.3rem; }}
719
+ figure img {{ width: 100%; height: auto; display: block; image-rendering: pixelated; }}
720
+ figcaption {{ font: 0.62rem monospace; color: #5c6672; margin-top: 0.2rem; }}
721
+ table {{ border-collapse: collapse; font-size: 0.85rem; }}
722
+ th, td {{ text-align: left; padding: 0.3rem 0.7rem; border-bottom: 1px solid #d9dee3; }}
723
+ td.n, th.n {{ text-align: right; font-variant-numeric: tabular-nums; }}
724
+ a {{ color: #1e6f68; }}
725
+ </style>
726
+ <h1>{title}</h1>
727
+ {body}
728
+ """