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,11 @@
1
+ # PEP 561 marker.
2
+ #
3
+ # This package is fully annotated and `mypy src` is clean, but without this
4
+ # file a type checker in a DOWNSTREAM project ignores every annotation --
5
+ # PEP 561 says an installed package's types are invisible unless it says so.
6
+ # Nothing in this repository would ever have noticed: `mypy src` runs against
7
+ # the source tree, where the marker is irrelevant.
8
+ #
9
+ # Added 2026-09-12 in a release-readiness pass. `tests/test_py_typed.py`
10
+ # asserts one exists per shipped package and that setuptools is told to
11
+ # include it, because a marker that is not packaged is the same as no marker.
arrayprobe_uiops/qc.py ADDED
@@ -0,0 +1,169 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """v3.5 ``imgProc_sm.m:801-846`` -- the ``iQC=1``
3
+ (the UIOPS quality-control option) denoise pass (Part C).
4
+
5
+ Run on the char image ``c`` *after* ``dec2bin`` assembly (``:792-795``) and
6
+ *before* the width check (``:849-853``) and every measurement, so a cleaned
7
+ image is what every downstream measurement sees. Pure numpy: the port
8
+ refuses scipy in core (it is in the ``arrayprobe[extra]`` extra; ``intarr.py:68`` imports
9
+ it lazily as an enhancement extra only), so the three MATLAB Image Processing
10
+ Toolbox calls this pass makes -- ``bwareaopen``, ``bwconncomp``, ``bwdist``
11
+ with ``'chessboard'`` -- are each reimplemented directly against their own
12
+ documented semantics rather than pulled from a dependency.
13
+
14
+ Octave 11.3 (the differential oracle) supplies the first three from its
15
+ ``image`` package (2.20.0, measured present, ``pkg load image``);
16
+ ``mink`` (MATLAB R2017b+) is not implemented there (measured
17
+ ``exist('mink')==0``) and is supplied by ``octave_oracle/v35_qc_shims/mink.m``,
18
+ placed on the Octave path *ahead of* the vendored tree -- the tree is never
19
+ edited.
20
+
21
+ What it computes, per particle, verbatim from ``:801-846``:
22
+
23
+ 1. ``pix_thresh = 5``; ``P = max(5, floor(0.01*5*sum(sum(c=='0'))))`` --
24
+ ``'0'`` is the shadowed diode (``:263``, ``:803``).
25
+ 2. ``c_logical = bwareaopen('1' - c, P)`` -- MATLAB's 2-D default
26
+ connectivity is **8**; Octave's ``bwareaopen`` default
27
+ (``conndef(2,"maximal")``) is also 8 (measured).
28
+ 3. If every pixel of ``c_logical`` is False: ``num_subparticles = 0``,
29
+ ``dist_min = 0``, and **``c`` is returned unchanged** (``:804-807`` --
30
+ the ``continue`` is commented out in the vendored file).
31
+ 4. Else: ``c_parts = bwconncomp(c_logical, 8)``;
32
+ ``num_subparticles = c_parts.NumObjects`` (``:809-810``). If ``> 1``:
33
+ for each component, ``darr = bwdist(component_only, 'chessboard')``
34
+ (``:814-819``); for every pair, ``dist(a,b) = min(darr_a + darr_b) - 1``
35
+ (``:833``); ``dist_min = max(mink(dist_arr, n-1))``, i.e. the
36
+ **(n-1)-th smallest** pairwise distance (``:835``). If ``== 1``:
37
+ ``dist_min = 0`` (``:837``).
38
+ 5. ``if dist_min < 5: num_subparticles = 1`` (``:840-842``) --
39
+ **``dist_min`` is NOT reset**, so a two-component image found 3 apart
40
+ merges to ``(num_subparticles=1, dist_min=3)``: a reader of
41
+ ``subparticle_mindist`` sees a nonzero distance for what the file calls
42
+ a single particle. Preserved, not corrected --
43
+ not a bug this port may fix.
44
+ 6. ``c = char('1' - c_logical)`` (``:844``) -- the cleaned image replaces
45
+ ``c`` for all later measurements, only in the branch that reached here
46
+ (i.e. never in the branch-3 no-survivor case).
47
+
48
+ Component discovery order (a column-major raster scan, matching
49
+ ``bwconncomp``'s own ``PixelIdxList`` order) does not affect ``dist_min``:
50
+ the value is ``min`` over each pairwise Chebyshev distance transform, then
51
+ an order statistic over the resulting (order-independent, since it is a set
52
+ of pairwise distances) list -- so any consistent labelling gives the same
53
+ answer. ``tests/test_v35_qc.py`` pins this with a shuffle test rather than
54
+ asserting it.
55
+ """
56
+
57
+ from __future__ import annotations
58
+
59
+ import itertools
60
+
61
+ import numpy as np
62
+
63
+ from .particle import shadow_mask
64
+
65
+ __all__ = ["qc_image"]
66
+
67
+ #: ``:802`` -- the experimental percent threshold, and ``:803``'s ``0.01 *``
68
+ #: factor kept as its own literal so the MATLAB expression stays visible.
69
+ _PIX_THRESH = 5
70
+
71
+
72
+ def _label8(mask: np.ndarray) -> list[np.ndarray]:
73
+ """8-connected components of a boolean 2-D array (``bwconncomp(mask, 8)``).
74
+
75
+ Returns one boolean mask per component, in column-major first-pixel
76
+ discovery order (MATLAB's own linear-index convention) -- documented
77
+ only for reproducibility of intermediate state; see the module
78
+ docstring for why ``dist_min`` does not depend on this order.
79
+ """
80
+ nrows, ncols = mask.shape
81
+ visited = np.zeros_like(mask, dtype=bool)
82
+ components: list[np.ndarray] = []
83
+ for col in range(ncols):
84
+ for row in range(nrows):
85
+ if not mask[row, col] or visited[row, col]:
86
+ continue
87
+ comp = np.zeros_like(mask, dtype=bool)
88
+ stack = [(row, col)]
89
+ visited[row, col] = True
90
+ while stack:
91
+ r, c0 = stack.pop()
92
+ comp[r, c0] = True
93
+ for dr in (-1, 0, 1):
94
+ for dc in (-1, 0, 1):
95
+ if dr == 0 and dc == 0:
96
+ continue
97
+ nr, nc = r + dr, c0 + dc
98
+ if (0 <= nr < nrows and 0 <= nc < ncols
99
+ and mask[nr, nc] and not visited[nr, nc]):
100
+ visited[nr, nc] = True
101
+ stack.append((nr, nc))
102
+ components.append(comp)
103
+ return components
104
+
105
+
106
+ def _bwareaopen(mask: np.ndarray, min_pixels: int) -> np.ndarray:
107
+ """``bwareaopen(mask, min_pixels)`` -- keep 8-connected components with at
108
+ least ``min_pixels`` pixels; MATLAB's own wording ("removes ... fewer than
109
+ P pixels") makes ``>= P`` the surviving set, not ``> P``."""
110
+ out = np.zeros_like(mask, dtype=bool)
111
+ for comp in _label8(mask):
112
+ if int(comp.sum()) >= min_pixels:
113
+ out |= comp
114
+ return out
115
+
116
+
117
+ def _chessboard_distance_transform(component: np.ndarray) -> np.ndarray:
118
+ """``bwdist(component, 'chessboard')`` -- per-pixel minimum Chebyshev
119
+ distance to the nearest True pixel of ``component``, over the component's
120
+ own full grid (``:814-819``). Particle images here are at most a few
121
+ hundred pixels, so brute force is exact and obviously right."""
122
+ fg = np.argwhere(component)
123
+ if fg.size == 0: # pragma: no cover -- every component here is non-empty
124
+ return np.full(component.shape, np.inf)
125
+ rows, cols = np.indices(component.shape)
126
+ all_pts = np.stack([rows.ravel(), cols.ravel()], axis=1)
127
+ d = np.abs(all_pts[:, None, :] - fg[None, :, :]).max(axis=2).min(axis=1)
128
+ return d.reshape(component.shape).astype(np.float64)
129
+
130
+
131
+ def qc_image(c: np.ndarray) -> tuple[np.ndarray, int, int]:
132
+ """``imgProc_sm.m:801-846``. Returns ``(c_after, num_subparticles, dist_min)``.
133
+
134
+ ``c`` is the ``(n_slices, diodenum)`` particle image in any form
135
+ :func:`arrayprobe.particle.shadow_mask` accepts (the same convention
136
+ ``measure_record`` uses downstream). ``c_after`` is returned in that same
137
+ canonical form on both branches -- the vendored file's own ``char('1' -
138
+ c_logical)`` rebuild (``:844``) is reproduced literally as a ``'0'``/``'1'``
139
+ ASCII array so a caller inspecting ``c_after``'s dtype sees the same
140
+ convention as the input, not a silently-widened boolean.
141
+ """
142
+ shadow = shadow_mask(c) # True where c == '0' (shadowed) -- :801-806
143
+ n_shadowed = int(shadow.sum())
144
+ min_pixels = max(5, int(np.floor(0.01 * _PIX_THRESH * n_shadowed))) # :803
145
+
146
+ c_logical = _bwareaopen(shadow, min_pixels) # :803
147
+
148
+ if not c_logical.any(): # :804
149
+ return c, 0, 0 # :805-807 -- c unchanged
150
+
151
+ components = _label8(c_logical) # :809
152
+ num_subparticles = len(components) # :810
153
+
154
+ if num_subparticles > 1: # :813
155
+ darr = [_chessboard_distance_transform(comp) for comp in components] # :814-819
156
+ dist_arr = [
157
+ float(np.min(darr[a] + darr[b])) - 1.0 # :833
158
+ for a, b in itertools.combinations(range(num_subparticles), 2) # :822 nchoosek
159
+ ]
160
+ # :835 -- max(mink(dist_arr, n-1)) is the (n-1)-th smallest value.
161
+ dist_min = int(round(sorted(dist_arr)[num_subparticles - 2]))
162
+ else:
163
+ dist_min = 0 # :837
164
+
165
+ if dist_min < 5: # :840-842 -- dist_min is NOT reset here
166
+ num_subparticles = 1
167
+
168
+ c_after = np.where(c_logical, np.uint8(ord("0")), np.uint8(ord("1"))) # :844
169
+ return c_after, num_subparticles, dist_min
@@ -0,0 +1,8 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Raw-probe-file decoders both engines share: ``read_binary_PMS.m`` and the ``.MK.csv`` reader.
3
+
4
+ Moved from :mod:`arrayprobe.readers` (code both engines share lives in the v3.5
5
+ engine); the old module paths are alias shims back to these.
6
+ """
7
+
8
+ from __future__ import annotations
@@ -0,0 +1,74 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """A reader for the ``.MK.csv`` sidecar ``read_binary_SPEC.m`` writes with no
3
+ line terminators at all -- the unterminated mask sidecar: *tooling*, since it reads an existing
4
+ file and computes no new number.
5
+
6
+ **Why the file has no newlines.** ``read_binary_SPEC.m:313-315`` declares
7
+ twenty ``%d`` conversions in its format string but supplies only nineteen
8
+ values (``timeWord``, sixteen ``MaskBits``, ``timeStart``, ``timeEnd``).
9
+ MATLAB's ``fprintf`` stops the instant the data runs out, dropping the
10
+ trailing ``' \\n'`` -- so every mask record in a run lands on one unbroken
11
+ line, confirmed by actually running the source under Octave (see
12
+ :class:`arrayprobe.readers.spec.SidecarWriter`'s docstring, which this port's
13
+ own writer reproduces byte-for-byte).
14
+
15
+ **Why a reader is still possible despite that.** Each record is a *fixed*
16
+ width -- exactly nineteen integers, each written as ``str(v) + ", "`` -- so
17
+ the file is unambiguously splittable by counting tokens, not by looking for a
18
+ delimiter that was never written. This module does the counting; it does not
19
+ try to recover the missing newlines, because there is nothing to recover them
20
+ *from* -- the information which byte offset MATLAB's writer happened to be at
21
+ when it moved to the next record was never distinguishable from "still the
22
+ same record" in the first place, and guessing would be exactly the kind of
23
+ invented fact this project's own doctrine refuses to produce.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from dataclasses import dataclass
29
+ from pathlib import Path
30
+
31
+ #: timeWord + 16 MaskBits + timeStart + timeEnd, matching read_binary_SPEC.m:314's argument list.
32
+ _RECORD_WIDTH = 19
33
+ _N_MASK_BITS = 16
34
+
35
+ __all__ = ["MaskRecord", "load_mask_csv"]
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class MaskRecord:
40
+ """One automask event, in the order ``read_binary_SPEC.m:314`` writes it."""
41
+
42
+ time_word: int
43
+ mask_bits: tuple[int, ...]
44
+ time_start: int
45
+ time_end: int
46
+
47
+
48
+ def load_mask_csv(path: str | Path) -> list[MaskRecord]:
49
+ """Parse a ``.MK.csv`` sidecar into its fixed-width records.
50
+
51
+ Source: reads what ``read_binary_SPEC.m:314-315`` (UIOOPS v3.1.4) writes.
52
+
53
+ Raises :class:`ValueError` if the file's token count is not a multiple of
54
+ nineteen -- a truncated write or a file that is not actually a mask
55
+ sidecar, either of which should stop a caller rather than silently drop
56
+ a partial trailing record.
57
+ """
58
+ text = Path(path).read_text(encoding="ascii")
59
+ tokens = [t for t in text.split(",") if t.strip()]
60
+ if len(tokens) % _RECORD_WIDTH != 0:
61
+ raise ValueError(
62
+ f"{path}: {len(tokens)} comma-separated values is not a multiple of "
63
+ f"{_RECORD_WIDTH} -- not a well-formed .MK.csv (or it was truncated)")
64
+ values = [int(t) for t in tokens]
65
+ records = []
66
+ for i in range(0, len(values), _RECORD_WIDTH):
67
+ row = values[i:i + _RECORD_WIDTH]
68
+ records.append(MaskRecord(
69
+ time_word=row[0],
70
+ mask_bits=tuple(row[1:1 + _N_MASK_BITS]),
71
+ time_start=row[1 + _N_MASK_BITS],
72
+ time_end=row[2 + _N_MASK_BITS],
73
+ ))
74
+ return records
@@ -0,0 +1,239 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """NCAR OAP raw decoder -- ``read_binary_PMS.m``.
3
+
4
+ The format is an XML preamble (terminated by a literal ``</OAP>`` line) followed
5
+ by a flat stream of fixed **4116-byte records**: a 2-byte probe-type tag, nine
6
+ big-endian ``uint16`` header fields, then 4096 bytes of raw image data with
7
+ **no compression at all** -- unlike DMT's byte-level RLE (:mod:`arrayprobe.readers.dmt`)
8
+ or SPEC's run-length words (:mod:`arrayprobe.readers.spec`). The probe-type tag
9
+ routes each record to one of three output files (2DC, F2DC, 2DP); nothing else
10
+ about decoding a record depends on which type it is.
11
+
12
+ **Byte order is big-endian** (``fopen(...,'r','b')``, MATLAB's ``'ieee-be'``) --
13
+ the opposite of DMT's little-endian raw stream.
14
+
15
+ **The image reshape has no reversal.** ``reshape(data, n, 4096/n)`` is a plain
16
+ column-major reshape of the flat 4096-byte payload into an ``(n, 4096/n)``
17
+ MATLAB array (``n`` is 4 for 2DC/2DP, 8 for F2DC). Unlike DMT's byte-reversed
18
+ 8-groups, this is passed straight to :func:`arrayprobe.ncio.put_var`, which
19
+ performs the MATLAB-order-in/on-disk-order-out conversion itself.
20
+
21
+ **A preserved bug, found by tracing every ``netcdf.putVar`` call's file handle
22
+ against its variable id, not by reading the branch labels: the ``'C6'`` tag
23
+ (``probetype == [67, 54]``, ``:147-166``) writes its nine scalar fields to the
24
+ *2DC file* (`f`), not the F2DC file (`f1`) its own comment claims.** Only the
25
+ image write on that branch (``:159``) correctly targets ``f1``. The scalar
26
+ writes use variable ids that were allocated on ``f1`` (``varid02..varid92``)
27
+ but are passed to ``netcdf.putVar(f, ...)``, MATLAB's low-level call, which
28
+ resolves the id **within whichever file handle it is given** -- so the write
29
+ lands on `f`'s *own* variable of the same numeric id. Both files declare their
30
+ ten variables in identical order (year, month, ..., tas, data), so id-for-id
31
+ this happens to hit the correctly *named* variable, just in the wrong file:
32
+ a `'C6'` record's year/month/day/... land in the 2DC output, at the F2DC
33
+ write-counter's index (``kk2-1``) -- a different index sequence than 2DC's
34
+ own counter (``kk``), so it can silently overwrite an unrelated 2DC record's
35
+ scalar fields while leaving that record's image untouched, or extend the 2DC
36
+ file with scalar-populated, image-empty (fill-value) trailing rows. Meanwhile
37
+ the F2DC file gets `'C6'` **images with no matching scalar fields** at that
38
+ same index, since nothing in this branch writes them to `f1`. Verified by
39
+ constructing a synthetic file and tracing both ``f`` and ``f1`` on the real
40
+ MATLAB under Octave: a `'C6'` record's `second`/`millisec`/`tas` show up in
41
+ the **2DC** output, not the F2DC one. Flagged for the UIOOPS authors
42
+ -- likely a copy-paste of the `'C1'` branch
43
+ above it that missed updating the file handle on nine of its ten lines.
44
+
45
+ **Preserved verbatim, not fixed**: the ``'C6'`` branch below writes scalars
46
+ to the 2DC file/varids and the image to the F2DC file/varids, exactly
47
+ mirroring the bug. The ``'C4'`` tag (``probetype == [67, 52]``) has no such
48
+ bug -- all ten of its writes correctly target `f1`, at its own independent
49
+ counter (``kk3``).
50
+
51
+ **The trailing EOF probe (``:215-222``) is a byte-by-byte peek-and-rewind
52
+ with no observable effect beyond "does a full next record exist".** MATLAB
53
+ reads up to 4116 individual bytes checking ``feof`` after each one, then
54
+ unconditionally seeks back exactly 4116 bytes -- a no-op if that many bytes
55
+ were actually available, which is the only case where the loop continues.
56
+ This port reproduces the *outcome* (a trailing partial record, less than
57
+ 4116 bytes, is never decoded) via a strict read-or-stop check rather than
58
+ the byte-by-byte mechanism, since the mechanism itself has no effect a
59
+ caller can observe. The first record has no probe in front of it, so a
60
+ file whose first record is short is handled apart (:func:`_first_record_short`).
61
+
62
+ **Not ported: the ``'*'``-glob and ``outfilename == '1'`` auto-naming
63
+ branches (``:8-33``).** Driver-script conveniences for
64
+ ``automaticDataProcessing.m``; this port's callers always pass an explicit
65
+ output base path, the same simplification already made for
66
+ :func:`arrayprobe.readers.dmt.read_binary_DMT`.
67
+ """
68
+
69
+ from __future__ import annotations
70
+
71
+ import numpy as np
72
+
73
+ from .. import ncio
74
+ from ..matlab_compat import MatlabIndexError
75
+
76
+ __all__ = ["read_binary_PMS"]
77
+
78
+ _RECORD_BYTES = 4116 # 2 (tag) + 9*2 (header fields) + 4096 (data)
79
+ _HEADER_FIELDS = ("hour", "minute", "second", "year", "month", "day",
80
+ "tas", "millisec", "wkday")
81
+ _SCALAR_FIELDS = ("year", "month", "day", "hour", "minute", "second",
82
+ "millisec", "wkday", "tas")
83
+
84
+ _N_2DC = 4
85
+ _N_F2DC = 8
86
+ _N_2DP = 4
87
+
88
+ _TAG_2DC = (67, 49) # 'C1'
89
+ _TAG_F2DC_A = (67, 54) # 'C6' -- the buggy branch, see module docstring
90
+ _TAG_F2DC_B = (67, 52) # 'C4'
91
+ _TAG_2DP_PREFIX = 80 # 'P*'
92
+
93
+
94
+ def _def_output(filename: str, n: int):
95
+ """One output file: eight timestamp vars, ``tas``, and the packed image.
96
+
97
+ ``:45-59`` -- dims declared ``[ImgRowlen(n) ImgBlocklen(4096/n) time]``,
98
+ MATLAB order, same convention as :mod:`arrayprobe.readers.dmt` and
99
+ :mod:`arrayprobe.readers.spec`. Variables are declared in the same order
100
+ (year, month, day, hour, minute, second, millisec, wkday, tas, data) for
101
+ every output file -- load-bearing for the `'C6'` bug above, which relies
102
+ on both files assigning identical numeric ids to identically-named vars.
103
+ """
104
+ f = ncio.create(filename, "clobber")
105
+ dim_time = f.def_dim("time", ncio.NC_UNLIMITED)
106
+ dim_row = f.def_dim("ImgRowlen", n)
107
+ dim_block = f.def_dim("ImgBlocklen", 4096 // n)
108
+ varids = {
109
+ "year": f.def_var("year", "short", dim_time),
110
+ "month": f.def_var("month", "byte", dim_time),
111
+ "day": f.def_var("day", "byte", dim_time),
112
+ "hour": f.def_var("hour", "byte", dim_time),
113
+ "minute": f.def_var("minute", "byte", dim_time),
114
+ "second": f.def_var("second", "byte", dim_time),
115
+ "millisec": f.def_var("millisec", "short", dim_time),
116
+ "wkday": f.def_var("wkday", "short", dim_time),
117
+ "tas": f.def_var("tas", "double", dim_time),
118
+ "data": f.def_var("data", "int", [dim_row, dim_block, dim_time]),
119
+ }
120
+ f.end_def()
121
+ return f, varids
122
+
123
+
124
+ def _write_scalars(f, varids, index: int, header: dict) -> None:
125
+ for name in _SCALAR_FIELDS:
126
+ f.put_var(varids[name], index, 1, header[name])
127
+
128
+
129
+ def _write_image(f, varids, index: int, image_matlab: np.ndarray) -> None:
130
+ n, blocklen = image_matlab.shape
131
+ f.put_var(varids["data"], [0, 0, index], [n, blocklen, 1], image_matlab)
132
+
133
+
134
+ def _skip_xml_header(fh) -> None:
135
+ """``:103-106`` -- read text lines until one strips to literally ``</OAP>``."""
136
+ line = bytearray()
137
+ while True:
138
+ b = fh.read(1)
139
+ if not b:
140
+ # fgetl returns a last line that has no newline, so a file ending
141
+ # in ``</OAP>`` still ends the header (then there are no records).
142
+ if line.decode("ascii", errors="replace").strip() == "</OAP>":
143
+ return
144
+ raise ValueError("no </OAP> header terminator found before EOF")
145
+ if b == b"\n":
146
+ if line.decode("ascii", errors="replace").strip() == "</OAP>":
147
+ return
148
+ line.clear()
149
+ else:
150
+ line += b
151
+
152
+
153
+ def _first_record_short(chunk: bytes) -> None:
154
+ """What ``:109-123`` make of a first record cut short by the end of the file.
155
+
156
+ The first record is read without the EOF probe that guards every later one
157
+ (``:215-222``), so a short one reaches the tag tests. Octave-measured
158
+ (``tests/test_reader_edge_octave.py::PmsAgainstOctave``): no bytes at all end the run
159
+ cleanly (``fgetl`` has already left the file at its end); one byte dies at
160
+ ``:127``'s ``probetype(2)``; a recognised tag dies at the branch's
161
+ ``reshape`` of a short ``data``; an unrecognised tag is printed and the run
162
+ ends. Raises :class:`~arrayprobe.matlab_compat.MatlabIndexError` for the
163
+ two deaths.
164
+ """
165
+ if not chunk:
166
+ return
167
+ if len(chunk) < 2:
168
+ raise MatlabIndexError(
169
+ "read_binary_PMS.m:127: probetype(2) of a 1-byte record (truncated file)")
170
+ tag = (chunk[0], chunk[1])
171
+ if tag in (_TAG_2DC, _TAG_F2DC_A, _TAG_F2DC_B) or tag[0] == _TAG_2DP_PREFIX:
172
+ raise MatlabIndexError(
173
+ f"read_binary_PMS.m: reshape of a {max(0, len(chunk) - 20)}-byte data block "
174
+ "to 4096 bytes -- the first record is truncated")
175
+
176
+
177
+ def _reshape_matlab(data: np.ndarray, n: int) -> np.ndarray:
178
+ """``reshape(data, n, 4096/n)`` -- MATLAB column-major, no byte reversal."""
179
+ return data.reshape((n, data.shape[0] // n), order="F")
180
+
181
+
182
+ def read_binary_PMS(infilename, outfilename): # noqa: N802,N803
183
+ """``read_binary_PMS.m`` -- raw NCAR-OAP file to three probe-type outputs.
184
+
185
+ Writes ``<outfilename>.2dc.cdf``, ``<outfilename>.f2dc.cdf`` and
186
+ ``<outfilename>.2dp.cdf``. Returns ``(n_2dc, n_f2dc_c6, n_f2dc_c4, n_2dp)``
187
+ -- the four raw MATLAB write-counters (``kk``, ``kk2``, ``kk3``, ``kk1``),
188
+ kept separate rather than summed because ``'C6'`` and ``'C4'`` records
189
+ are not equivalent: see the module docstring for what each actually
190
+ writes and where.
191
+ """
192
+ f_2dc, v_2dc = _def_output(f"{outfilename}.2dc.cdf", _N_2DC)
193
+ f_f2dc, v_f2dc = _def_output(f"{outfilename}.f2dc.cdf", _N_F2DC)
194
+ f_2dp, v_2dp = _def_output(f"{outfilename}.2dp.cdf", _N_2DP)
195
+
196
+ kk = kk1 = kk2 = kk3 = 0 # 0-based; MATLAB's kk/kk1/kk2/kk3 start at 1
197
+
198
+ try:
199
+ with open(infilename, "rb") as fh:
200
+ _skip_xml_header(fh)
201
+ first = True
202
+ while True:
203
+ chunk = fh.read(_RECORD_BYTES)
204
+ if len(chunk) < _RECORD_BYTES: # :215-222's outcome, see docstring
205
+ if first:
206
+ _first_record_short(chunk)
207
+ break
208
+ first = False
209
+ tag = (chunk[0], chunk[1])
210
+ fields = np.frombuffer(chunk[2:20], dtype=">u2")
211
+ header = dict(zip(_HEADER_FIELDS, (int(v) for v in fields), strict=True))
212
+ data = np.frombuffer(chunk[20:], dtype=np.uint8)
213
+
214
+ if tag == _TAG_2DC:
215
+ image = _reshape_matlab(data, _N_2DC)
216
+ _write_scalars(f_2dc, v_2dc, kk, header)
217
+ _write_image(f_2dc, v_2dc, kk, image)
218
+ kk += 1
219
+ elif tag == _TAG_F2DC_A: # 'C6' -- upstream bug, see docstring
220
+ image = _reshape_matlab(data, _N_F2DC)
221
+ _write_scalars(f_2dc, v_2dc, kk2, header) # wrong file, preserved
222
+ _write_image(f_f2dc, v_f2dc, kk2, image) # right file
223
+ kk2 += 1
224
+ elif tag == _TAG_F2DC_B: # 'C4' -- correct
225
+ image = _reshape_matlab(data, _N_F2DC)
226
+ _write_scalars(f_f2dc, v_f2dc, kk3, header)
227
+ _write_image(f_f2dc, v_f2dc, kk3, image)
228
+ kk3 += 1
229
+ elif tag[0] == _TAG_2DP_PREFIX:
230
+ image = _reshape_matlab(data, _N_2DP)
231
+ _write_scalars(f_2dp, v_2dp, kk1, header)
232
+ _write_image(f_2dp, v_2dp, kk1, image)
233
+ kk1 += 1
234
+ finally:
235
+ f_2dc.close()
236
+ f_f2dc.close()
237
+ f_2dp.close()
238
+
239
+ return kk, kk2, kk3, kk1
@@ -0,0 +1,57 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """``loadTASinfo_2DS.m`` -- read a flight's true-air-speed CSV sidecar.
3
+
4
+ ``read_binary_SPEC.m``'s ``.tas.csv`` sidecar (written by
5
+ ``read_binary_SPEC`` in the v3.1.4 validation engine (not included in this package) on this port's
6
+ side) has nine
7
+ columns; MATLAB's auto-generated importer keeps only the first two
8
+ (``timehhmmss``, ``tas``) via a ``'%f%f%*s%*s%*s%*s%*s%*s%*s'`` format string
9
+ -- there is no arithmetic anywhere in this function, only parsing.
10
+
11
+ **Octave cannot run the real source at all**, which is a real, worth-recording
12
+ limitation distinct from every other "runs fine under Octave" case this port
13
+ has found: ``textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, ...)`` with
14
+ ``endRow`` defaulting to ``Inf`` is accepted by MATLAB (documented behavior --
15
+ read to end of file) but Octave rejects the infinite repeat count outright
16
+ (``textscan: REPEAT = inf is too large``). ``octave_oracle/shims/loadTASinfo_2DS.m``
17
+ reproduces the same two-column parse by a different route and stands in as the
18
+ oracle -- "shim-derived" here means only "parsed by different code," a weaker
19
+ asterisk than ``CGAL_minR``'s, since no arithmetic differs at all.
20
+
21
+ That shim (and this port) both drop a trailing all-zero row when present: a
22
+ ``dlmread`` artifact from a CSV that ends with a trailing newline, which the
23
+ real MATLAB ``textscan`` would not produce. A spurious ``(0, 0)`` sample would
24
+ put a zero TAS into the sample-volume calculation downstream, so dropping it
25
+ is required for fidelity to what ``textscan`` actually returns, not an
26
+ arbitrary cleanup.
27
+
28
+ Provenance: ``loadTASinfo_2DS.m`` (ORACLES-local code, not part of
29
+ distributed UIOOPS -- there is no upstream to report this to). Validated
30
+ against the Octave shim on a synthetic fixture:
31
+ ``octave_oracle/run_s9_tasinfo_bank.py``, ``tests/test_readers_tasinfo.py``.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ from pathlib import Path
37
+
38
+ import numpy as np
39
+
40
+ __all__ = ["load_tas_info"]
41
+
42
+
43
+ def load_tas_info(path) -> tuple[np.ndarray, np.ndarray]:
44
+ """``[timehhmmss, tas] = loadTASinfo_2DS(filename)``.
45
+
46
+ Returns ``(timehhmmss, tas)``, both 1-D ``float64`` arrays. Reads only
47
+ the first two columns of the CSV; every other column (there are seven
48
+ in a real ``.tas.csv``) is discarded, matching the source's own
49
+ ``'%f%f%*s...'`` format string.
50
+ """
51
+ # usecols=(0, 1): the source's own '%f%f%*s...' skips every other column
52
+ # unconditionally, whatever it holds -- reading only the first two here
53
+ # means this doesn't choke on non-numeric content in the discarded ones.
54
+ m = np.atleast_2d(np.loadtxt(Path(path), delimiter=",", usecols=(0, 1)))
55
+ if m.size and np.all(m[-1] == 0):
56
+ m = m[:-1]
57
+ return m[:, 0], m[:, 1]