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,325 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Export decoded 2D-S images in NCAR's RAF OAP file format (``.2d``).
3
+
4
+ Opt-in tooling inside the v3.5 engine: it re-packs images the S2 stage already
5
+ decoded and computes no number used by any product. The format follows
6
+ translate2ds's writer (NCAR/aircraft_oap ``translate2ds/UCAR_Writer.h``); the
7
+ reader it is checked against, :mod:`arrayprobe_uiops.oap_read`, was written from
8
+ process2d's rule instead, so the round trip draws its two sides from different
9
+ places.
10
+
11
+ What is written
12
+ ---------------
13
+ * An XML preamble (``<OAP version="1">`` ... ``</OAP>``) naming the project,
14
+ platform, flight and one ``<probe>`` element per channel written.
15
+ * 4116-byte records: a 2-byte probe id (``SH``/``SV``), nine big-endian uint16
16
+ (hour, minute, second, year, month, day, TAS, msec, overload = 0), then 4096
17
+ data bytes = 256 slices of 16 bytes. The slice stream runs across record
18
+ boundaries; the final record is zero-padded.
19
+ * Image slices: one bit per diode, **1 = clear** (the OAP convention). The S2
20
+ canvas stores 1 = shaded, so every pixel is inverted on the way out. Diode
21
+ row ``r`` of the S2 canvas (1-based, word 1 bit 15 = row 1) is written as
22
+ process2d's diode ``r - 1`` (byte 15 bit 7 = diode 0).
23
+ * After each particle's image slices, one sync slice: the timing value in bytes
24
+ 0-7 little-endian, then ``0xAAAAAA0000000000`` little-endian.
25
+
26
+ Timing
27
+ ------
28
+ The S2 header slice holds the particle's timing counter as a **32-bit** value
29
+ (words 7-8 of the header slice; see :mod:`arrayprobe_uiops.oap_read`'s storage
30
+ notes), so that is what is written: bytes 0-3 of the sync slice, bytes 4-7
31
+ zero. The counter survives the round trip exactly. translate2ds writes the
32
+ 2D-S's own 48-bit word; the upper 16 bits are not stored at S2 and are not
33
+ reconstructed.
34
+
35
+ translate2ds writes the sync that closes particle *k* with particle *k + 1*'s
36
+ time and closes the stream with a final sync repeating the last time.
37
+ ``timing_convention="translate2ds"`` (the default) copies that; ``"own"``
38
+ writes each particle's own time in the sync that closes it, which is how
39
+ process2d attributes a sync's time. Which convention xpms2d and process2d
40
+ expect of a 2D-S file is not settled here.
41
+
42
+ Open question: diode order
43
+ --------------------------
44
+ process2d unpacks diode 0 from byte 15 bit 7 (``process2d.cpp:997-1002``);
45
+ translate2ds packs diode 0 into byte 0 bit 0 (``UCAR_Writer.h`` ``ToBits``,
46
+ LSB-first). The two pack diode 0 at opposite ends of the slice, so one of
47
+ them reads the other's images mirrored across the array. This module follows
48
+ process2d's order, so its own reader sees the images unmirrored; whether a
49
+ translate2ds-written file and this one agree byte for byte stays unresolved
50
+ until Process2D builds and the two can be compared on the same raw file.
51
+
52
+ Lossy, and stated
53
+ -----------------
54
+ Record-header time is per record (the stamp of the particle whose slices open
55
+ the record), not per particle; TAS is a uint16 word; overload is 0;
56
+ housekeeping and mask packets are not carried; particles the S2 canvas cut at
57
+ column 1700 never reach this module.
58
+ """
59
+
60
+ from __future__ import annotations
61
+
62
+ import dataclasses
63
+ import struct
64
+ from collections.abc import Iterable, Sequence
65
+ from pathlib import Path
66
+
67
+ import numpy as np
68
+
69
+ __all__ = [
70
+ "BOUNDARY_WORD",
71
+ "OapStamp",
72
+ "OapWriteReport",
73
+ "ExportParticle",
74
+ "encode_slice",
75
+ "particles_from_canvas",
76
+ "main",
77
+ "particles_from_decode",
78
+ "write_oap_2ds",
79
+ ]
80
+
81
+ OAP_RECORD_BYTES = 4116
82
+ DATA_BYTES = 4096
83
+ SLICE_BYTES = 16
84
+ N_DIODES = 128
85
+ BOUNDARY_WORD = 0b1010101010101010 # the S2 canvas's alternating boundary slice, per word
86
+ SYNC_TAIL_WORD = 0xAAAAAA0000000000
87
+ TIMING_MASK_32 = 0xFFFFFFFF
88
+ _HEADER = struct.Struct(">2s9H")
89
+ _SUFFIX = {b"SH": "_2H", b"SV": "_2V"}
90
+
91
+
92
+ @dataclasses.dataclass(frozen=True)
93
+ class OapStamp:
94
+ """The per-record header fields (as stored: unsigned 16-bit words)."""
95
+
96
+ year: int
97
+ month: int
98
+ day: int
99
+ hour: int
100
+ minute: int
101
+ second: int
102
+ msec: int = 0
103
+ tas: int = 0
104
+
105
+
106
+ @dataclasses.dataclass(frozen=True)
107
+ class ExportParticle:
108
+ """One particle: ``shaded`` is ``(n_slices, 128)`` with 1 = shaded, S2's
109
+ convention; ``timing`` is the 32-bit counter; ``stamp`` the record time."""
110
+
111
+ shaded: np.ndarray
112
+ timing: int
113
+ stamp: OapStamp
114
+
115
+
116
+ @dataclasses.dataclass(frozen=True)
117
+ class OapWriteReport:
118
+ particles: int
119
+ records: int
120
+ slices: int
121
+ timing_convention: str
122
+
123
+
124
+ def encode_slice(shaded_row: np.ndarray) -> bytes:
125
+ """One 128-diode slice, 1 = shaded in, OAP bytes (1 = clear) out, diode 0 at
126
+ byte 15 bit 7 (process2d's order)."""
127
+ row = np.asarray(shaded_row, dtype=np.uint8)
128
+ if row.shape != (N_DIODES,):
129
+ raise ValueError(f"a 2D-S slice has {N_DIODES} diodes, got shape {row.shape}")
130
+ clear = (1 - row).astype(np.uint8)
131
+ return np.packbits(clear, bitorder="big").tobytes()[::-1]
132
+
133
+
134
+ def _sync_slice(timing: int) -> bytes:
135
+ return (int(timing) & TIMING_MASK_32).to_bytes(8, "little") + SYNC_TAIL_WORD.to_bytes(
136
+ 8, "little")
137
+
138
+
139
+ def _unpack_words(col: np.ndarray) -> np.ndarray:
140
+ """Eight 16-bit words, MSB-first, to 128 diode bits (row 1 = word 1 bit 15)."""
141
+ words = np.asarray(col, dtype=np.int64).astype(">u2")
142
+ return np.unpackbits(words.view(np.uint8), bitorder="big")
143
+
144
+
145
+ def particles_from_canvas(canvas: np.ndarray) -> list[tuple[np.ndarray, int]]:
146
+ """Split one S2 record canvas into ``(shaded, timing)`` per particle.
147
+
148
+ ``canvas`` is ``(8, n_columns)`` integer words, one column per slice, as the
149
+ S2 ``data`` variable holds it for one ``time`` step. A particle is the image
150
+ columns up to a boundary column (every word ``BOUNDARY_WORD``), closed by the
151
+ header column after it, whose words 7-8 are the 32-bit timing counter.
152
+ Columns after the last header column (the zero fill of the canvas) are
153
+ ignored. An image column that is itself all-alternating would be read as a
154
+ boundary; the header column that must follow is not checked further.
155
+ """
156
+ arr = np.asarray(canvas)
157
+ if arr.ndim != 2 or arr.shape[0] != 8:
158
+ raise ValueError(f"canvas must be (8, n_columns), got {arr.shape}")
159
+ out: list[tuple[np.ndarray, int]] = []
160
+ start = 0
161
+ col = 0
162
+ n = arr.shape[1]
163
+ while col + 1 < n:
164
+ if (arr[:, col] == BOUNDARY_WORD).all():
165
+ header = arr[:, col + 1]
166
+ timing = (int(header[6]) << 16) | int(header[7])
167
+ image = (np.vstack([_unpack_words(arr[:, c]) for c in range(start, col)])
168
+ if col > start else np.zeros((0, N_DIODES), dtype=np.uint8))
169
+ out.append((image, timing))
170
+ col += 2
171
+ start = col
172
+ else:
173
+ col += 1
174
+ return out
175
+
176
+
177
+ def _xml(probe_id: bytes, project: str, platform: str, flight_number: str,
178
+ first: OapStamp | None, probe_type: str, serial: str) -> bytes:
179
+ date = (f"{first.month:02d}/{first.day:02d}/{first.year:04d}" if first else "")
180
+ tag = probe_id.decode("ascii")
181
+ lines = [
182
+ '<?xml version="1.0" encoding="ISO-8859-1"?>',
183
+ '<OAP version="1">',
184
+ " <Source>arrayprobe_uiops.export_oap</Source>",
185
+ " <FormatURL>http://www.eol.ucar.edu/raf/software/OAPfiles.html</FormatURL>",
186
+ f" <Project>{project}</Project>",
187
+ f" <Platform>{platform}</Platform>",
188
+ f" <FlightNumber>{flight_number}</FlightNumber>",
189
+ f" <FlightDate>{date}</FlightDate>",
190
+ f' <probe id="{tag}" type="{probe_type}" resolution="10" nDiodes="{N_DIODES}"'
191
+ f' serialnumber="{serial}" suffix="{_SUFFIX[probe_id]}"/>',
192
+ "</OAP>",
193
+ ]
194
+ return ("\n".join(lines) + "\n").encode("latin-1")
195
+
196
+
197
+ def write_oap_2ds(particles: Iterable[ExportParticle], out: str | Path, *,
198
+ probe_id: bytes = b"SH", project: str = "", platform: str = "",
199
+ flight_number: str = "", probe_type: str = "2DS", serial: str = "",
200
+ timing_convention: str = "translate2ds") -> OapWriteReport:
201
+ """Write ``particles`` (in time order) to ``out`` as one 2D-S channel."""
202
+ if probe_id not in _SUFFIX:
203
+ raise ValueError(f"not a 2D-S probe id: {probe_id!r}")
204
+ if timing_convention not in ("translate2ds", "own"):
205
+ raise ValueError(f"unknown timing_convention {timing_convention!r}")
206
+ parts: Sequence[ExportParticle] = list(particles)
207
+ stream: list[bytes] = []
208
+ owner: list[OapStamp] = [] # the stamp of the particle each slice belongs to
209
+ for k, p in enumerate(parts):
210
+ shaded = np.asarray(p.shaded)
211
+ if shaded.ndim != 2 or shaded.shape[1] != N_DIODES:
212
+ raise ValueError(f"particle {k}: shaded must be (n, {N_DIODES}), got {shaded.shape}")
213
+ if timing_convention == "own":
214
+ sync_t = p.timing
215
+ else:
216
+ sync_t = parts[k + 1].timing if k + 1 < len(parts) else p.timing
217
+ for row in shaded:
218
+ stream.append(encode_slice(row))
219
+ owner.append(p.stamp)
220
+ stream.append(_sync_slice(sync_t))
221
+ owner.append(p.stamp)
222
+ per_record = DATA_BYTES // SLICE_BYTES
223
+ records: list[bytes] = []
224
+ for i in range(0, len(stream), per_record):
225
+ data = b"".join(stream[i : i + per_record]).ljust(DATA_BYTES, b"\x00")
226
+ s = owner[i]
227
+ records.append(_HEADER.pack(probe_id, s.hour, s.minute, s.second, s.year, s.month,
228
+ s.day, s.tas, s.msec, 0) + data)
229
+ first = parts[0].stamp if parts else None
230
+ xml = _xml(probe_id, project, platform, flight_number, first, probe_type, serial)
231
+ Path(out).write_bytes(xml + b"".join(records))
232
+ return OapWriteReport(particles=len(parts), records=len(records), slices=len(stream),
233
+ timing_convention=timing_convention)
234
+
235
+
236
+ #: Probe names a v3.5 SPEC decode can come from; only the 2D-S is this format's subject here.
237
+ _OTHER_SPEC_PROBES = ("HVPS", "3VCPI", "CPI", "CIP", "PIP", "2DC", "2DP")
238
+ _CHANNEL_IDS = {"Horizontal": b"SH", "Vertical": b"SV"}
239
+
240
+
241
+ def particles_from_decode(path: str | Path) -> tuple[bytes, list[ExportParticle]]:
242
+ """Read a v3.5 S2 decode (``<flight>.H.nc`` / ``.V.nc``) into export particles.
243
+
244
+ Returns the channel's probe id (``SH`` / ``SV``, from the file's
245
+ ``Probe Channel_Orientation``) and every particle in file order, each
246
+ stamped with its record's time, millisecond and TAS (rounded to a uint16
247
+ word; a missing or negative TAS is written as 0). Raises ``ValueError`` on a
248
+ file that is not a v3.5 SPEC decode, or that names another probe.
249
+ """
250
+ import netCDF4
251
+
252
+ p = Path(path)
253
+ with netCDF4.Dataset(p) as ds:
254
+ attrs = {k: ds.getncattr(k) for k in ds.ncattrs()}
255
+ orient = attrs.get("Probe Channel_Orientation")
256
+ if orient not in _CHANNEL_IDS or "data" not in ds.variables:
257
+ raise ValueError(f"{p.name}: not a v3.5 2D-S decode (no 'data' variable or no "
258
+ "'Probe Channel_Orientation' of Horizontal/Vertical)")
259
+ named = " ".join([p.name, *(str(v) for v in attrs.values())]).upper()
260
+ other = [n for n in _OTHER_SPEC_PROBES if n in named]
261
+ if other:
262
+ raise ValueError(f"{p.name}: names probe {other[0]}; export-oap writes 2D-S "
263
+ "decodes only")
264
+ ds.set_auto_mask(False)
265
+ data = np.asarray(ds.variables["data"][:])
266
+ if data.ndim != 3 or data.shape[2] != 8:
267
+ raise ValueError(f"{p.name}: 'data' is {data.shape}, expected (time, columns, 8)")
268
+ fields = {n: np.asarray(ds.variables[n][:]).astype(np.int64)
269
+ for n in ("year", "month", "day", "hour", "minute", "second", "millisec")}
270
+ tas = (np.asarray(ds.variables["tas"][:], dtype=float) if "tas" in ds.variables
271
+ else np.zeros(data.shape[0]))
272
+ out: list[ExportParticle] = []
273
+ for t in range(data.shape[0]):
274
+ v = tas[t]
275
+ tas_word = int(min(round(v), 0xFFFF)) if np.isfinite(v) and v > 0 else 0
276
+ stamp = OapStamp(year=int(fields["year"][t]), month=int(fields["month"][t]),
277
+ day=int(fields["day"][t]), hour=int(fields["hour"][t]),
278
+ minute=int(fields["minute"][t]), second=int(fields["second"][t]),
279
+ msec=int(fields["millisec"][t]), tas=tas_word)
280
+ for shaded, timing in particles_from_canvas(data[t].T):
281
+ out.append(ExportParticle(shaded, timing, stamp))
282
+ return _CHANNEL_IDS[orient], out
283
+
284
+
285
+ def main(argv: Sequence[str] | None = None) -> int:
286
+ """``python -m arrayprobe_uiops.export_oap DECODE OUT --probe 2DS``: one channel, one file.
287
+
288
+ Opt-in: writes ``OUT`` and nothing else, and changes no product.
289
+ """
290
+ import argparse
291
+
292
+ ap = argparse.ArgumentParser(
293
+ prog="python -m arrayprobe_uiops.export_oap",
294
+ description="Write a v3.5 2D-S stage-2 decode (<flight>.H.nc or .V.nc) as an NCAR "
295
+ "RAF OAP (.2d) file. Writes OUT only; no product changes.")
296
+ ap.add_argument("decode", help="the v3.5 decoder's output file for one channel")
297
+ ap.add_argument("out", help="the .2d file to write (refused if it exists)")
298
+ ap.add_argument("--probe", required=True,
299
+ help="the probe the decode came from; only 2DS is accepted")
300
+ ap.add_argument("--timing-convention", choices=("translate2ds", "own"),
301
+ default="translate2ds")
302
+ ap.add_argument("--project", default="")
303
+ ap.add_argument("--platform", default="")
304
+ ap.add_argument("--flight-number", default="")
305
+ ap.add_argument("--serial", default="")
306
+ args = ap.parse_args(argv)
307
+ if args.probe.upper() not in ("2DS", "2D-S"):
308
+ ap.error(f"--probe {args.probe}: export-oap writes 2D-S decodes only")
309
+ out = Path(args.out)
310
+ if out.exists():
311
+ ap.error(f"{out} exists; refusing to overwrite")
312
+ try:
313
+ probe_id, parts = particles_from_decode(args.decode)
314
+ except ValueError as exc:
315
+ ap.error(str(exc))
316
+ report = write_oap_2ds(parts, out, probe_id=probe_id, project=args.project,
317
+ platform=args.platform, flight_number=args.flight_number,
318
+ serial=args.serial, timing_convention=args.timing_convention)
319
+ print(f"{out}: {report.particles} particles, {report.records} records "
320
+ f"({probe_id.decode()}, timing {report.timing_convention})")
321
+ return 0
322
+
323
+
324
+ if __name__ == "__main__":
325
+ raise SystemExit(main())
@@ -0,0 +1,366 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Shared leaf: the minimum-enclosing-circle helpers both engines use.
3
+
4
+ Moved verbatim from ``arrayprobe.geometry.min_circle``; that module re-imports them,
5
+ so its names still resolve. Pure functions: no module state, no numba.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import random
12
+ from fractions import Fraction
13
+
14
+ import numpy as np
15
+
16
+ from .particle import shadow_mask
17
+
18
+ __all__: list[str] = []
19
+
20
+
21
+ def _shadow_points(c) -> np.ndarray:
22
+ """The shadowed pixels of a particle image, as ``(n, 2)`` integer coordinates.
23
+
24
+ ``CGAL_minR.cpp:56-70`` walks the MATLAB array in column-major order and
25
+ pushes ``p = (j, i)`` -- row index first, column index second, both 0-based --
26
+ for every entry equal to ``48``, the character ``'0'``, which is UIOOPS's
27
+ encoding for *shadowed*. Order does not affect the circle, so the walk is
28
+ vectorized; the coordinate convention is kept because the centre is reported
29
+ in it.
30
+
31
+ Accepts either the canonical boolean ``shadow`` array (``True`` = shadowed) or
32
+ the MATLAB char matrix itself, so a call site can pass whichever it holds.
33
+ The coercion itself lives in :func:`arrayprobe.particle.shadow_mask` -- it
34
+ was private here at first, and moved out once ``habit`` and ``reject``
35
+ needed the same rule. Three modules agreeing on which value means
36
+ "shadowed" is worth more than three modules each being sure.
37
+ """
38
+ rows, cols = np.nonzero(shadow_mask(c))
39
+ return np.column_stack((rows, cols))
40
+
41
+
42
+ def _hull_candidates(points: np.ndarray) -> list[tuple[int, int]]:
43
+ """Reduce to a superset of the convex-hull vertices, cheaply.
44
+
45
+ A convex-hull vertex is extreme in some direction, so it cannot lie strictly
46
+ between two other points of the set on the same vertical line: it must be the
47
+ topmost or bottommost point of its own column. Keeping two points per column
48
+ therefore preserves the hull exactly, and it collapses a dense particle from
49
+ O(pixels) to O(columns) before any exact arithmetic runs.
50
+
51
+ A full convex hull afterwards would shrink the set further, but not usefully:
52
+ the incremental algorithm is expected-linear in the input size, and the
53
+ monotone chain would cost the same sort.
54
+ """
55
+ cols = points[:, 1]
56
+ order = np.argsort(cols, kind="stable")
57
+ sorted_pts = points[order]
58
+ sorted_cols = cols[order]
59
+ starts = np.flatnonzero(np.r_[True, sorted_cols[1:] != sorted_cols[:-1]])
60
+ ends = np.r_[starts[1:], len(sorted_pts)] - 1
61
+ rows = sorted_pts[:, 0]
62
+ keep = []
63
+ for s, e in zip(starts, ends, strict=True):
64
+ block = rows[s : e + 1]
65
+ col = int(sorted_cols[s])
66
+ keep.append((int(block.min()), col))
67
+ keep.append((int(block.max()), col))
68
+ return keep
69
+
70
+
71
+ # --------------------------------------------------------------------------
72
+ # Exact circle primitives. A circle is (cx, cy, r2) over Fraction.
73
+ # --------------------------------------------------------------------------
74
+
75
+
76
+ def _contains(circle, p) -> bool:
77
+ cx, cy, r2 = circle
78
+ dx = Fraction(p[0]) - cx
79
+ dy = Fraction(p[1]) - cy
80
+ return dx * dx + dy * dy <= r2
81
+
82
+
83
+ def _from_two(a, b):
84
+ cx = Fraction(a[0] + b[0], 2)
85
+ cy = Fraction(a[1] + b[1], 2)
86
+ dx = Fraction(a[0] - b[0])
87
+ dy = Fraction(a[1] - b[1])
88
+ return cx, cy, (dx * dx + dy * dy) / 4
89
+
90
+
91
+ def _from_three(a, b, c):
92
+ """Circumcircle of three points, or the two-point circle when they are collinear.
93
+
94
+ Collinear triples do reach here: three shadowed pixels in a row is an
95
+ unremarkable particle. The minimum circle enclosing collinear points is the
96
+ one spanning the two extremes, which is what the fallback returns.
97
+ """
98
+ ax, ay = Fraction(a[0]), Fraction(a[1])
99
+ bx, by = Fraction(b[0]), Fraction(b[1])
100
+ cx_, cy_ = Fraction(c[0]), Fraction(c[1])
101
+ d = 2 * (ax * (by - cy_) + bx * (cy_ - ay) + cx_ * (ay - by))
102
+ if d == 0:
103
+ best = _from_two(a, b)
104
+ for pair in ((a, c), (b, c)):
105
+ cand = _from_two(*pair)
106
+ if cand[2] > best[2]:
107
+ best = cand
108
+ return best
109
+ a2 = ax * ax + ay * ay
110
+ b2 = bx * bx + by * by
111
+ c2 = cx_ * cx_ + cy_ * cy_
112
+ ux = (a2 * (by - cy_) + b2 * (cy_ - ay) + c2 * (ay - by)) / d
113
+ uy = (a2 * (cx_ - bx) + b2 * (ax - cx_) + c2 * (bx - ax)) / d
114
+ return ux, uy, (ax - ux) ** 2 + (ay - uy) ** 2
115
+
116
+
117
+ _TRUNCATED_PI = 3.1415926 # CGAL_EllipseSize.cpp:35's own #define PI
118
+
119
+
120
+ def _shadow_points_xy(c) -> np.ndarray:
121
+ """Shadowed pixels as ``(n, 2)`` integer ``(col, row)`` coordinates --
122
+ identical convention to :func:`arrayprobe.geometry.min_rectangle._shadow_points_xy`."""
123
+ rows, cols = np.nonzero(shadow_mask(c))
124
+ return np.column_stack((cols, rows))
125
+
126
+
127
+ def _khachiyan_ellipsoid(points: np.ndarray, tol: float = 1e-4, max_iter: int = 3000):
128
+ """The 2D Loewner-John ellipse via Khachiyan's barycentric algorithm.
129
+
130
+ ``points`` is ``(n, 2)`` float. Returns ``(center, shape)`` where
131
+ ``shape`` is the symmetric positive-definite 2x2 matrix defining the
132
+ ellipse ``{x : (x-center)^T shape (x-center) <= 1}``, or ``None`` if the
133
+ points do not affinely span the plane (all collinear or fewer than 3
134
+ distinct points) -- the caller handles those degenerate cases directly,
135
+ the same way :mod:`.min_rectangle` special-cases a 1- or 2-point hull.
136
+
137
+ Khachiyan's (1996) barycentric multiplicative-update algorithm: lift
138
+ each point to ``(x, y, 1)``, maintain a probability weighting over the
139
+ points, and repeatedly shift weight toward whichever point is currently
140
+ farthest (in the Mahalanobis sense) from the running weighted
141
+ ellipsoid, until every point is within tolerance of the boundary.
142
+ Provably convergent to the unique minimum-volume enclosing ellipsoid
143
+ regardless of starting weights, independent of anything CGAL's own
144
+ algorithm does -- Todd & Yildirim (2007) is the reference for this
145
+ convergence analysis, though the step rule used here is the classic
146
+ Khachiyan one, not their accelerated variant.
147
+
148
+ **A real, measured numerical property, not a theoretical nicety**: near
149
+ the optimum this step rule has a well-documented slow tail (each step
150
+ shrinks the remaining gap only linearly, not geometrically), so
151
+ ``tol``/``max_iter``'s defaults target practical diode-scale accuracy
152
+ (a few parts in 10\\ :sup:`4` on the semi-axis lengths -- far finer than
153
+ any downstream measurement resolves) rather than machine precision.
154
+ *Every* iterate, converged or not, defines a valid ellipsoid containing
155
+ all the input points -- the iteration only ever shrinks a starting
156
+ superset -- so running out of ``max_iter`` still returns a correct,
157
+ merely very slightly non-minimal, answer; it is not treated as failure.
158
+ """
159
+ n = points.shape[0]
160
+ if n < 3:
161
+ return None
162
+ q = np.hstack([points, np.ones((n, 1))]) # (n, 3), the lifted points
163
+ u = np.full(n, 1.0 / n)
164
+ d = 2 # dimension
165
+
166
+ for _ in range(max_iter):
167
+ qtq = (q * u[:, None]).T @ q # (3, 3)
168
+ try:
169
+ qtq_inv = np.linalg.inv(qtq)
170
+ except np.linalg.LinAlgError:
171
+ return None # degenerate (collinear) point set
172
+ m = np.einsum("ij,jk,ik->i", q, qtq_inv, q) # Mahalanobis-type scores
173
+ j = int(np.argmax(m))
174
+ max_m = m[j]
175
+ if max_m <= d + 1 + tol:
176
+ break
177
+ step = (max_m - d - 1) / ((d + 1) * (max_m - 1))
178
+ u = (1 - step) * u
179
+ u[j] += step
180
+ # Reached tolerance or exhausted max_iter -- either way `u` defines a
181
+ # valid (if not perfectly minimal, in the latter case) enclosing
182
+ # ellipsoid; see the docstring's note on why this is safe to use as-is.
183
+
184
+ center = u @ points # (2,)
185
+ p_centered = points - center
186
+ cov = (p_centered * u[:, None]).T @ p_centered # (2, 2)
187
+ try:
188
+ shape = np.linalg.inv(cov) / d
189
+ except np.linalg.LinAlgError:
190
+ return None
191
+ return center, shape
192
+
193
+
194
+ def min_area_ellipse(points):
195
+ """The minimum-area enclosing ellipse of a 2D point set.
196
+
197
+ Returns ``(major, minor, angle)``: full axis lengths (diameters, not
198
+ semi-axes -- matching ``CGAL_EllipseSize.cpp``'s own ``2*sqrt(...)``
199
+ convention) with ``major >= minor``, and ``angle`` the major axis's
200
+ direction in radians, wrapped to ``(-pi/2, pi/2]`` the way
201
+ ``CGAL_EllipseSize.cpp:120-124`` does. ``None`` for fewer than 3 points.
202
+
203
+ **Degenerate point sets -- derived, not measured** (no CGAL to run):
204
+
205
+ * **All points collinear**: the Khachiyan iteration cannot converge (the
206
+ lifted covariance is singular), so this returns the same "degenerate
207
+ ellipse is the spanning line segment" answer
208
+ :func:`arrayprobe.geometry.min_rectangle.min_area_rectangle` already
209
+ documents for its own 2-point-hull case -- ``minor = 0``, ``major``
210
+ spans the two extreme points, ``angle`` along the line.
211
+ """
212
+ pts = np.asarray([(float(p[0]), float(p[1])) for p in points])
213
+ if len(pts) < 3:
214
+ return None
215
+
216
+ unique = np.unique(pts, axis=0)
217
+ if len(unique) < 3 or _is_collinear(unique):
218
+ return _degenerate_segment_ellipse(unique)
219
+
220
+ result = _khachiyan_ellipsoid(pts)
221
+ if result is None:
222
+ return _degenerate_segment_ellipse(unique)
223
+
224
+ center, shape = result
225
+ eigvals, eigvecs = np.linalg.eigh(shape) # ascending eigenvalues
226
+ # shape = V diag(eigvals) V^T; semi-axis along eigvecs[:,k] has length 1/sqrt(eigvals[k]).
227
+ # Smaller eigenvalue -> longer (major) axis.
228
+ semi_major = 1.0 / math.sqrt(eigvals[0])
229
+ semi_minor = 1.0 / math.sqrt(eigvals[1])
230
+ major_dir = eigvecs[:, 0]
231
+ angle = _wrap_angle(math.atan2(major_dir[1], major_dir[0]))
232
+ return 2.0 * semi_major, 2.0 * semi_minor, angle
233
+
234
+
235
+ def _is_collinear(pts: np.ndarray) -> bool:
236
+ base = pts[0]
237
+ rest = pts[1:] - base
238
+ if len(rest) < 2:
239
+ return True
240
+ cross = rest[0, 0] * rest[:, 1] - rest[0, 1] * rest[:, 0]
241
+ return bool(np.allclose(cross, 0.0))
242
+
243
+
244
+ def _degenerate_segment_ellipse(pts: np.ndarray):
245
+ if len(pts) == 1:
246
+ return 0.0, 0.0, 0.0
247
+ diffs = pts[:, None, :] - pts[None, :, :]
248
+ dist2 = np.einsum("ijk,ijk->ij", diffs, diffs)
249
+ i, j = np.unravel_index(np.argmax(dist2), dist2.shape)
250
+ dx, dy = pts[j] - pts[i]
251
+ span = math.hypot(dx, dy)
252
+ angle = _wrap_angle(math.atan2(dy, dx)) if span > 0 else 0.0
253
+ return span, 0.0, angle
254
+
255
+
256
+ def _wrap_angle(angle: float) -> float:
257
+ """``CGAL_EllipseSize.cpp:120-124`` -- wrap into ``(-pi/2, pi/2]`` using
258
+ the source's own truncated-pi literal."""
259
+ if angle > _TRUNCATED_PI / 2:
260
+ angle -= 3.141592653
261
+ if angle < -_TRUNCATED_PI / 2:
262
+ angle += 3.141592653
263
+ return angle
264
+
265
+
266
+ def cgal_ellipse_size(c) -> tuple[float, float, float]:
267
+ """``CGAL_EllipseSize(c)`` -- ``(major, minor, angle)``, diode units / radians.
268
+
269
+ Same empty-image convention as
270
+ :func:`arrayprobe.geometry.min_rectangle.cgal_rect_size` (``CGAL_EllipseSize.cpp:82-89``):
271
+ no shadowed pixel returns ``(0.0, 0.0, 0.0)`` directly, not NaN like
272
+ :func:`arrayprobe_uiops.geometry_core.cgal_min_r`.
273
+ """
274
+ a = np.asarray(c)
275
+ points = _shadow_points_xy(a)
276
+ if len(points) == 0:
277
+ return 0.0, 0.0, 0.0
278
+ if len(points) < 3:
279
+ span, minor, angle = _degenerate_segment_ellipse(
280
+ np.unique(points.astype(float), axis=0)
281
+ )
282
+ return 1.0 + span, 1.0 + minor, angle
283
+
284
+ result = min_area_ellipse(points)
285
+ major, minor, angle = result
286
+ return 1.0 + major, 1.0 + minor, angle
287
+
288
+
289
+ #: Fixed shuffle seed. Welzl's incremental algorithm is randomized for expected
290
+ #: linear time, but the circle it returns is unique, so the seed affects speed
291
+ #: and nothing else. It is fixed anyway: an algorithm whose *runtime* varies run
292
+ #: to run makes a slow case impossible to reproduce from a bug report.
293
+ _SEED = 0x6D696E52 # 'minR'
294
+
295
+
296
+ def min_enclosing_circle_exact(points):
297
+ """The unique minimum enclosing circle, as exact ``(cx, cy, r2)`` Fractions.
298
+
299
+ Source: stands in for the Miniball call in ``CGAL_minR.cpp:81-89`` (UIOOPS v3.1.4), which
300
+ computes the same unique circle.
301
+
302
+ Welzl's incremental algorithm (the move-to-front formulation Gaertner builds
303
+ on). Every comparison is exact, so there is no tolerance to tune and no
304
+ degenerate configuration that can flip a decision the wrong way -- which is
305
+ the failure mode a floating-point implementation has to defend against.
306
+
307
+ Returns ``None`` for an empty point set; the caller decides what that means.
308
+ """
309
+ pts = [(int(p[0]), int(p[1])) for p in points]
310
+ if not pts:
311
+ return None
312
+ random.Random(_SEED).shuffle(pts)
313
+
314
+ circle = (Fraction(pts[0][0]), Fraction(pts[0][1]), Fraction(0))
315
+ for i, p in enumerate(pts):
316
+ if _contains(circle, p):
317
+ continue
318
+ circle = (Fraction(p[0]), Fraction(p[1]), Fraction(0))
319
+ for j, q in enumerate(pts[:i]):
320
+ if _contains(circle, q):
321
+ continue
322
+ circle = _from_two(p, q)
323
+ for r in pts[:j]:
324
+ if not _contains(circle, r):
325
+ circle = _from_three(p, q, r)
326
+ return circle
327
+
328
+
329
+ def min_enclosing_circle(points):
330
+ """:func:`min_enclosing_circle_exact` as floats: ``(cx, cy, radius)``.
331
+
332
+ Source: stands in for the Miniball call in ``CGAL_minR.cpp:81-89`` (UIOOPS v3.1.4).
333
+
334
+ ``None`` for an empty point set.
335
+ """
336
+ circle = min_enclosing_circle_exact(points)
337
+ if circle is None:
338
+ return None
339
+ cx, cy, r2 = circle
340
+ return float(cx), float(cy), math.sqrt(r2)
341
+
342
+
343
+ def cgal_min_r(c) -> float:
344
+ """``CGAL_minR(c)`` -- the enclosing-circle diameter in diode units.
345
+
346
+ Two edge cases, both taken from the C++ rather than invented:
347
+
348
+ * **An empty matrix returns 0.0.** ``CGAL_minR.cpp:47-52`` tests ``0 == m*n``
349
+ and returns before touching Miniball.
350
+ * **A non-empty matrix with no shadowed pixel returns NaN.** That case falls
351
+ through to Miniball with an empty point range. The constructor's
352
+ ``assert(points_begin != points_end)`` is compiled out -- MATLAB's ``mex``
353
+ defines ``NDEBUG`` -- so ``pivot_mb`` runs its loop over nothing, leaves
354
+ ``current_sqr_r`` at its initial ``-1`` (``Miniball.hpp:183``), and the
355
+ caller takes ``sqrt(-1)``. Preserved as NaN rather than "fixed" to 0: a
356
+ zero would be a plausible diameter and would flow silently into
357
+ ``area_ratio`` and the size distribution, where NaN is at least loud.
358
+ """
359
+ a = np.asarray(c)
360
+ if a.size == 0:
361
+ return 0.0
362
+ points = _shadow_points(a)
363
+ if len(points) == 0:
364
+ return math.nan
365
+ circle = min_enclosing_circle(_hull_candidates(points))
366
+ return 1.0 + 2.0 * circle[2]