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,161 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """``CGAL_EllipseSize(c)`` for v3.5 -- gains centre x/y outputs, drops the
3
+ major/minor "+1" bias v3.1.4 has.
4
+
5
+ Ported from: ``CGAL_EllipseSize.cpp`` (UIOOPS v3.5, CHANGED from v3.1.4 --
6
+ Lee Dunnavan and Joe Finlon, 29 Jan 2024). **An Octave oracle exists since 2026-09-13**: Part D
7
+ measured that the
8
+ ``cgal_oracle`` conda env's CGAL headers compile this exact ``.cpp`` clean
9
+ under Octave's own ``mkoctfile --mex`` (``octave_oracle/mex_build/README.md``),
10
+ and :func:`cgal_ellipse_size` is now goldened against the real
11
+ ``CGAL_EllipseSize_v35.mex`` on a dedicated non-degenerate fixture
12
+ (``octave_oracle/run_v35_rect_ellipse_bank.py``,
13
+ ``tests/test_v35_rect_ellipse.py``) -- doctrine layer 2 for major/minor/x/y
14
+ (within the Khachiyan-vs-CGAL bound already established for the v3.1.4 port)
15
+ and for the angle on well-conditioned (non-circular) particles; layer 3
16
+ still, by necessity, for the near-circular tie case point 5 below describes,
17
+ where the real MEX was independently measured to disagree with ITSELF
18
+ across separate Octave processes on identical input (CGAL's ``Min_ellipse_2``
19
+ is a randomized incremental algorithm), so no run of it is more authoritative
20
+ than another to compare against. **The ellipse-fitting algorithm itself is
21
+ unchanged between versions**; the diff (read in full, both files) is:
22
+
23
+ 1. **Two new outputs, ``x``/``y``, the ellipse centre** -- computed in the
24
+ C++ from the implicit conic's coefficients: ``x = 1+(2*c*d-b*f)/(b*b-4*a*c)``,
25
+ ``y = 1+(2*a*f-b*d)/(b*b-4*a*c)`` (``:154-155``). This is algebraically
26
+ the conic-form route to a quantity the Khachiyan fit already produces
27
+ directly as its own ``center`` -- see
28
+ :func:`arrayprobe.geometry.min_ellipse._khachiyan_ellipsoid`, reused here
29
+ unmodified. No need to reconstruct a/b/c/d/f/g to get there.
30
+ 2. **``major``/``minor`` DROP the "+1." bias v3.1.4 has** (``:127-128``:
31
+ v3.1.4 is ``major=1.+2*sqrt(...)``; v3.5 is ``major=2*sqrt(...)``, no
32
+ leading term) -- while the NEW ``x``/``y`` outputs GAIN their own "+1"
33
+ (the same 0-based-to-1-based MATLAB-index convention v3.1.4 puts on
34
+ major/minor instead). Preserved exactly as measured: this is not the same
35
+ bias moved, it is applied to different outputs than in v3.1.4.
36
+ 3. **A sign-normalization block** (v3.5 only, ``:107-117``): if the conic
37
+ coefficient ``a`` is negative, every coefficient is negated. Because the
38
+ Khachiyan fit here never produces the raw CGAL conic coefficients at all
39
+ (this port reaches the ellipse a different, coefficient-free way), this
40
+ normalization has no analogue to preserve -- it is CGAL's own internal
41
+ housekeeping for a representation this port does not use.
42
+ 4. **A named ``PI = 3.1415926`` used consistently** for the angle-wrap
43
+ comparison AND the add/subtract (``:148-152``). v3.1.4 uses
44
+ ``3.1415926/2`` for the comparison but a DIFFERENT, more precise
45
+ ``3.141592653`` for the actual add/subtract -- an inconsistency v3.1.4's
46
+ own Python port (:data:`arrayprobe.geometry.min_ellipse._TRUNCATED_PI`)
47
+ preserves exactly. v3.5 fixes the inconsistency; ported as fixed, using
48
+ ``3.1415926`` for both sides here.
49
+ 5. **Two new angle branches for the near-circular tie case**
50
+ (``a==c and b>0`` -> ``-PI/4``; ``a==c and b<0`` -> ``PI/4``, ``:141-144``)
51
+ are a CGAL-conic-coefficient tie-break this port has no coefficient-level
52
+ access to reproduce (see point 3) -- **not ported, flagged as an honest
53
+ gap**: near-circular particles (major approx minor) may get a
54
+ numerically-valid but not CGAL-bit-identical angle from this port's
55
+ eigendecomposition, which is not meaningfully different physically (the
56
+ major axis of a near-circle is not a well-conditioned quantity either
57
+ way) but is stated here rather than silently claimed as reproduced.
58
+ """
59
+ from __future__ import annotations
60
+
61
+ import math
62
+ from typing import Any
63
+
64
+ import numpy as np
65
+
66
+ from .geometry_core import (
67
+ _degenerate_segment_ellipse,
68
+ _is_collinear,
69
+ _khachiyan_ellipsoid,
70
+ _shadow_points_xy,
71
+ )
72
+
73
+ __all__ = ["cgal_ellipse_size"]
74
+
75
+ #: v3.5's own #define PI (CGAL_EllipseSize.cpp:40) -- used for BOTH the
76
+ #: comparison and the add/subtract, unlike v3.1.4's two-different-literals
77
+ #: inconsistency (see module docstring point 4).
78
+ _PI = 3.1415926
79
+
80
+
81
+ def _wrap_angle_v35(angle: float) -> float:
82
+ if angle > _PI / 2:
83
+ angle -= _PI
84
+ if angle < -_PI / 2:
85
+ angle += _PI
86
+ return angle
87
+
88
+
89
+ def _min_area_ellipse_with_center(points: Any) -> Any:
90
+ """Like :func:`arrayprobe.geometry.min_ellipse.min_area_ellipse`, but
91
+ also returns the fit centre -- v3.1.4's version discards it because
92
+ v3.1.4 never needed it. Returns ``(major, minor, angle, cx, cy)``;
93
+ major/minor are full axis lengths (diameters), NOT the "+1"-biased form.
94
+
95
+ **Bug found and fixed 2026-09-13 (Part D), not a Step-7 angle change.**
96
+ This used to ``return None`` for fewer than 3 points before ever reaching
97
+ the ``len(unique) < 3`` branch below -- which already exists specifically
98
+ to give a degenerate-segment answer for 1-2 point images -- so 1- and
99
+ 2-pixel particles (``pixel1``, ``two_pixel_diagonal`` in the driver's fixture;
100
+ "6 of 16" particles on real ORACLES data per
101
+ ``test_cgal_mex_oracle.py::test_real_data_contains_the_A16_trigger_in_its_first_record``)
102
+ raised ``TypeError: cannot unpack non-iterable NoneType object`` in
103
+ :func:`cgal_ellipse_size` instead of returning the degenerate value the
104
+ module docstring already promises ("the port returns instead of
105
+ aborting"). Latent because Part D (``rect_ellipse.py``) is the first
106
+ caller to reach ``extended=True`` on a real per-particle loop; the measurement block's own
107
+ ``min_ellipse`` tests never called this function with fewer than 3
108
+ points. The fix is simply not to special-case fewer-than-3 at all: the
109
+ ``len(unique) < 3`` branch immediately below already handles it
110
+ correctly (``unique`` can only be smaller than ``pts``), the same way it
111
+ already handles a 3+-point image whose points happen to collapse to
112
+ fewer than 3 distinct ones.
113
+ """
114
+ pts = np.asarray([(float(p[0]), float(p[1])) for p in points])
115
+
116
+ unique = np.unique(pts, axis=0)
117
+ if len(unique) < 3 or _is_collinear(unique):
118
+ span, minor, angle = _degenerate_segment_ellipse(unique)
119
+ if len(unique) == 1:
120
+ cx, cy = unique[0]
121
+ else:
122
+ # The same two extreme points _degenerate_segment_ellipse itself
123
+ # picks -- its own midpoint is the natural degenerate "centre".
124
+ diffs = unique[:, None, :] - unique[None, :, :]
125
+ dist2 = np.einsum("ijk,ijk->ij", diffs, diffs)
126
+ i, j = np.unravel_index(np.argmax(dist2), dist2.shape)
127
+ cx, cy = (unique[i] + unique[j]) / 2.0
128
+ return span, minor, angle, float(cx), float(cy)
129
+
130
+ result = _khachiyan_ellipsoid(pts)
131
+ if result is None:
132
+ span, minor, angle = _degenerate_segment_ellipse(unique)
133
+ cx, cy = unique.mean(axis=0)
134
+ return span, minor, angle, float(cx), float(cy)
135
+
136
+ center, shape = result
137
+ eigvals, eigvecs = np.linalg.eigh(shape)
138
+ semi_major = 1.0 / math.sqrt(eigvals[0])
139
+ semi_minor = 1.0 / math.sqrt(eigvals[1])
140
+ major_dir = eigvecs[:, 0]
141
+ angle = _wrap_angle_v35(math.atan2(major_dir[1], major_dir[0]))
142
+ return 2.0 * semi_major, 2.0 * semi_minor, angle, float(center[0]), float(center[1])
143
+
144
+
145
+ def cgal_ellipse_size(c: Any) -> tuple[float, float, float, float, float]:
146
+ """``CGAL_EllipseSize(c)`` -- ``(major, minor, angle, x, y)``, v3.5.
147
+
148
+ No shadowed pixel: ``(0.0, 0.0, 0.0, 0.0, 0.0)``, matching v3.5's own
149
+ zero-initialization of all five outputs before the early return
150
+ (``CGAL_EllipseSize.cpp:63-64,100-101``) -- unlike v3.1.4's Python port,
151
+ which only zero-initializes three outputs because v3.1.4 only computes
152
+ three.
153
+ """
154
+ a = np.asarray(c)
155
+ points = _shadow_points_xy(a)
156
+ if len(points) == 0:
157
+ return 0.0, 0.0, 0.0, 0.0, 0.0
158
+
159
+ result = _min_area_ellipse_with_center(points)
160
+ major, minor, angle, cx, cy = result
161
+ return major, minor, angle, 1.0 + cx, 1.0 + cy
@@ -0,0 +1,200 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Minimum-area enclosing rectangle -- the replacement for ``CGAL_RectSize.mexa64``.
3
+
4
+ ``CGAL_RectSize.cpp`` collects the coordinates of every shadowed pixel as
5
+ ``Point_2(i, j)`` -- **column first, row second** (``i`` is the outer/column
6
+ loop, ``j`` the inner/row loop; the opposite convention from
7
+ :mod:`arrayprobe.geometry.min_circle`'s ``(row, col)``, kept because the *angle* output depends
8
+ on which axis is which) -- takes their convex hull, and calls
9
+ ``CGAL::min_rectangle_2`` (the standard rotating-calipers minimum-area
10
+ bounding rectangle: Toussaint 1983; the minimum-area rectangle enclosing a
11
+ convex polygon always has one side flush with a hull edge, so trying every
12
+ hull edge as a candidate orientation is exhaustive, not heuristic). The two
13
+ resulting edge lengths get ``+1`` each (same "assume round diode, add 1 for
14
+ the boundary" convention :func:`arrayprobe_uiops.geometry_core.cgal_min_r`
15
+ documents) and are returned as ``(length, width, angle)`` with
16
+ ``length >= width`` and ``angle`` the direction, in radians, of whichever of
17
+ the two actual computed edges is the *longer* one.
18
+
19
+ **Why this port can be exact where the original is not**, same reasoning as
20
+ :mod:`arrayprobe.geometry.min_circle`: the minimum-area bounding rectangle of a finite point set
21
+ is unique (up to the symmetric tie of a square), so there is no "our
22
+ algorithm versus theirs" question -- agreement is a theorem. The comparison
23
+ across candidate hull-edge orientations needs no square root at all: with an
24
+ UNNORMALIZED integer edge vector ``(dx, dy)``, a point's projection along and
25
+ perpendicular to the edge, scaled by ``|edge|``, is a plain integer dot/cross
26
+ product; dividing the resulting box area by ``edge_len_sq`` (exact
27
+ :class:`fractions.Fraction`) gives the true area without ever taking a root.
28
+ Square roots appear exactly once, at the very end, converting the winning
29
+ orientation's two squared extents into the lengths CGAL's polygon output
30
+ would have reported.
31
+
32
+ Provenance: ``CGAL_RectSize.cpp`` (whole file); called at
33
+ ``imgProc_sm.m:849``, gated by ``iRectEllipse`` (never ``1`` in any real
34
+ ORACLES call -- see :mod:`arrayprobe.geometry`'s own module docstring).
35
+
36
+ **One place this port cannot claim more than "derived."** No Windows build of
37
+ the CGAL binary exists, and Octave cannot supply an oracle for a MEX-only
38
+ routine, so the degenerate cases below
39
+ were worked out by reading ``CGAL_RectSize.cpp`` and the standard rotating-
40
+ calipers algorithm, not by running the real CGAL library and comparing:
41
+
42
+ * **A single shadowed pixel** (a 1-point hull): no hull edge exists to rotate
43
+ around. Reported as ``length = width = 1.0`` (both extents 0, then the
44
+ ``+1``), ``angle = pi/2`` (the perpendicular-direction branch is taken
45
+ because ``L`` is not strictly greater than ``W``, and that direction's own
46
+ ``dx`` is 0).
47
+ * **All shadowed pixels collinear** (a 2-point hull after collapsing):
48
+ degenerates to a zero-width rectangle -- ``length = 1 + span``,
49
+ ``width = 1``, angle along the line.
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import math
55
+ from fractions import Fraction
56
+ from typing import Any
57
+
58
+ import numpy as np
59
+
60
+ from .particle import shadow_mask
61
+
62
+ __all__ = ["cgal_rect_size", "min_area_rectangle"]
63
+
64
+ #: The source's own truncated-pi literal (``CGAL_RectSize.cpp:134``), the
65
+ #: same one already preserved at ``imgProc_sm.m:428``/``:845`` and
66
+ #: ``sizeDist.m``'s equivalents -- not a typo unique to this file.
67
+ _TRUNCATED_PI = 3.1415926
68
+
69
+
70
+ def _shadow_points_xy(c: Any) -> np.ndarray:
71
+ """Shadowed pixels as ``(n, 2)`` integer ``(col, row)`` coordinates.
72
+
73
+ ``CGAL_RectSize.cpp:66-78`` walks the MATLAB array in column-major order
74
+ and pushes ``Point_2(i, j)`` -- ``i`` the column, ``j`` the row, both
75
+ 0-based -- for every entry equal to ``48`` (``'0'``, UIOOPS's "shadowed").
76
+ """
77
+ rows, cols = np.nonzero(shadow_mask(c))
78
+ return np.column_stack((cols, rows))
79
+
80
+
81
+ def _convex_hull(points: list[tuple[int, int]]) -> list[tuple[int, int]]:
82
+ """Andrew's monotone chain. Exact integer arithmetic, CCW, no closing dup.
83
+
84
+ ``cross <= 0`` (not ``< 0``) discards collinear interior points, so a
85
+ hull of exactly-collinear input correctly collapses to its two extremes
86
+ regardless of how many points were on the line.
87
+ """
88
+ pts = sorted(set(points))
89
+ if len(pts) < 3:
90
+ return pts
91
+
92
+ def cross(o: tuple[int, int], a: tuple[int, int], b: tuple[int, int]) -> int:
93
+ """2-D cross product of ``o->a`` and ``o->b``: >0 left turn, 0 collinear.
94
+
95
+ Integer in, integer out -- the inputs are diode/slice indices, so this
96
+ is exact and the ``<= 0`` turn test above has no tolerance to tune.
97
+ """
98
+ return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
99
+
100
+ lower: list[tuple[int, int]] = []
101
+ for p in pts:
102
+ while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
103
+ lower.pop()
104
+ lower.append(p)
105
+ upper: list[tuple[int, int]] = []
106
+ for p in reversed(pts):
107
+ while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
108
+ upper.pop()
109
+ upper.append(p)
110
+ return lower[:-1] + upper[:-1]
111
+
112
+
113
+ def _direction_angle(dx: float, dy: float) -> float:
114
+ """``atan(dy/dx)``, with the source's own ``dx==0 -> pi/2`` special case
115
+ (``CGAL_RectSize.cpp:134``) and its truncated-pi literal."""
116
+ if dx == 0:
117
+ return _TRUNCATED_PI / 2
118
+ return math.atan(dy / dx)
119
+
120
+
121
+ def min_area_rectangle(points: Any) -> Any:
122
+ """The minimum-area bounding rectangle of an integer point set, exact.
123
+
124
+ Source: stands in for ``CGAL::min_rectangle_2`` in ``CGAL_RectSize.cpp:96`` (UIOOPS v3.1.4).
125
+
126
+ Returns ``(along_dx, along_dy, along_len, perp_len)``: ``along_dx``/
127
+ ``along_dy`` is the (unnormalized) direction of the winning orientation,
128
+ ``along_len`` the extent along it, ``perp_len`` the extent perpendicular
129
+ to it -- both plain floats, the one place a square root happens.
130
+ ``None`` for an empty point set.
131
+ """
132
+ pts = [(int(p[0]), int(p[1])) for p in points]
133
+ if not pts:
134
+ return None
135
+
136
+ hull = _convex_hull(pts)
137
+
138
+ if len(hull) == 1:
139
+ return (1, 0, 0.0, 0.0)
140
+ if len(hull) == 2:
141
+ (x0, y0), (x1, y1) = hull
142
+ dx, dy = x1 - x0, y1 - y0
143
+ return (dx, dy, math.sqrt(dx * dx + dy * dy), 0.0)
144
+
145
+ n = len(hull)
146
+ best = None # (area: Fraction, dx, dy, along_len2: Fraction, perp_len2: Fraction)
147
+ for i in range(n):
148
+ x0, y0 = hull[i]
149
+ x1, y1 = hull[(i + 1) % n]
150
+ dx, dy = x1 - x0, y1 - y0
151
+ edge_len2 = dx * dx + dy * dy
152
+ if edge_len2 == 0:
153
+ continue # degenerate zero-length hull edge; cannot happen after dedup, guarded anyway
154
+
155
+ along_vals = []
156
+ perp_vals = []
157
+ for px, py in hull:
158
+ qx, qy = px - x0, py - y0
159
+ along_vals.append(qx * dx + qy * dy) # raw projection * |edge|
160
+ perp_vals.append(qx * dy - qy * dx) # raw perpendicular projection * |edge|
161
+ along_span = max(along_vals) - min(along_vals)
162
+ perp_span = max(perp_vals) - min(perp_vals)
163
+ area = Fraction(along_span * perp_span, edge_len2)
164
+
165
+ if best is None or area < best[0]:
166
+ along_len2 = Fraction(along_span * along_span, edge_len2)
167
+ perp_len2 = Fraction(perp_span * perp_span, edge_len2)
168
+ best = (area, dx, dy, along_len2, perp_len2)
169
+
170
+ assert best is not None
171
+ _, dx, dy, along_len2, perp_len2 = best
172
+ return (dx, dy, math.sqrt(along_len2), math.sqrt(perp_len2))
173
+
174
+
175
+ def cgal_rect_size(c: Any) -> tuple[float, float, float]:
176
+ """``CGAL_RectSize(c)`` -- ``(length, width, angle)``, diode units / radians.
177
+
178
+ ``length >= width`` always; ``angle`` is the direction of whichever of
179
+ the two actual rectangle edges is the longer one -- computed directly
180
+ from ``min_area_rectangle``'s own two candidate directions, so this
181
+ never needs to reproduce CGAL's internal polygon-edge numbering, only
182
+ the final ``(L, W, angle)`` relationship ``CGAL_RectSize.cpp`` itself
183
+ exposes.
184
+
185
+ **A different empty-image convention from** :func:`arrayprobe_uiops.geometry_core.cgal_min_r`:
186
+ ``CGAL_RectSize.cpp:81-89`` returns ``(0.0, 0.0, 0.0)`` for no shadowed
187
+ pixel, not NaN -- confirmed by reading both C++ sources side by side
188
+ rather than assuming the two MEX functions agree on this.
189
+ """
190
+ a = np.asarray(c)
191
+ points = _shadow_points_xy(a)
192
+ if len(points) == 0:
193
+ return 0.0, 0.0, 0.0
194
+
195
+ dx, dy, along_len, perp_len = min_area_rectangle(points)
196
+ length_along = 1.0 + along_len
197
+ length_perp = 1.0 + perp_len
198
+ if length_along > length_perp:
199
+ return length_along, length_perp, _direction_angle(dx, dy)
200
+ return length_perp, length_along, _direction_angle(-dy, dx)
@@ -0,0 +1,100 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """NCAR-recorded PMS 2DC timing/sync words, converted to the 0x55 form before framing.
3
+
4
+ **Not UIOOPS behaviour: a default-on v3.5 correction** (the package's rule for upstream
5
+ defects that destroy data: on a probe with no archived product the defect is corrected by
6
+ default, can be turned off, and is stamped in the run's configuration record).
7
+ Finding: the timing-word form was identified.
8
+
9
+
10
+ The defect. ``imgProc_sm.m:137-139`` sets the probetype-0 frame as ``boundary = [255 255 255
11
+ 255]`` followed by a slice whose first byte is ``boundarytime = 85`` (0x55), and ``:754`` frames a
12
+ particle only on that pair. RAF-format 2DC records written with NCAR's timing/sync words carry
13
+ ``[FFFFFFFF][FF tttttt][FF000000]`` between particles -- the same structure (``:786``: "end of
14
+ particle, timing word, and sync word") with marker byte 0xFF -- so ``:754`` never fires and the
15
+ run writes an empty proc file with no message.
16
+
17
+ The correction is SODA-2's own (``fix2dimage.pro``; "The sync words and timelines are different on
18
+ NCAR probes"), applied under SODA-2's own gate (``soda2_processbuffer.pro:84-87``):
19
+
20
+ - gate (``soda2_processbuffer.pro:84-87``): a record is converted only when it has fewer than
21
+ three primary 0x55 syncs (two consecutive slices with top byte 0x55), i.e. it does not already
22
+ carry the form UIOOPS frames -- detected per record, never assumed per file;
23
+ - ``fix2dimage.pro:9``: candidate sync words ``FF800000``, ``0``, ``FF000000``, ``2A000000``;
24
+ - ``:10``: fewer than five candidates, the record is unchanged;
25
+ - ``:13-15``: keep the candidates followed by a gap greater than one (drops the last; a record
26
+ with no such gap keeps them all);
27
+ - ``:17``: keep those with a blank (``FFFFFFFF``) slice two back, or an index below 2;
28
+ - ``:23-26``: the sync slice and the slice before it (the timing word) are rewritten
29
+ ``(w or FF000000) xor AA000000`` -- top byte 0x55, the lower 24 bits (the timing count)
30
+ unchanged. Subscript -1 is clipped to 0, as IDL does.
31
+
32
+ A slice here is ``imgProc_sm``'s ``data(j, 1:4)``, its first byte the first file byte -- the
33
+ ``FF000000`` byte SODA-2 reads after its big-endian swap (``soda2_read2dbuffer.pro:23,53``), so
34
+ the 32-bit word is built big-endian from the four bytes. Only byte 1 of a converted slice changes.
35
+
36
+ Off (the faithful path) is byte-identical to upstream: :func:`convert_record` is never called.
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import numpy as np
41
+
42
+ __all__ = ["STAMP_OFF", "STAMP_ON", "convert_record", "ncar_word_slices"]
43
+
44
+ STAMP_ON = "on:fix2dimage"
45
+ STAMP_OFF = "off"
46
+
47
+ _CANDIDATES = (0xFF800000, 0x00000000, 0xFF000000, 0x2A000000) # fix2dimage.pro:9
48
+ _BLANK = np.uint32(0xFFFFFFFF)
49
+ _TOP = np.uint32(0xFF000000)
50
+ _SYNC55 = np.uint32(0x55000000)
51
+
52
+
53
+ def _words(data: np.ndarray) -> np.ndarray:
54
+ """Big-endian 32-bit word per slice from ``data``'s first four byte columns."""
55
+ b = np.asarray(data[:, :4]).astype(np.uint32)
56
+ return (b[:, 0] << 24) | (b[:, 1] << 16) | (b[:, 2] << 8) | b[:, 3]
57
+
58
+
59
+ def _primary_syncs(w: np.ndarray) -> int:
60
+ """``soda2_processbuffer.pro:84``: slices k with k and k-1 both top byte 0x55."""
61
+ top55 = (w & _TOP) == _SYNC55
62
+ return int(np.count_nonzero(top55[1:] & top55[:-1]))
63
+
64
+
65
+ def ncar_word_slices(data: np.ndarray) -> np.ndarray:
66
+ """0-based indices of the NCAR sync slices (``fix2dimage.pro:20``'s ``timelines``) in
67
+ ``data``; empty when the record already carries 0x55 syncs (gate) or ``fix2dimage.pro``
68
+ finds none. :func:`convert_record` rewrites these and the slice before each."""
69
+ w = _words(data)
70
+ if w.size < 2 or _primary_syncs(w) >= 3: # processbuffer :84-87
71
+ return np.zeros(0, dtype=np.int64)
72
+ hit = np.zeros(w.shape, dtype=bool)
73
+ for c in _CANDIDATES: # :9
74
+ hit |= w == np.uint32(c)
75
+ test1 = np.flatnonzero(hit).astype(np.int64)
76
+ num = test1.size
77
+ if num < 5: # :10
78
+ return np.zeros(0, dtype=np.int64)
79
+ good = np.flatnonzero(np.diff(test1) > 1) # :13-14
80
+ if good.size > 0: # :15
81
+ test1 = test1[good]
82
+ back = w[np.maximum(test1, 2) - 2] # :17
83
+ timelines = test1[(back == _BLANK) | (test1 < 2)]
84
+ if timelines.size == 0: # :18
85
+ return np.zeros(0, dtype=np.int64)
86
+ return timelines
87
+
88
+
89
+ def convert_record(data: np.ndarray) -> tuple[np.ndarray, int]:
90
+ """``data`` with every NCAR sync/timing slice's first byte set to 0x55
91
+ (``fix2dimage.pro:23-26``: ``(w or FF000000) xor AA000000`` changes only the top byte, to
92
+ ``FF xor AA = 55``), and the number of sync words converted. The input is not modified; a
93
+ record the gate passes over is returned as the same object."""
94
+ timelines = ncar_word_slices(data)
95
+ if timelines.size == 0:
96
+ return data, 0
97
+ out = np.array(data, copy=True)
98
+ out[timelines, 0] = 0x55 # :25
99
+ out[np.maximum(timelines - 1, 0), 0] = 0x55 # :26, IDL clips -1 to 0
100
+ return out, int(timelines.size)