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,1089 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Build a synthetic raw ``.2DS`` file with no campaign data required.
3
+
4
+ **Why this exists**: everything else a
5
+ stranger can run through this package needs either the ORACLES archive
6
+ (gitignored, campaign-restricted) or Octave (an external install). This tool
7
+ needs neither -- it hand-builds a raw SPEC file shaped exactly like a real
8
+ 2D-S recording (the record geometry, the housekeeping packet layout, one
9
+ framed particle per second) and writes it to a path of the caller's choosing,
10
+ so the whole pipeline can be exercised in seconds::
11
+
12
+ arrayprobe make-demo-flight base160101000000.2DS --seconds 5
13
+
14
+ This module lives inside the installed package rather than in ``scripts/``,
15
+ which ``pip install`` does not ship; ``scripts/make_demo_flight.py`` remains as
16
+ a re-export shim because the documentation publishes that path.
17
+
18
+ Then process it with ``arrayprobe run <config.toml> <flight> --yes`` (see
19
+ ``examples/start_here/README.md``), or with ``run_flight.py``'s own ``DEMO_2DS_H`` preset
20
+ (a separate tool, with its own flags): ``run_flight.py --preset DEMO_2DS_H --engine 3.5
21
+ --profile stock-v3.5 --tas-file <aircraft.cdf> --stages 234 --yes base160101000000.2DS``.
22
+ Engine 3.1.4, the ORACLES-validation anchor, is not part of this package.
23
+
24
+ **The output filename must follow the SPEC ``base<YYMMDDhhmmss>`` convention**
25
+ (any valid-looking date/time; the demo data are synthetic regardless) --
26
+ ``combine_sizedist`` reproduces the original's own behaviour of reading the
27
+ flight date from the raw stem (``combine_sizedist.m``, ``summaryfile(1).name``;
28
+ see ``docs/09-conventions.md``'s ``<stem>`` placeholder), so a
29
+ stage-4c combine fails on any other name. This is a faithful constraint, not a
30
+ bug in this tool: a name like ``demo.2DS`` runs stages 2-4 fine and only the
31
+ combine step needs the convention.
32
+
33
+ **Not validated science.** The synthetic particle is shaped to survive S3's
34
+ accept ladder (centred, aspect-ratio coherent) but its inter-arrival times are
35
+ arbitrary incrementing constants, not a realistic clock -- under the
36
+ production shattering configuration every one of them reads as a sub-6us
37
+ inter-arrival and is rejected, exactly as ``tests/test_end_to_end.py``
38
+ documents. The demo proves the pipeline *runs end to end and writes valid
39
+ files*; it is not a stand-in for the oracle-backed validation this project's
40
+ actual fidelity claims rest on. The :data:`DEMO_2DS_H` preset this module's
41
+ sibling ``run_flight.py`` carries says so in its own ``provenance`` field.
42
+
43
+ **One deliberate duplication.** ``tests/test_spec_reader.py`` already has
44
+ ``run_word``/``image_packet``/``raw_file`` -- lower-level packet-framing
45
+ primitives used to test individual bit-layout decisions. This module does not
46
+ import them: a `scripts/` script that a `pip install`'d user runs cannot depend
47
+ on `tests/`, which the sdist does not even ship. The three primitives are
48
+ reproduced here, small and stable (they encode a fixed binary layout, not
49
+ project logic that could drift), and ``tests/test_end_to_end.py`` now imports
50
+ its synthetic flight builder *from this tool* rather than defining its own --
51
+ the direction the plan's own item names: "tests import from the tool, not the
52
+ reverse."
53
+ """
54
+
55
+ from __future__ import annotations
56
+
57
+ import argparse
58
+ import importlib.util
59
+ import math
60
+ import sys
61
+ from pathlib import Path
62
+
63
+ import numpy as np
64
+
65
+ from arrayprobe_uiops import spec_core as spec
66
+
67
+
68
+ def run_word(aa: int, bb: int, new_slice: bool = False) -> int:
69
+ """One run-length word: ``aa`` shadowed diodes after ``bb`` clear ones."""
70
+ assert 0 <= aa < 128 and 0 <= bb < 128
71
+ return (0x4000 if new_slice else 0) | (aa << 7) | bb
72
+
73
+
74
+ def image_packet(runs, n_s, *, channel="H", pc=7, t_particle=0x1234ABCD, timing=False):
75
+ """A ``'2S'`` image packet. ``runs`` are the run words; the timestamp is appended."""
76
+ payload = [*runs, (t_particle >> 16) & 0xFFFF, t_particle & 0xFFFF]
77
+ n = len(payload)
78
+ flag = 4096 if timing else 0
79
+ if channel == "H":
80
+ return [spec.MARKER_2S, n | flag, 0, pc, n_s, *payload]
81
+ return [spec.MARKER_2S, 0, n | flag, pc, n_s, *payload]
82
+
83
+
84
+ def _packet_counter(k: int, distinct: bool) -> int:
85
+ """Particle-counter word for the ``k``-th image packet (0-based).
86
+
87
+ Default: the constant 7 every demo has always written, so default output is
88
+ byte-identical. ``distinct=True`` gives each packet its own counter,
89
+ ``(7 + k) mod 65536`` (the counter is one 16-bit word), because SODA-2's
90
+ ``spec_index`` keeps a frame only when the counter changes -- with a
91
+ constant counter it sees one particle of the dense demo's 60.
92
+ """
93
+ return (7 + k) & 0xFFFF if distinct else 7
94
+
95
+
96
+ def raw_file(path, records) -> Path:
97
+ """Write a raw ``.2DS``-shaped file: ``records`` is a list of (header, image words)."""
98
+ out = np.zeros((len(records), spec.RECORD_WORDS), dtype="<u2")
99
+ for i, (header, image) in enumerate(records):
100
+ out[i, : spec.HEADER_WORDS] = header
101
+ out[i, spec.HEADER_WORDS : spec.HEADER_WORDS + len(image)] = image
102
+ out.tofile(path)
103
+ return Path(path)
104
+
105
+
106
+ def _drop_runs():
107
+ """A small closed loop of shadowed diodes -- lit, a ring of shadow, lit
108
+ again -- framed as one real, accepted particle through S3's reject
109
+ ladder. Centred near diode 60-62 rather than the array edge:
110
+ ``image_center_in`` requires the shape to sit away from the edge of the
111
+ 128-diode array.
112
+ """
113
+ return [run_word(2, 62), run_word(2, 60, new_slice=True),
114
+ run_word(2, 60, new_slice=True), run_word(2, 62, new_slice=True)]
115
+
116
+
117
+ def _hk_words(tas_mps: float, time_of_day: float) -> list[int]:
118
+ """One housekeeping packet: TAS at word 49-50 (float32, split high/low),
119
+ time-of-day at 51-52 -- the fields ``SidecarWriter`` reads for the
120
+ ``.tas.csv`` sidecar S4 needs.
121
+ """
122
+ words = [0] * 60
123
+ words[0] = spec.MARKER_HK
124
+ raw = np.float32(tas_mps).view(np.uint32).item()
125
+ words[49] = raw >> 16
126
+ words[50] = raw & 0xFFFF
127
+ words[51], words[52] = int(time_of_day // 65536), int(time_of_day % 65536)
128
+ return words
129
+
130
+
131
+ def build_demo_flight(path, n_seconds: int = 5, tas_mps: float = 130.0,
132
+ start_hour: int = 6, start_minute: int = 6,
133
+ start_second: int = 40, distinct_counters: bool = False) -> Path:
134
+ """Write a synthetic raw ``.2DS`` file: one accepted-shaped H-channel
135
+ particle and one HK (TAS) packet per second, starting at
136
+ ``start_hour:start_minute:start_second`` UTC on an arbitrary date.
137
+ """
138
+ records = []
139
+ for sec in range(n_seconds):
140
+ header = (2016, 9, 2, 6, start_hour, start_minute, start_second + sec, 250)
141
+ pkt = image_packet(_drop_runs(), 4, channel="H",
142
+ pc=_packet_counter(sec, distinct_counters),
143
+ t_particle=0x1234ABCD + sec)
144
+ records.append((header, pkt))
145
+ tod = start_hour * 3600 + start_minute * 60 + start_second + sec
146
+ records.append((header, _hk_words(tas_mps, tod)))
147
+ return raw_file(str(path), records)
148
+
149
+
150
+ #: A realistic aircraft airspeed series for the demo, so the quickstart runs on engine
151
+ #: 3.5 (the default), which refuses to size a 2D-S without an aircraft TAS file
152
+ #: (``imgProc_sm.m:183-185``). Derived, not invented: 60 s of ARM AAF ``true_airspeed`` (m/s,
153
+ #: public ARM data) from ``enaaafmergedF1.c1.20170706.082313.nc``, 09:40:00-09:40:59 UTC,
154
+ #: each value multiplied by 0.9565335751997573 -- one draw of
155
+ #: ``numpy.random.default_rng(387).uniform(0.85, 1.15)`` -- and rounded to 0.01 m/s, so it
156
+ #: reads like an aircraft record and matches no real flight.
157
+ DEMO_AIRCRAFT_TAS_MPS = (
158
+ 96.94, 96.72, 95.95, 96.22, 96.12, 95.84, 96.02, 96.02, 96.03, 96.28,
159
+ 96.76, 95.8, 96.13, 95.89, 96.0, 95.36, 96.54, 94.95, 96.33, 96.42,
160
+ 96.17, 95.65, 95.84, 95.37, 96.18, 96.43, 95.12, 94.89, 94.91, 95.98,
161
+ 95.48, 96.13, 96.49, 95.88, 95.09, 95.31, 94.84, 94.54, 94.94, 95.02,
162
+ 95.06, 94.3, 95.57, 94.54, 96.33, 94.61, 95.81, 93.3, 94.13, 96.17,
163
+ 95.57, 92.62, 93.68, 93.28, 96.44, 93.29, 94.84, 90.48, 91.95, 93.06,
164
+ )
165
+
166
+
167
+ def demo_aircraft_path(raw_path) -> Path:
168
+ """Where :func:`write_demo_aircraft` puts the demo flight's aircraft file."""
169
+ raw_path = Path(raw_path)
170
+ return raw_path.with_name(raw_path.stem + ".aircraft.cdf")
171
+
172
+
173
+ def write_demo_aircraft(raw_path, n_seconds: int = 5, start_hour: int = 6,
174
+ start_minute: int = 6, start_second: int = 40,
175
+ margin_s: int = 10) -> Path:
176
+ """Write ``<stem>.aircraft.cdf`` beside a demo flight: ``Time`` (HHMMSS) and ``TAS`` (m/s).
177
+
178
+ Covers the flight's records plus ``margin_s`` seconds either side, so every image
179
+ record's second finds a sample (``imgProc_sm.m:727`` looks it up by exact equality).
180
+ Values cycle through :data:`DEMO_AIRCRAFT_TAS_MPS`.
181
+ """
182
+ from arrayprobe.tools.make_tas_file import write_tas_file
183
+
184
+ t0 = start_hour * 3600 + start_minute * 60 + start_second - margin_s
185
+ n = n_seconds + 2 * margin_s
186
+ tod = [(t0 + i) % 86400 for i in range(n)]
187
+ hhmmss = [float((s // 3600) * 10000 + (s % 3600 // 60) * 100 + s % 60) for s in tod]
188
+ tas = [DEMO_AIRCRAFT_TAS_MPS[i % len(DEMO_AIRCRAFT_TAS_MPS)] for i in range(n)]
189
+ return write_tas_file(demo_aircraft_path(raw_path), hhmmss, tas, provenance={
190
+ "source": "demo: ARM AAF true_airspeed 2017-07-06 09:40 UTC excerpt x 0.9565",
191
+ })
192
+
193
+
194
+ def disk_runs(diameter: int, x0: int) -> list[int]:
195
+ """A filled circle ``diameter`` diodes across, left edge at diode ``x0``
196
+ ("test your thresholds" example data).
197
+
198
+ One run word per slice: a horizontal chord ``2w+1`` diodes wide, centred
199
+ on the circle's own centre column, ``w = floor(sqrt(r**2 - (j-c)**2))``
200
+ with ``r = diameter/2``, ``c = (diameter-1)/2``. A filled disk's area
201
+ ratio is close to ``pi/4`` (~0.79, measured on the proc file this writes),
202
+ comfortably above both ``area_ratio_z`` thresholds (0.5, 0.2) -- these
203
+ shapes exist to land in used bins, not to test that threshold.
204
+ """
205
+ r = diameter / 2
206
+ c = (diameter - 1) / 2
207
+ runs = []
208
+ for j in range(diameter):
209
+ w = int(math.floor(math.sqrt(max(r * r - (j - c) ** 2, 0.0))))
210
+ aa = 2 * w + 1
211
+ bb = x0 + int(c) - w
212
+ runs.append(run_word(aa, bb, new_slice=(j > 0)))
213
+ return runs
214
+
215
+
216
+ #: The measured deviation from the plan (S3.2): a genuinely one-diode-wide
217
+ #: outline (the plan's original description) landed at area ratio ~0.15 for
218
+ #: every diameter tried (measured 2026-09-13) -- BELOW both ``area_ratio_z``
219
+ #: thresholds (0.2, 0.5), because the outline's area shrinks linearly with
220
+ #: diameter while the normalising circle grows quadratically (``area_ratio ~
221
+ #: 8/(pi*diameter)`` for a 1-diode outline). No diameter separates the two
222
+ #: thresholds that way. :func:`ring_runs` is a true **annulus** instead --
223
+ #: outer diameter ``diameter``, hole diameter ``round(RING_HOLE_FRACTION *
224
+ #: diameter)`` -- whose area ratio is tunable by the hole fraction alone
225
+ #: (``~= 1 - RING_HOLE_FRACTION**2``, independent of diameter) and calibrated
226
+ #: to land between the two thresholds; see :data:`DENSE_RING_DIAMETER`'s
227
+ #: measured numbers.
228
+ RING_HOLE_FRACTION: float = 0.8
229
+
230
+
231
+ def ring_runs(diameter: int, x0: int) -> list[int]:
232
+ """A hollow disk (annulus) -- outer diameter ``diameter``, left edge at
233
+ diode ``x0`` -- to move the ``area_ratio_z`` threshold (
234
+ see :data:`RING_HOLE_FRACTION` for why this is an annulus and not a bare
235
+ outline).
236
+
237
+ Each slice is either one filled run (the polar caps, where the hole does
238
+ not reach) or two runs -- left arc, right arc -- separated by the
239
+ uncovered hole. Run words after the first *in the same slice* are
240
+ **relative**: ``spec.py``'s decoder accumulates ``b_base`` across a
241
+ slice's runs (``read_binary_SPEC.m:223-241``), so a second run's ``bb``
242
+ is the gap *from the end of the previous run*, not an absolute diode
243
+ index -- this is the bug the plan's own outline draft had (measured
244
+ 2026-09-13: an absolute second ``bb`` decoded ~50 diodes past the
245
+ intended wall).
246
+ """
247
+ r_out = diameter / 2
248
+ r_in = RING_HOLE_FRACTION * r_out
249
+ c = (diameter - 1) / 2
250
+ runs = []
251
+ for j in range(diameter):
252
+ w_out = int(math.floor(math.sqrt(max(r_out * r_out - (j - c) ** 2, 0.0))))
253
+ w_in_sq = r_in * r_in - (j - c) ** 2
254
+ if w_in_sq <= 0:
255
+ # The polar cap: the hole does not reach this slice, so it is a
256
+ # filled chord, exactly like one slice of :func:`disk_runs`.
257
+ aa = 2 * w_out + 1
258
+ bb = x0 + int(c) - w_out
259
+ runs.append(run_word(aa, bb, new_slice=(j > 0)))
260
+ continue
261
+ w_in = int(math.floor(math.sqrt(w_in_sq)))
262
+ left_len = w_out - w_in
263
+ right_len = w_out - w_in
264
+ left_start = x0 + int(c) - w_out
265
+ runs.append(run_word(left_len, left_start, new_slice=(j > 0)))
266
+ gap = 2 * w_in + 1 # the uncovered hole, between the two arcs
267
+ runs.append(run_word(right_len, gap, new_slice=False))
268
+ return runs
269
+
270
+
271
+ def bar_runs(length_slices: int, width_diodes: int, x0: int) -> list[int]:
272
+ """A filled rectangle, ``length_slices`` slices of ``width_diodes``
273
+ contiguous shadowed diodes starting at diode ``x0`` -- to move the
274
+ ``max_comp_img_ar`` aspect-ratio threshold. Fully filled
275
+ (area ratio 1.0), so it cannot also trip ``area_ratio_z``: it exists to
276
+ test the aspect-ratio ceiling alone.
277
+ """
278
+ return [run_word(width_diodes, x0, new_slice=(j > 0)) for j in range(length_slices)]
279
+
280
+
281
+ #: Diameters for the "disk" shape, spanning 6-40 diodes
282
+ #: (60-400 um at the 2D-S's 10 um diode) so particles land across used bins
283
+ #: 6-40 rather than piling into one. Fixed rather than a continuous draw so a
284
+ #: reader can reproduce the exact set of bins exercised without re-running
285
+ #: the generator.
286
+ DENSE_DISK_DIAMETERS: tuple[int, ...] = (6, 8, 10, 14, 18, 22, 26, 30, 34, 40)
287
+
288
+ #: A single fixed ring diameter, not drawn from a range: S3.2 calls for
289
+ #: *verifying* the area-ratio crossing against the proc file rather than
290
+ #: assuming it, which only makes sense for one calibrated shape. 16 diodes
291
+ #: is what this module was calibrated against (see the docstring of
292
+ #: :func:`build_dense_demo_flight`).
293
+ DENSE_RING_DIAMETER: int = 16
294
+
295
+ #: The bar geometry named directly in the plan (S3.2): aspect ratio 9/2 = 4.5,
296
+ #: strictly between ``ORACLES_PRODUCTION_REJECT_CONFIG.max_comp_img_ar`` (4)
297
+ #: and ``DEFAULT_REJECT_CONFIG.max_comp_img_ar`` (5).
298
+ DENSE_BAR_LENGTH_SLICES: int = 9
299
+ DENSE_BAR_WIDTH_DIODES: int = 2
300
+
301
+ #: The particle-clock gap design (raw counts) for the shattering/inter-arrival
302
+ #: test, named as module constants rather than inline literals so
303
+ #: ``tests/test_demo_flight_thresholds.py`` can patch :data:`DENSE_GAP_SHORT`
304
+ #: to :data:`DENSE_GAP_LONG`'s value and show the test it guards actually
305
+ #: fires (the plan's own "mutation for this guard"). At ``tas_mps=130`` and
306
+ #: the 2D-S's 10 um diode, :data:`DENSE_GAP_SHORT` reads back as a sub-6-us
307
+ #: gap (a shattering candidate) and :data:`DENSE_GAP_LONG` as safely above it
308
+ #: -- confirmed against a built proc file's own ``inter_arrival``, not
309
+ #: assumed (see :func:`build_dense_demo_flight`).
310
+ DENSE_GAP_SHORT: int = 20
311
+ DENSE_GAP_LONG: int = 4000
312
+
313
+ def _gap_safe_indices(particles_per_second: int) -> list[int]:
314
+ """0-based indices, within one record, that ``sizedist.py``'s shattering
315
+ ladder (``:1375-1382``) never flags 'S' under this module's own gap
316
+ design.
317
+
318
+ Index 0 is always flagged (the record-boundary reset, ``imgproc.py:967-
319
+ 972``). For ``ix`` in ``1 .. particles_per_second-1``, a design gap of 20
320
+ counts at particle ``ix+1`` (this module's ``j % 3 == 1`` rule) flags
321
+ **both** ``ix`` and ``ix-1`` (``sizedist.py:1381-1382``: ``auto_reject[ix
322
+ - 1:ix + 1] = 'S'``). Measured 2026-09-13: without this, a shape drawn at
323
+ an unsafe position is rejected by the shattering test regardless of any
324
+ OTHER threshold, which silently zeroed test 3's (``max_comp_img_ar``)
325
+ used-bin difference the first time this flight was built -- every bar
326
+ happened to land on a flagged position. Bars are pinned to these safe
327
+ slots below so the aspect-ratio test can never be masked that way.
328
+ """
329
+ unsafe = {0}
330
+ for ix in range(1, particles_per_second):
331
+ if ix % 3 == 0:
332
+ unsafe.add(ix - 1)
333
+ unsafe.add(ix)
334
+ return [i for i in range(particles_per_second) if i not in unsafe]
335
+
336
+
337
+ def build_dense_demo_flight(path, n_seconds: int = 20, seed: int = 20260913,
338
+ particles_per_second: int = 12, tas_mps: float = 130.0,
339
+ start_hour: int = 6, start_minute: int = 6,
340
+ start_second: int = 40,
341
+ distinct_counters: bool = False) -> Path:
342
+ """Write a DENSE synthetic raw ``.2DS`` file: example data users can
343
+ "test their thresholds" on.
344
+
345
+ The plain :func:`build_demo_flight` cannot: its five particles sit below
346
+ the first used bin's lower edge (0.055 mm) and every ``inter_arrival`` is
347
+ identically zero (each is the only particle of its record), so no reject
348
+ or shattering threshold can ever move a used-bin count -- measured, S3.1.
349
+ This flight fixes both. Per second, one record holds
350
+ ``particles_per_second`` image packets **concatenated in the same
351
+ record** (each sized to survive S3's centring and accept ladder -- see
352
+ :func:`disk_runs`/:func:`ring_runs`/:func:`bar_runs`), followed by the
353
+ housekeeping (TAS) record as before. Per record: exactly 2 bars, pinned
354
+ to :func:`_gap_safe_indices` slots (never shatter-flagged, so the
355
+ aspect-ratio test is never confounded by the shattering test); up to 2
356
+ rings at random remaining positions; the rest disks. ``rng =
357
+ np.random.default_rng(seed)`` makes the flight fully reproducible: the
358
+ same seed always draws the same diameters, ring positions and disk
359
+ positions.
360
+
361
+ **Multi-particle records are not new plumbing.** ``spec.get_img`` already
362
+ walks its whole 2048-word window for repeated ``MARKER_2S`` packets (real
363
+ 2D-S records hold many small particles); this only exercises a path the
364
+ plain demo flight, at one particle per record, never has.
365
+
366
+ **The inter-arrival design.** ``imgproc.py:967-972`` (preserved bug)
367
+ zeroes ``inter_arrival`` for the first particle of every
368
+ record, so only particles 2..``particles_per_second`` within a record
369
+ carry a real gap. For the ``j``-th particle of a record (1-based, ``j >
370
+ 1``), the particle clock advances by 20 raw counts when ``j % 3 == 1``,
371
+ else 4000. At ``tas_mps=130`` and the 2D-S's 10 um diode, one count is
372
+ ``ds / 1e3 / TAS`` seconds (``imgproc.py:955``) -- confirmed against a
373
+ built proc file, not assumed: 20 counts reads back as a sub-6-us gap
374
+ (shattering-candidate) and 4000 as a safely-supra-6-us one, against
375
+ ``sizeDist``'s per-probe default threshold (the twelfth
376
+ argument). The record-boundary reset supplies additional close-together
377
+ (zero-gap) events for free.
378
+
379
+ Raw file record count is exactly ``2 * n_seconds`` (one image record, one
380
+ HK record, per second) -- a stranger can predict the file size from that
381
+ alone, as :func:`build_demo_flight` already documents.
382
+ """
383
+ rng = np.random.default_rng(seed)
384
+ safe = _gap_safe_indices(particles_per_second)
385
+ # Two bars per record, pinned to gap-safe slots (see _gap_safe_indices) so
386
+ # the aspect-ratio test never competes with the shattering test. Up to two
387
+ # rings per record at whatever positions remain, drawn once per record so
388
+ # a record's ring count never depends on how many safe slots existed.
389
+ bar_slots = set(safe[:2])
390
+ records = []
391
+ t_particle = 0x1000_0000
392
+ n_packets = 0
393
+ for sec in range(n_seconds):
394
+ header = (2016, 9, 2, 6, start_hour, start_minute, start_second + sec, 250)
395
+ non_bar = [i for i in range(particles_per_second) if i not in bar_slots]
396
+ n_rings = min(2, len(non_bar))
397
+ ring_slots = (set(rng.choice(non_bar, size=n_rings, replace=False).tolist())
398
+ if n_rings else set())
399
+ payload: list[int] = []
400
+ for j in range(1, particles_per_second + 1):
401
+ i = j - 1
402
+ if i in bar_slots:
403
+ shape = "bar"
404
+ elif i in ring_slots:
405
+ shape = "ring"
406
+ else:
407
+ shape = "disk"
408
+ if shape == "disk":
409
+ diameter = int(rng.choice(DENSE_DISK_DIAMETERS))
410
+ x0 = int(rng.integers(16, 112 - diameter))
411
+ runs = disk_runs(diameter, x0)
412
+ n_s = diameter
413
+ elif shape == "ring":
414
+ diameter = DENSE_RING_DIAMETER
415
+ x0 = int(rng.integers(16, 112 - diameter))
416
+ runs = ring_runs(diameter, x0)
417
+ n_s = diameter
418
+ else:
419
+ x0 = int(rng.integers(16, 112 - DENSE_BAR_WIDTH_DIODES))
420
+ runs = bar_runs(DENSE_BAR_LENGTH_SLICES, DENSE_BAR_WIDTH_DIODES, x0)
421
+ n_s = DENSE_BAR_LENGTH_SLICES
422
+ if j > 1:
423
+ t_particle += DENSE_GAP_SHORT if (j % 3 == 1) else DENSE_GAP_LONG
424
+ payload.extend(image_packet(runs, n_s, channel="H",
425
+ pc=_packet_counter(n_packets, distinct_counters),
426
+ t_particle=t_particle))
427
+ n_packets += 1
428
+ records.append((header, payload))
429
+ tod = start_hour * 3600 + start_minute * 60 + start_second + sec
430
+ records.append((header, _hk_words(tas_mps, tod)))
431
+ # The gap to next record's first particle is unobservable: :967-972
432
+ # always writes 0 for a record's first particle regardless of the
433
+ # clock value, so this advance exists only to keep the 32-bit clock
434
+ # monotonically increasing across the whole file (never wrapping).
435
+ t_particle += DENSE_GAP_LONG
436
+ return raw_file(str(path), records)
437
+
438
+
439
+ # ---------------------------------------------------------------------------
440
+ # The FEATURE flight: the instrument faults the corrections act on
441
+ # ---------------------------------------------------------------------------
442
+ #
443
+ # The plain and dense flights above are clean by construction, so every enhancement
444
+ # whose subject is a *fault* -- a clipped particle, an out-of-focus ring, a stuck or
445
+ # noisy diode, a duplicated housekeeping second, a clock glitch -- measured an
446
+ # A/B of exactly zero on them (the vacuous A/Bs of 2026-09-14/15: A7, Z8, Z21, GL4).
447
+ # :func:`build_feature_demo_flight` writes one more flight, alongside and never in
448
+ # place of those two (their bytes are tracked and tested), that carries one of each.
449
+ # Every feature is listed in :data:`FEATURES` with the MATLAB line it exercises; every
450
+ # particle is listed, in raw order, by :func:`feature_particle_manifest`, which the
451
+ # tests read to find each feature in the decoded output.
452
+
453
+ #: The 2D-S array width, in diodes (``read_binary_SPEC.m``'s 128-bit slice).
454
+ N_DIODES: int = 128
455
+
456
+ #: Particle-clock advances (raw counts) for the feature flight: ``FEATURE_GAP_LONG``
457
+ #: between ordinary particles (a supra-6-us gap at 130 m/s, the dense flight's own
458
+ #: :data:`DENSE_GAP_LONG`), ``FEATURE_GAP_BURST`` inside a shattering burst (the dense
459
+ #: flight's sub-6-us :data:`DENSE_GAP_SHORT`).
460
+ FEATURE_GAP_LONG: int = 4000
461
+ FEATURE_GAP_BURST: int = 20
462
+
463
+ #: Disk diameters (diodes) for the ordinary particles: 0.12-0.48 mm at the 2D-S's
464
+ #: 10 um diode, so they fill the v3.1.4 grid's used bins (6+, above 0.055 mm) AND
465
+ #: v3.5's 2D-S grid, which starts at 0.2 mm (measured on this flight's v3.5 sd:
466
+ #: ``bin_min[0] = 0.2``) -- the dense flight's 0.06-0.40 mm disks mostly fall below it.
467
+ FEATURE_DISK_MIN: int = 12
468
+ FEATURE_DISK_MAX: int = 48
469
+
470
+ #: The stuck diode (1-based) -- shadowed in every slice of every particle of the
471
+ #: stuck-diode seconds -- and the noisy diode, which fires isolated one-pixel
472
+ #: particles. Both are well away from the particles' own bodies and from diode 32,
473
+ #: so neither is confounded with the 32-diode hollow packing (A1).
474
+ FEATURE_STUCK_DIODE: int = 100
475
+ FEATURE_NOISY_DIODE: int = 20
476
+
477
+ #: What the feature flight carries, one entry per feature: the one-second record it
478
+ #: occupies (0-based second index, see :func:`build_feature_demo_flight`), the
479
+ #: MATLAB line(s) the feature exercises, and the enhancement(s) whose A/B it exists
480
+ #: to make non-vacuous. Read by the tests, which assert each is present in the
481
+ #: decoded output rather than trusting this table.
482
+ FEATURES: dict[str, dict] = {
483
+ "background": {
484
+ "seconds": (0, 1, 2, 3, 13),
485
+ "matlab": "sizeDist.m:1080-1100 (good/bad split): ordinary accepted disks",
486
+ "for": "the used-bin population every sd-level A/B is measured against",
487
+ },
488
+ "edge_clipped": {
489
+ "seconds": (4,),
490
+ "matlab": ("calculate_reject_unified.m:213-216 (touching_edge 't'); "
491
+ "imgProc_sm.m:897 (touching_edge - '0' = 68); sizeDist.m:1094-1100 "
492
+ "(entirein / centerin masks)"),
493
+ "for": "A7 partial_image_habit (Korolev & Sussman 2000 partials), SAmethod 1",
494
+ },
495
+ "hollow_ring": {
496
+ "seconds": (5,),
497
+ "matlab": ("calculate_reject_unified.m:279-280, :408-530 (is_it_hollow, "
498
+ "rej_hollow=1 -> 'h'); :465 (32-diode packing, A1); v3.5 "
499
+ "is_it_hollow (no middle-third window) and imgProc_sm.m:1276 "
500
+ "(D/size_factor)"),
501
+ "for": "A1 wide_hollow_fix, A3 spot_edge_fix, A12 outoffocus, C5 hole_edge_swap, GL4",
502
+ },
503
+ "one_diode_streak": {
504
+ "seconds": (6,),
505
+ "matlab": ("calculate_reject_unified.m:269 (max_comp_img_ar -> 'a'); "
506
+ "sizeDist.m:1316-1340 (a second with data but no accepted particle)"),
507
+ "for": "spec_artefact_filter line noise, A8 overload_accounting_fix",
508
+ },
509
+ "stuck_diode": {
510
+ "seconds": (7, 8),
511
+ "matlab": ("read_binary_SPEC.m:223-241 (a second run in the same slice); "
512
+ "calculate_reject_unified.m:188-196 (split), :228 (>80% block)"),
513
+ "for": "ml_accept_reject Method A (stuck-diode merge), spec_artefact_filter",
514
+ },
515
+ "noisy_diode": {
516
+ "seconds": (9,),
517
+ "matlab": "imgProc_sm.m diode_stats (per-diode shadow counts); one-pixel particles",
518
+ "for": "spec_artefact_filter's noisy-diode exception and dot noise",
519
+ },
520
+ "shattering_burst": {
521
+ "seconds": (10,),
522
+ "matlab": ("sizeDist.m:874 (6 us default threshold), :1375-1382 ('S' on both "
523
+ "neighbours), :1036/:1169 (reacceptance scans the first event only)"),
524
+ "for": ("D3 reaccept_every_event_fix, intarr_policy, distance_rejection, "
525
+ "poisson_restore"),
526
+ },
527
+ "duplicated_tas_second": {
528
+ "seconds": (11,),
529
+ "matlab": ("sizeDist.m:88 (floor to whole seconds), :476 (one_sec_times = "
530
+ "tas_time), :627-644 (an empty [t, t) interval still consumes its "
531
+ "particles)"),
532
+ "for": "A17 tas_grid_fix",
533
+ },
534
+ "missing_tas_second": {
535
+ "seconds": (12,),
536
+ "matlab": "sizeDist.m:476, :549-596 (a gap in one_sec_times)",
537
+ "for": "A17 tas_grid_fix (the other half: a second with no housekeeping)",
538
+ },
539
+ "bad_particle_timestamp": {
540
+ "seconds": (14,),
541
+ "matlab": ("imgProc_sm.m:379 (Time from the record header); sizeDist.m:544-545 "
542
+ "(x(find(diff(x)<0)+1:end) += 240000 -- one glitch files every later "
543
+ "particle 24 h late)"),
544
+ "for": "the CIP timestamp cascade (the rollover_fix enhancement)",
545
+ },
546
+ "cascade_victims": {
547
+ "seconds": (15, 16),
548
+ "matlab": "sizeDist.m:544-545 (the particles after the glitch)",
549
+ "for": "the measured size of the cascade",
550
+ },
551
+ "last_record_particles": {
552
+ "seconds": (17,),
553
+ "matlab": ("read_binary_SPEC.m (the final record is never a primary: the loop "
554
+ "decodes (N, N+1) and breaks on EOF)"),
555
+ "for": "E5 last_record_fix",
556
+ },
557
+ }
558
+
559
+ #: The header second of the one glitched record, as an HHMMSS offset: the record
560
+ #: carries 00:MM:SS instead of 06:MM:SS -- a six-hour backwards jump, the shape of a
561
+ #: corrupted hour field. It is the one decrease in the particle ``Time`` series.
562
+ FEATURE_GLITCH_HOUR: int = 0
563
+
564
+ #: The duplicated second's second housekeeping packet carries this TAS, so which of
565
+ #: the two rows survives a collapse (A17: the first, MATLAB's unique(...,'first')) is
566
+ #: visible in the output rather than inferred.
567
+ FEATURE_DUPLICATE_TAS_MPS: float = 131.0
568
+
569
+
570
+ def _runs_from_image(img) -> list[int]:
571
+ """Run words for a boolean image of shape ``(n_slices, 128)`` (True = shadowed).
572
+
573
+ The inverse of ``spec._decode_runs_scalar`` (``read_binary_SPEC.m:223-241``): the
574
+ first run of a slice carries its clear count from diode 1 and the new-slice flag
575
+ (on every slice but the first); later runs in the same slice carry the clear gap
576
+ from the end of the previous run -- the relative encoding :func:`ring_runs`
577
+ documents. An all-clear slice is one ``aa = 0`` word, which the decoder turns
578
+ into an empty run.
579
+ """
580
+ img = np.asarray(img, dtype=bool)
581
+ assert img.ndim == 2 and img.shape[1] == N_DIODES
582
+ runs: list[int] = []
583
+ for j, row in enumerate(img):
584
+ padded = np.concatenate(([False], row, [False])).astype(np.int8)
585
+ edges = np.flatnonzero(np.diff(padded))
586
+ starts, ends = edges[0::2], edges[1::2]
587
+ if starts.size == 0:
588
+ runs.append(run_word(0, 0, new_slice=(j > 0)))
589
+ continue
590
+ prev_end = 0
591
+ for k, (s, e) in enumerate(zip(starts, ends, strict=True)):
592
+ runs.append(run_word(int(e - s), int(s - prev_end), new_slice=(j > 0 and k == 0)))
593
+ prev_end = int(e)
594
+ return runs
595
+
596
+
597
+ def _disk_image(diameter: int, centre: float) -> np.ndarray:
598
+ """A filled disk ``diameter`` slices long, centred on 0-based column ``centre``,
599
+ clipped to the 128-diode array (a disk centred near an end is a clipped,
600
+ edge-touching particle)."""
601
+ r = diameter / 2
602
+ c = (diameter - 1) / 2
603
+ img = np.zeros((diameter, N_DIODES), dtype=bool)
604
+ for j in range(diameter):
605
+ w = math.sqrt(max(r * r - (j - c) ** 2, 0.0))
606
+ lo = int(math.floor(centre - w + 0.5))
607
+ hi = int(math.floor(centre + w + 0.5))
608
+ img[j, max(lo, 0):min(hi + 1, N_DIODES)] = True
609
+ return img
610
+
611
+
612
+ def _annulus_image(diameter: int, hole_fraction: float, left: int,
613
+ spot_diameter: int = 0) -> np.ndarray:
614
+ """An annulus (an out-of-focus drop's bright centre), outer diameter
615
+ ``diameter``, hole diameter ``hole_fraction * diameter``, leftmost diode at
616
+ 0-based column ``left``; ``spot_diameter > 0`` adds Korolev's central (Poisson)
617
+ spot inside the hole."""
618
+ r_out = diameter / 2
619
+ r_in = hole_fraction * r_out
620
+ c = (diameter - 1) / 2
621
+ yy, xx = np.mgrid[0:diameter, 0:diameter]
622
+ rr = np.hypot(yy - c, xx - c)
623
+ body = (rr <= r_out) & (rr > r_in)
624
+ if spot_diameter:
625
+ body |= rr <= spot_diameter / 2
626
+ img = np.zeros((diameter, N_DIODES), dtype=bool)
627
+ img[:, left:left + diameter] = body
628
+ return img
629
+
630
+
631
+ def _streak_image(length_slices: int, diode: int) -> np.ndarray:
632
+ """One diode (1-based) shadowed for ``length_slices`` consecutive slices."""
633
+ img = np.zeros((length_slices, N_DIODES), dtype=bool)
634
+ img[:, diode - 1] = True
635
+ return img
636
+
637
+
638
+ def _record_header(hour: int, minute: int, second: int) -> tuple:
639
+ """The eight header words (``readRecord``, :170-182), the demo flights' own
640
+ date and millisecond."""
641
+ return (2016, 9, 2, 6, hour, minute, second, 250)
642
+
643
+
644
+ def _feature_seconds(rng) -> list[dict]:
645
+ """The flight's content, second by second: a list of dicts with the particle
646
+ images (``shapes``: list of ``(feature, image, gap)``), whether the second gets
647
+ housekeeping (``hk``: 0, 1 or 2 packets) and whether its header time is the
648
+ glitch. Drawn once from ``rng`` so the flight is reproducible from its seed."""
649
+
650
+ def disks(n, feature="background", lo=FEATURE_DISK_MIN, hi=FEATURE_DISK_MAX):
651
+ out = []
652
+ for _ in range(n):
653
+ d = int(rng.integers(lo, hi + 1))
654
+ centre = float(rng.integers(34 + d // 2, 95 - d // 2))
655
+ out.append((feature, _disk_image(d, centre), FEATURE_GAP_LONG))
656
+ return out
657
+
658
+ secs: list[dict] = []
659
+ for _ in range(4): # 0-3: background
660
+ secs.append({"shapes": disks(8), "hk": 1})
661
+ # 4: edge-clipped -- three disks clipped at diode 1, three at diode 128, of
662
+ # growing size (the clipped fraction grows with it), and two whole disks.
663
+ edge = []
664
+ for d, off in ((16, 2.0), (30, 4.0), (44, 6.0)):
665
+ edge.append(("edge_clipped", _disk_image(d, off), FEATURE_GAP_LONG))
666
+ edge.append(("edge_clipped", _disk_image(d, N_DIODES - 1 - off), FEATURE_GAP_LONG))
667
+ secs.append({"shapes": edge + disks(2), "hk": 1})
668
+ # 5: hollow rings -- three inside diodes 1-32 (the only span v3.1.4's hollow
669
+ # test packs, :465), three beyond it; hole fractions spanning a thin and a thick
670
+ # ring; two carry a Poisson spot.
671
+ rings = []
672
+ for d, frac, left, spot in ((24, 0.5, 2, 0), (28, 0.6, 2, 0), (22, 0.45, 5, 4),
673
+ (30, 0.5, 50, 0), (40, 0.65, 44, 0), (34, 0.5, 70, 6)):
674
+ rings.append(("hollow_ring", _annulus_image(d, frac, left, spot), FEATURE_GAP_LONG))
675
+ secs.append({"shapes": rings + disks(2), "hk": 1})
676
+ # 6: one-diode streaks only -- a second whose every particle is an artefact.
677
+ streaks = [("one_diode_streak", _streak_image(n, dio), FEATURE_GAP_LONG)
678
+ for n, dio in ((30, 45), (40, 64), (24, 90), (36, 110))]
679
+ secs.append({"shapes": streaks, "hk": 1})
680
+ # 7-8: stuck diode -- every particle also shadows FEATURE_STUCK_DIODE in every slice.
681
+ for _ in range(2):
682
+ stuck = []
683
+ for feature, img, gap in disks(6, "stuck_diode", lo=12, hi=30):
684
+ img = img.copy()
685
+ img[:, FEATURE_STUCK_DIODE - 1] = True
686
+ stuck.append((feature, img, gap))
687
+ secs.append({"shapes": stuck, "hk": 1})
688
+ # 9: noisy diode -- ten one-pixel particles on FEATURE_NOISY_DIODE among four disks.
689
+ noisy = [("noisy_diode", _streak_image(1, FEATURE_NOISY_DIODE), FEATURE_GAP_LONG)
690
+ for _ in range(10)]
691
+ mixed = disks(4)
692
+ secs.append({"shapes": noisy[:5] + mixed[:2] + noisy[5:] + mixed[2:], "hk": 1})
693
+ # 10: shattering burst -- two bursts of six (sub-6-us gaps) separated by long gaps,
694
+ # a larger "parent" drop opening each, then two isolated disks.
695
+ burst = []
696
+ for _ in range(2):
697
+ burst.append(("shattering_burst", _disk_image(40, 64.0), FEATURE_GAP_LONG))
698
+ for _k in range(6):
699
+ d = int(rng.integers(6, 14))
700
+ burst.append(("shattering_burst", _disk_image(d, float(rng.integers(30, 98))),
701
+ FEATURE_GAP_BURST))
702
+ secs.append({"shapes": burst + disks(2), "hk": 1})
703
+ secs.append({"shapes": disks(6, "duplicated_tas_second"), "hk": 2}) # 11
704
+ secs.append({"shapes": disks(6, "missing_tas_second"), "hk": 0}) # 12
705
+ secs.append({"shapes": disks(8), "hk": 1}) # 13
706
+ secs.append({"shapes": disks(1, "bad_particle_timestamp", 30, 30), # 14
707
+ "hk": 1, "glitch": True})
708
+ for _ in range(2): # 15-16
709
+ secs.append({"shapes": disks(6, "cascade_victims"), "hk": 1})
710
+ secs.append({"shapes": disks(4, "last_record_particles"), "hk": 1, # 17
711
+ "last": True})
712
+ return secs
713
+
714
+
715
+ def feature_particle_manifest(seed: int = 20260915) -> list[dict]:
716
+ """Every particle of :func:`build_feature_demo_flight` in raw order:
717
+ ``{"second", "feature", "n_slices", "width", "min_diode", "max_diode", "area"}``
718
+ (diodes 1-based). Recomputed from the same seed, never stored, so it cannot
719
+ drift from the flight it describes."""
720
+ rng = np.random.default_rng(seed)
721
+ out = []
722
+ for sec, spec_ in enumerate(_feature_seconds(rng)):
723
+ for feature, img, _gap in spec_["shapes"]:
724
+ cols = np.flatnonzero(img.any(axis=0))
725
+ out.append({
726
+ "second": sec, "feature": feature, "n_slices": int(img.shape[0]),
727
+ "width": int(cols.size and cols[-1] - cols[0] + 1),
728
+ "min_diode": int(cols[0] + 1) if cols.size else 0,
729
+ "max_diode": int(cols[-1] + 1) if cols.size else 0,
730
+ "area": int(img.sum()),
731
+ })
732
+ return out
733
+
734
+
735
+ def build_feature_demo_flight(path, seed: int = 20260915, tas_mps: float = 130.0,
736
+ start_hour: int = 6, start_minute: int = 6,
737
+ start_second: int = 40) -> Path:
738
+ """Write the FEATURE synthetic raw ``.2DS`` file: eighteen
739
+ one-second records carrying, second by second, the faults :data:`FEATURES`
740
+ lists -- edge-clipped particles at both array ends, hollow and Poisson-spot
741
+ rings inside and beyond diode 32, one-diode streaks, a stuck and a noisy diode,
742
+ a two-event shattering burst, a duplicated and a missing housekeeping (TAS)
743
+ second, one record whose header hour is corrupted (the one decrease in the
744
+ particle ``Time`` series, ``sizeDist.m:544-545``), and particles in the file's
745
+ final record (which ``read_binary_SPEC.m`` never decodes as a primary).
746
+
747
+ Record order per second: the image record, then its housekeeping packet(s) --
748
+ except the final second, whose housekeeping record comes *first* so that its
749
+ image record is the last record of the file. The glitched second's housekeeping
750
+ record carries the correct header time (only the image record's hour is
751
+ corrupted), so the TAS grid itself never goes backwards and the missing second
752
+ stays the only gap in it -- only the particle times go backwards, which is the
753
+ CIP shape. Not validated science, exactly as the other two flights.
754
+ """
755
+ rng = np.random.default_rng(seed)
756
+ records = []
757
+ t_particle = 0x2000_0000
758
+ t0 = start_hour * 3600 + start_minute * 60 + start_second
759
+ for sec, spec_ in enumerate(_feature_seconds(rng)):
760
+ tod = t0 + sec
761
+ hh, mm, ss = tod // 3600, (tod % 3600) // 60, tod % 60
762
+ header = _record_header(hh, mm, ss)
763
+ image_header = _record_header(FEATURE_GLITCH_HOUR, mm, ss) if spec_.get("glitch") \
764
+ else header
765
+ payload: list[int] = []
766
+ for k, (_feature, img, gap) in enumerate(spec_["shapes"]):
767
+ if k > 0:
768
+ t_particle += gap
769
+ payload.extend(image_packet(_runs_from_image(img), img.shape[0], channel="H",
770
+ pc=7, t_particle=t_particle))
771
+ assert len(payload) <= spec.DATA_WORDS, (sec, len(payload))
772
+ hk = [(header, _hk_words(FEATURE_DUPLICATE_TAS_MPS if n else tas_mps, tod))
773
+ for n in range(spec_["hk"])]
774
+ if spec_.get("last"):
775
+ records.extend(hk)
776
+ records.append((image_header, payload))
777
+ else:
778
+ records.append((image_header, payload))
779
+ records.extend(hk)
780
+ t_particle += FEATURE_GAP_LONG
781
+ return raw_file(str(path), records)
782
+
783
+
784
+ # ---------------------------------------------------------------------------
785
+ # What the product will look like, said at the point of writing the flight
786
+ # ---------------------------------------------------------------------------
787
+ #
788
+ # Recorded 2026-09-16, measured 2026-09-17: a stranger runs the published quickstart,
789
+ # sees ``ALL DONE``, opens the 68 MB combined product it wrote and finds 99.72 % of its
790
+ # cells NaN, with nothing in either command's output having said so. The padding is
791
+ # faithful -- ``combine_sizedist.m`` pads every second between the flight date it reads
792
+ # out of the raw STEM and the first second the records actually carry -- but a user who
793
+ # has not read the user guide's Quickstart section has no way to know that, and a
794
+ # mostly-NaN file looks exactly like a broken one.
795
+ #
796
+ # This tool cannot fix the padding without changing what it writes, and its bytes are
797
+ # tracked (``tests/data/demo_flight_v35_*``, the pinned threshold counts in
798
+ # ``tests/test_demo_flight_thresholds.py``). What it CAN do is say, before the pipeline
799
+ # is ever started, exactly how long the time axis will be and how much of it can carry
800
+ # data -- all of which follows from the stem it was given and the clock it is about to
801
+ # stamp into the records, both of which are this function's own inputs.
802
+
803
+
804
+ def _stem_time_of_day(stem: str) -> int | None:
805
+ """Seconds after midnight in a ``base<YYMMDDhhmmss>`` stem, or ``None``.
806
+
807
+ The combine step reads the flight's date and time out of the raw stem
808
+ (``combine_sizedist.m``, ``summaryfile(1).name``), never out of the record
809
+ headers -- measured 2026-09-17 on the quickstart's own product, whose
810
+ ``Time Vector`` starts at MATLAB datenum 736330.0 (2016-01-01 00:00:00) from
811
+ the stem ``base160101000000`` while every record header in that same file
812
+ carries 2016-09-06 (the header tuple is year, month, weekday, day, so its
813
+ 2 is the weekday). A stem this cannot parse returns ``None`` rather than a
814
+ guess.
815
+ """
816
+ if not stem.startswith("base"):
817
+ return None
818
+ digits = stem[4:]
819
+ if len(digits) != 12 or not digits.isdigit():
820
+ return None
821
+ hh, mm, ss = int(digits[6:8]), int(digits[8:10]), int(digits[10:12])
822
+ if hh > 23 or mm > 59 or ss > 59:
823
+ return None
824
+ return hh * 3600 + mm * 60 + ss
825
+
826
+
827
+ def expected_product_shape(path, n_seconds: int, *, start_hour: int = 6,
828
+ start_minute: int = 6,
829
+ start_second: int = 40) -> dict | None:
830
+ """How long the combined product's time axis will be, and how much of it can
831
+ carry data, for a flight written to ``path`` with these arguments.
832
+
833
+ Returns ``None`` when the stem does not carry a parseable ``base<YYMMDDhhmmss>``
834
+ timestamp, or when that timestamp is at or after the records' own clock -- the
835
+ padding direction this has not been measured in, and a number nobody measured
836
+ does not get printed.
837
+
838
+ **How each field was established.** ``data_seconds`` is ``n_seconds - 1``:
839
+ measured 2026-09-17 on the quickstart's own five-second run, whose ``.tas.csv``
840
+ carries four seconds (60640-60643) because the raw file's LAST record is the
841
+ fifth second's housekeeping packet and ``read_binary_SPEC.m`` never decodes a
842
+ file's last record -- the decode and ``proc`` do carry all five seconds of
843
+ particles (60 particles across 60640-60644 on the dense flight), and it is
844
+ stage 4, gridding on the TAS seconds, that drops the fifth. ``axis_seconds``
845
+ is derived from the same run: 22,004 = (22,000 seconds from the stem's
846
+ 00:00:00 to the records' 06:06:40) + 4 data seconds.
847
+ """
848
+ stem_tod = _stem_time_of_day(Path(path).stem)
849
+ if stem_tod is None:
850
+ return None
851
+ record_tod = start_hour * 3600 + start_minute * 60 + start_second
852
+ pad = record_tod - stem_tod
853
+ if pad < 0:
854
+ return None
855
+ data_seconds = max(n_seconds - 1, 0)
856
+ axis = pad + data_seconds
857
+ return {
858
+ "stem_time_of_day": stem_tod,
859
+ "record_time_of_day": record_tod,
860
+ "pad_seconds": pad,
861
+ "data_seconds": data_seconds,
862
+ "axis_seconds": axis,
863
+ "populated_fraction": (data_seconds / axis) if axis else 0.0,
864
+ }
865
+
866
+
867
+ def _hhmmss(seconds: int) -> str:
868
+ return f"{seconds // 3600:02d}:{(seconds % 3600) // 60:02d}:{seconds % 60:02d}"
869
+
870
+
871
+ #: Measured 2026-09-17 on a five-second dense flight run through
872
+ #: ``--preset DEMO_2DS_H --stages 234c``: 60 particles decoded, 50 accepted by S3
873
+ #: (10 bars rejected ``'a'``, by design), 11 counted into used bins across the four
874
+ #: TAS seconds, ``Mean Area Ratio`` finite in 11 of 2,816,512 cells and touching
875
+ #: two of those seconds. Quoted in the tool's own summary so a reader knows what
876
+ #: "not empty" amounts to here.
877
+ DENSE_MEASURED_COUNTED: int = 11
878
+
879
+ #: The same five-second dense flight on engine 3.5 (``--profile stock-v3.5`` with the
880
+ #: builder's own aircraft file, ``--borrowed-combine``): ``count`` in ``sd`` sums to 48,
881
+ #: measured 2026-10-05 by ``tests/test_quickstart_runs.py`` once engine 3.5 sized the demo
882
+ #: 2D-S on the 2D-S 128-bin ladder by default (15 on the stock HVPS table, 2026-09-27).
883
+ #: The message used to quote only the 3.1.4 figure, with no engine named, while the v3.5
884
+ #: run a new user is steered to printed a different one.
885
+ DENSE_MEASURED_COUNTED_V35: int = 48
886
+
887
+ #: Measured 2026-09-17 the same way on the PLAIN flight: 5 particles, all 0.048 mm
888
+ #: (below the first used bin's lower edge, 0.055 mm), each the only particle of its
889
+ #: record so every ``inter_arrival`` reads 0 -- the production shattering
890
+ #: configuration rejects all five. ``count`` sums to 0, ``mean_area_ratio`` is finite
891
+ #: in 0 of 512 cells, ``Reject_ratio`` is 1.0 in every second.
892
+ PLAIN_MEASURED_COUNTED: int = 0
893
+
894
+
895
+ def summary_lines(path, n_seconds: int, *, dense: bool) -> list[str]:
896
+ """The lines :func:`main` prints after writing a flight: what the combined
897
+ product's time axis will look like, and whether its size distribution will
898
+ have anything in it. Returned rather than printed so a test can read them.
899
+ """
900
+ lines: list[str] = []
901
+ shape = expected_product_shape(path, n_seconds)
902
+ if shape is not None:
903
+ lines.append(
904
+ f"combined product to expect: a {shape['axis_seconds']:,}-second time axis "
905
+ f"of which {shape['data_seconds']} carry data "
906
+ f"({100 * shape['populated_fraction']:.3g} %); the other "
907
+ f"{shape['pad_seconds']:,} are NaN.")
908
+ lines.append(
909
+ f" why: the combine step dates the flight from the file-name STEM "
910
+ f"({_hhmmss(shape['stem_time_of_day'])}), while these records are stamped "
911
+ f"{_hhmmss(shape['record_time_of_day'])}, and every second between is padded. "
912
+ "A NaN there means the probe wrote nothing that second, not an error.")
913
+ lines.append(
914
+ f" {shape['data_seconds']} data seconds and not {n_seconds}: the file's last "
915
+ "record is the last second's housekeeping packet, and the 2D-S reader never "
916
+ "decodes a file's last record, so the .tas.csv carries one second fewer than the "
917
+ "decode does and stage 4 grids on the TAS seconds (measured 2026-09-17).")
918
+ if shape["pad_seconds"]:
919
+ clock = _hhmmss(shape["record_time_of_day"]).replace(":", "")
920
+ aligned = f"base{Path(path).stem[4:10]}{clock}"
921
+ lines.append(
922
+ f" to get a product with no padding at all, name the file {aligned}"
923
+ f"{Path(path).suffix} -- the stem then matches the records' own clock.")
924
+ if dense:
925
+ lines.append(
926
+ f"the DENSE flight's size distribution is small, not empty: at --seconds 5, "
927
+ f"60 particles decode and {DENSE_MEASURED_COUNTED_V35} are counted into size bins "
928
+ "on engine 3.5.")
929
+ else:
930
+ lines.append(
931
+ "WARNING: this PLAIN flight's size distribution will be EMPTY. Measured "
932
+ "2026-09-17 under --preset DEMO_2DS_H: its particles are all 0.048 mm, below "
933
+ "the first used bin's lower edge (0.055 mm), and each is the only particle of "
934
+ "its record, so every inter-arrival reads 0 and the production shattering "
935
+ f"configuration rejects all of them -- Counts sum to {PLAIN_MEASURED_COUNTED}, "
936
+ "Mean Area Ratio is NaN in every cell and Reject Ratio is 1.0 in every second.")
937
+ lines.append(
938
+ " pass --dense for a flight whose distribution has particles in it.")
939
+ return lines
940
+
941
+
942
+ def next_lines(written, aircraft, py):
943
+ """The "next" commands printed after a demo flight is written.
944
+
945
+ The engine 3.1.4 line is printed only when that engine is installed (it is not
946
+ part of this package).
947
+ """
948
+ name = str(written)
949
+ folder = name.rsplit("/", 1)[0].rsplit("\\", 1)[0] if ("/" in name or "\\" in name) else "."
950
+ out = ["next -- engine 3.5, the default (re-run with --with-config to write run.toml "
951
+ "beside the flight; a repository checkout can use examples/start_here/run.toml, "
952
+ f"the same settings):\n arrayprobe run {folder}/run.toml {written} --yes"]
953
+ if importlib.util.find_spec("arrayprobe.reject") is not None:
954
+ out.append(f"or engine 3.1.4, the ORACLES-validation anchor:\n {py} "
955
+ f"scripts/run_flight.py --preset DEMO_2DS_H --engine 3.1.4 --port-validation "
956
+ f"--stages 234c --yes {written}")
957
+ return out
958
+
959
+
960
+ #: The ready-to-run settings ``--with-config`` writes beside the demo flight: the same
961
+ #: choices as the repository's ``examples/start_here/run.toml``, with every path relative
962
+ #: to the folder the flight is written in, so ``arrayprobe run <folder>/run.toml`` works
963
+ #: from a bare ``pip install`` with no ``examples/`` folder.
964
+ DEMO_RUN_TOML = """# The settings for the demo run, written by
965
+ # `arrayprobe make-demo-flight --with-config`.
966
+ # The same choices as the repository's examples/start_here/run.toml. Paths in it are
967
+ # relative to this folder.
968
+
969
+ [fidelity]
970
+ # The processing rules: the UIOPS v3.5 rules as the UIOPS developers released them.
971
+ profile = "stock-v3.5"
972
+
973
+ [run]
974
+ # Which processing program. "3.5" is the default for new data.
975
+ engine = "3.5"
976
+ # Which probe and aircraft settings. DEMO_2DS_H is the synthetic demo file's own settings.
977
+ preset = "DEMO_2DS_H"
978
+ # Where the results go: this folder.
979
+ out = "."
980
+ # Which steps to run: 2 = read the raw file, 3 = measure each particle,
981
+ # 4 = count particles by size each second, c = write one combined file.
982
+ stages = "234c"
983
+ # The aircraft's speed through the air, second by second, written beside the raw file.
984
+ tas_file = "{aircraft}"
985
+
986
+ [combine]
987
+ # Write the combined file (step "c"). Stock v3.5 has no combine step, so this
988
+ # borrows one and labels the output as borrowed.
989
+ borrowed = true
990
+
991
+ [enhancements]
992
+ # Empty on purpose: no optional corrections. The run is the plain UIOPS v3.5 processing.
993
+ """
994
+
995
+
996
+ def write_demo_run_toml(raw_path, aircraft) -> Path:
997
+ """Write ``run.toml`` beside a demo flight; returns its path."""
998
+ raw_path = Path(raw_path)
999
+ target = raw_path.with_name("run.toml")
1000
+ target.write_text(DEMO_RUN_TOML.format(aircraft=Path(aircraft).name), encoding="utf-8")
1001
+ return target
1002
+
1003
+
1004
+ def main(argv=None) -> int:
1005
+ """CLI entry point, shared by ``arrayprobe make-demo-flight`` and the
1006
+ ``scripts/make_demo_flight.py`` shim, so both surfaces parse identically."""
1007
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
1008
+ parser.add_argument("path", help="output path, e.g. demo.2DS")
1009
+ parser.add_argument("--seconds", type=int, default=5,
1010
+ help="number of one-second records to write (default: 5)")
1011
+ parser.add_argument("--tas-mps", type=float, default=130.0,
1012
+ help="synthetic true airspeed in m/s (default: 130.0)")
1013
+ parser.add_argument("--dense", action="store_true",
1014
+ help="write the DENSE flight instead: "
1015
+ "disks/rings/bars sized to move a reject or "
1016
+ "shattering threshold's used-bin count, not the "
1017
+ "plain one-particle-per-second flight above")
1018
+ parser.add_argument("--distinct-counters", action="store_true",
1019
+ help="give each image packet its own particle counter "
1020
+ "(default: the constant 7), so SODA-2's spec_index "
1021
+ "keeps every particle; changes the written bytes")
1022
+ parser.add_argument("--with-config", action="store_true",
1023
+ help="also create the output folder if needed and write a "
1024
+ "ready-to-run run.toml beside the flight, so "
1025
+ "`arrayprobe run <folder>/run.toml <flight> --yes` works "
1026
+ "without the repository's examples/ folder")
1027
+ args = parser.parse_args(argv)
1028
+ if args.seconds < 2:
1029
+ # Measured 2026-09-26: a 1-second flight (plain or --dense) decodes one image record but
1030
+ # writes no <stem>.tas.csv, so S4 skips and the run fails; a 0-second one is empty.
1031
+ # Both were written, exit 0, with the next command printed as if they would run.
1032
+ parser.error(f"--seconds must be at least 2, got {args.seconds}: a shorter flight "
1033
+ f"decodes to no airspeed record (<stem>.tas.csv), and the run then fails "
1034
+ f"at the size-distribution stage")
1035
+ if not args.tas_mps > 0:
1036
+ parser.error(f"--tas-mps must be a positive speed in m/s, got {args.tas_mps}")
1037
+
1038
+ if args.with_config:
1039
+ Path(args.path).parent.mkdir(parents=True, exist_ok=True)
1040
+ if args.dense:
1041
+ written = build_dense_demo_flight(args.path, n_seconds=args.seconds,
1042
+ tas_mps=args.tas_mps,
1043
+ distinct_counters=args.distinct_counters)
1044
+ print(f"wrote {written} (DENSE: {args.seconds} synthetic seconds, "
1045
+ f"TAS={args.tas_mps} m/s) -- see help(arrayprobe.tools.make_demo_flight."
1046
+ "build_dense_demo_flight) for what moves which threshold")
1047
+ else:
1048
+ written = build_demo_flight(args.path, n_seconds=args.seconds,
1049
+ tas_mps=args.tas_mps,
1050
+ distinct_counters=args.distinct_counters)
1051
+ print(f"wrote {written} ({args.seconds} synthetic seconds, "
1052
+ f"TAS={args.tas_mps} m/s)")
1053
+
1054
+ # Both flights, not just the plain one: the 99.72 %-NaN product a stranger opens
1055
+ # after the published quickstart is the DENSE one, and until 2026-09-17 the dense
1056
+ # branch returned here -- printing neither this summary, nor the base-name note,
1057
+ # nor the next command. See summary_lines.
1058
+ for line in summary_lines(written, args.seconds, dense=args.dense):
1059
+ print(line)
1060
+ if not written.stem.startswith("base"):
1061
+ print(f"note: {written.name!r} does not start with 'base' -- the combine "
1062
+ "step (--stages 234c) needs a base<YYMMDDhhmmss> name to read the "
1063
+ "flight date; stages 2-4 alone work with any name.")
1064
+ # The batch driver is still `scripts/run_flight.py`, which `pip install` does
1065
+ # not ship (see arrayprobe.tools.__init__ for why it has not moved yet), so
1066
+ # this hint names the repository path and says so rather than printing a
1067
+ # command an installed-package user cannot run.
1068
+ # --yes: this demo names no threshold policy, so the run would otherwise stop and
1069
+ # ask. The command printed here must be one somebody can paste and have work.
1070
+ aircraft = write_demo_aircraft(written, n_seconds=args.seconds)
1071
+ print(f"wrote {aircraft} (aircraft TAS for engine 3.5: a scaled excerpt of public ARM "
1072
+ "AAF data, see DEMO_AIRCRAFT_TAS_MPS)")
1073
+ # --engine is required on every preset (2026-09-23), so both commands name it.
1074
+ # The interpreter as this platform spells it: a Windows path printed on Linux could not be
1075
+ # pasted (cloud pass 8 cold-user run).
1076
+ py = ".venv/Scripts/python.exe" if sys.platform == "win32" else ".venv/bin/python"
1077
+ if args.with_config:
1078
+ config = write_demo_run_toml(written, aircraft)
1079
+ print(f"wrote {config} (the run settings, paths relative to its folder)")
1080
+ print("next -- engine 3.5, the default:")
1081
+ print(f" arrayprobe run {config} {written} --yes")
1082
+ return 0
1083
+ for line in next_lines(written, aircraft, py):
1084
+ print(line)
1085
+ return 0
1086
+
1087
+
1088
+ if __name__ == "__main__":
1089
+ raise SystemExit(main())