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,749 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Holroyd-family habit classification -- UIOOPS v3.5 (``holroyd.m``,
3
+ ``holroyd_new.m``, ``holroyd_new_HVPS.m``).
4
+
5
+ **Two schemes exist in v3.5, selected by ``iNewHabit`` at the call site**
6
+ (``imgProc_sm.m:1218-1248``): the original Holroyd (1987) tree, generalized
7
+ here to work for any probe resolution, and a second tree "modified according
8
+ as outlined in Schima et al. 2024" that comes in a 2D-S variant
9
+ (:func:`holroyd_new`) and an HVPS variant (:func:`holroyd_new_hvps`) -- two
10
+ separate MATLAB files, not one function parameterized by probe. This module
11
+ ports all three call targets.
12
+
13
+ **What changed in the original scheme (v3.1.4 -> v3.5's ``holroyd.m``),
14
+ measured by diffing the two files directly, not assumed from the docstring
15
+ claim that it is "a generalization":**
16
+
17
+ * ``probe_resolution`` changed from the v3.1.4 port's hardcoded ``0.025`` mm
18
+ to ``handles.diodesize`` -- now a required argument here
19
+ (:data:`PROBE_RESOLUTION` does not exist in this module on purpose).
20
+ * A second return value, ``F_fine_detail``, was added.
21
+ * The ``parabola_fit_center_is_in`` gate that made habit ``'C'`` unreachable
22
+ in v3.1.4 was **deleted outright** -- v3.5's ``holroyd.m`` calls
23
+ ``calc_stat`` unconditionally, with no ``else`` branch and no ``'C'``
24
+ anywhere in the function. Confirmed by reading the whole file: v3.5's
25
+ ``holroyd.m`` cannot itself emit ``'C'``.
26
+ * Three of the four length thresholds were re-expressed in physical units
27
+ with the *same* numeric threshold (``d_length < 64`` -> ``d_length *
28
+ probe_resolution < 1.6``, ``64*0.025 == 1.6``; ``d_length >= 64`` ->
29
+ ``... >= 1.6``; ``d_length >= 32`` -> ``... >= 0.8``; ``x_length <= 7.0`` ->
30
+ ``x_length * probe_resolution <= 0.175``, ``7.0*0.025 == 0.175``) -- pure
31
+ generalization, verified by arithmetic, not new science.
32
+ * **The fourth is not a pure generalization.** v3.1.4's aggregate test is
33
+ ``(d_length * probe_resolution > 6.4) or (d_length > 160.0)``; v3.5's is
34
+ ``d_length * probe_resolution > 4.0`` with the ``d_length > 160.0`` disjunct
35
+ *commented out* in the source (``holroyd.m:56``:
36
+ ``%|| (d_length > 160.0))``). The threshold moved from 6.4 to 4.0 mm and the
37
+ diode-count fallback was dropped entirely -- a real algorithmic change, not
38
+ a unit rewrite. Preserved exactly as v3.5 has it; not "fixed" back to 6.4.
39
+
40
+ Reference: Holroyd, *J. Atmos. Oceanic Technol.* **4**, 498-511 (1987);
41
+ Schima, J., McFarquhar, G. M., Delene, D., Heymsfield, A., Bansemer, A.,
42
+ Schnaiter, M., Finlon, J. A., Järvinen, E., and Nehlert, F., *A Multi-Probe
43
+ Automated Classification of Ice Crystal Habits During the IMPACTS Campaign*,
44
+ J. Geophys. Res. Atmos., **129**, e2024JD040895 (2024),
45
+ doi:10.1029/2024JD040895 (habit codes only -- this port transcribes
46
+ the MATLAB, it does not independently verify the paper's claims).
47
+
48
+ ``calc_stat`` (the 9-output helper) is **byte-identical** between v3.1.4's
49
+ ``holroyd.m`` and v3.5's ``holroyd.m`` (diffed directly: only whitespace and
50
+ one cosmetic ``&``->``&&``), so :func:`holroyd` below reuses
51
+ :func:`arrayprobe.habit.calc_stat` and :class:`arrayprobe.habit.ShapeStats`
52
+ rather than re-translating them -- the same reuse discipline
53
+ ``particle_physics.py`` used for ``single_vt`` before it moved here.
54
+
55
+ **The new scheme's ``calc_stat`` is also shared, between the two files.**
56
+ ``holroyd_new.m`` and ``holroyd_new_HVPS.m`` diff to *zero* in their
57
+ ``calc_stat`` subfunction (confirmed by direct diff) -- so
58
+ :func:`calc_stat_new` below serves both :func:`holroyd_new` and
59
+ :func:`holroyd_new_hvps`. It is a substantially different, richer
60
+ computation than the original scheme's ``calc_stat`` (TAS-ratio time-axis
61
+ scaling, front/back edge tracking for ``edge_diam_ratio``, a rotated-and-
62
+ **rounded** coordinate system feeding percentile-based width/length ratios
63
+ and a quadrant symmetry coefficient, and a max-gap statistic) -- not a
64
+ variant of the same function, a new one.
65
+
66
+ **The two decision trees over the new ``calc_stat`` differ in more than
67
+ tuning constants**, measured by diffing ``holroyd_new.m`` against
68
+ ``holroyd_new_HVPS.m`` directly:
69
+
70
+ * Tuning coefficients differ (``C_1..C_4``); the 2D-S version alone has a
71
+ fifth, ``C_5`` (plate).
72
+ * The 2D-S version identifies a column via a computed ``needed_ratio``
73
+ compared against the aspect ratio; the HVPS version instead tests
74
+ ``(a / (probe_resolution*1000) / d) < 1.6 - m_g/100 + (a_r-1)/5`` **or**
75
+ ``a_r > 5`` -- a different test, not the same formula re-tuned.
76
+ ``a`` here is the calc_stat area output already scaled to microns^2 by the
77
+ caller (``a = a * (probe_resolution*1000)^2``), matching the MATLAB
78
+ variable of the same name at this point in the function.
79
+ * The HVPS dendrite formula carries an extra ``* (1.4 - s_c)`` factor absent
80
+ from the 2D-S formula.
81
+ * **The HVPS version has no plate branch and cannot emit habit ``'h'``
82
+ (hexagonal) at all** -- confirmed by reading the whole decision tree, not
83
+ inferred from the missing ``C_5``: its dendrite branch returns ``'d'``
84
+ unconditionally where the 2D-S version splits ``'h'``/``'d'`` on
85
+ ``w_l_m_p``, and the 2D-S version's entire plate-vs-dendrite fallback block
86
+ before the final ``'i'`` is simply absent in the HVPS file.
87
+ * The tiny-particle threshold differs by probe geometry: ``d < 300`` microns
88
+ (2D-S) vs. ``d < 1000`` microns (HVPS).
89
+
90
+ **A latent arity bug found while building this module's Octave oracle,
91
+ filed as V58 in the upstream-findings list.**
92
+ Both ``holroyd_new.m`` and
93
+ ``holroyd_new_HVPS.m``'s ``n_slices == 0`` branch assigns only
94
+ ``holroyd_habit = 'M'`` and returns, leaving the other 8 declared outputs
95
+ unassigned. ``imgProc_sm.m:1225-1248`` always requests all 9 outputs, so a
96
+ zero-slice call at that call site errors in real MATLAB/Octave with
97
+ "element number 9 undefined in return list" -- measured directly, not
98
+ inferred. ``holroyd.m`` had exactly this bug once (its own
99
+ ``n_slices == 0`` branch carries the comment "need to assign a dummy value
100
+ ~ Joe Finlon 11/3/19", i.e. the fix), but the fix was not carried over when
101
+ ``holroyd_new.m``/``holroyd_new_HVPS.m`` were written. This module raises
102
+ :class:`ZeroSlicesUnassignedOutputs` in that case rather than silently
103
+ inventing values for the 8 unassigned outputs, matching MATLAB's own refusal.
104
+ """
105
+
106
+ from __future__ import annotations
107
+
108
+ import math
109
+ from dataclasses import dataclass
110
+ from typing import Any
111
+
112
+ import numpy as np
113
+
114
+ from .habit_core import ShapeStats
115
+ from .habit_core import calc_stat as _calc_stat_v314
116
+ from .particle import shadow_mask
117
+
118
+ __all__ = [
119
+ "MAX_TWOD_DATA_LENGTH",
120
+ "ShapeStatsNew",
121
+ "HolroydNewResult",
122
+ "ZeroSlicesUnassignedOutputs",
123
+ "holroyd",
124
+ "holroyd_new",
125
+ "holroyd_new_hvps",
126
+ "calc_stat_new",
127
+ ]
128
+
129
+ #: ``holroyd_new.m:214`` / ``holroyd_new_HVPS.m:175``. Same sentinel ceiling
130
+ #: as the v3.1.4/v3.5 ``holroyd.m`` calc_stat; see that module for the margin.
131
+ MAX_TWOD_DATA_LENGTH = 6000
132
+
133
+
134
+ class ZeroSlicesUnassignedOutputs(ValueError):
135
+ """Raised where real MATLAB/Octave errors: a zero-slice call to
136
+ ``holroyd_new``/``holroyd_new_HVPS`` requesting all 9 outputs.
137
+
138
+ See the module docstring's "latent arity bug" note. Not a deviation --
139
+ MATLAB itself refuses this call with "element number 9 undefined in
140
+ return list" (measured under Octave 11.3.0); this is that refusal.
141
+ """
142
+
143
+
144
+ @dataclass(frozen=True)
145
+ class ShapeStatsNew:
146
+ """The 16 outputs of the new scheme's ``calc_stat``
147
+ (``holroyd_new.m:211-674`` / ``holroyd_new_HVPS.m:172-635``, identical).
148
+
149
+ Field order follows the MATLAB return list.
150
+ """
151
+
152
+ d_length: float
153
+ w_width: float
154
+ d: float
155
+ a_angle: float
156
+ area: float
157
+ r2_correlation: float
158
+ F_fine_detail: float
159
+ O: float # noqa: E741 -- the MATLAB variable name (opacity ratio)
160
+ w_l_r_p: float
161
+ w_l_m_p: float
162
+ sym_coeff: float
163
+ cir_area_ratio: float
164
+ edge_diam_ratio: float
165
+ max_gap: float
166
+ aspect_ratio: float
167
+ p_perimeter_change: float
168
+
169
+
170
+ @dataclass(frozen=True)
171
+ class HolroydNewResult:
172
+ """The 9 outputs of ``holroyd_new``/``holroyd_new_hvps``, MATLAB order.
173
+
174
+ Source: the output list of ``holroyd_new.m:7`` (UIOOPS v3.5)."""
175
+
176
+ holroyd_habit: str
177
+ F: float
178
+ w_l_p: float
179
+ c_r: float
180
+ e_d_r: float
181
+ m_g: float
182
+ O: float # noqa: E741 -- the MATLAB variable name (opacity ratio)
183
+ a_r: float
184
+ p: float
185
+
186
+
187
+ def holroyd(image_buffer: Any, probe_resolution: Any,
188
+ bits_per_slice: Any = None) -> tuple[str, float]:
189
+ """``holroyd.m:7-89`` (v3.5) -- classify one particle. Returns
190
+ ``(holroyd_habit, F_fine_detail)``.
191
+
192
+ ``probe_resolution`` is MATLAB's ``handles.diodesize`` (mm/diode) --
193
+ required, no default: v3.5 made this probe-generic where v3.1.4 hardcoded
194
+ it, and silently picking a value would be a fidelity decision this module
195
+ does not get to make.
196
+ ``bits_per_slice`` behaves as in
197
+ the earlier translation's ``holroyd``: MATLAB's ``handles.bits_per_slice``,
198
+ defaulting to the image's own width.
199
+
200
+ Unlike v3.1.4's ``holroyd.m``, there is no
201
+ ``parabola_fit_center_is_in`` gate to reproduce -- v3.5 deleted it, so
202
+ this function's decision tree runs unconditionally, matching the source.
203
+ """
204
+ shadow = shadow_mask(image_buffer)
205
+ if shadow.ndim != 2:
206
+ shadow = np.atleast_2d(shadow)
207
+ n_slices = shadow.shape[0]
208
+
209
+ if n_slices == 0:
210
+ return "M", 0.0 # holroyd.m:34-37 -- the dummy value is in the source
211
+
212
+ if bits_per_slice is None:
213
+ bits_per_slice = shadow.shape[1]
214
+ s: ShapeStats = _calc_stat_v314(shadow, bits_per_slice)
215
+
216
+ # holroyd.m:41-87 (v3.5). Order matters, as in the v3.1.4 tree.
217
+ if s.area == 0:
218
+ return "M", s.F_fine_detail
219
+ if s.area < 25:
220
+ return "t", s.F_fine_detail
221
+ if (s.r2_correlation >= 0.4) or (
222
+ (s.d_length * probe_resolution < 1.6)
223
+ and ((s.x_length >= 4 * s.y_length) or (s.y_length >= 4 * s.x_length))
224
+ ):
225
+ if (s.a_angle > 30.0) and (s.a_angle < 60.0):
226
+ return "o", s.F_fine_detail
227
+ return "l", s.F_fine_detail
228
+ # holroyd.m:56 (v3.5) -- threshold moved to 4.0 and the `d_length > 160`
229
+ # disjunct is commented out in the source; see the module docstring.
230
+ if s.d_length * probe_resolution > 4.0:
231
+ return "a", s.F_fine_detail
232
+ if s.S_ratio >= 0.7:
233
+ return "g", s.F_fine_detail
234
+ if s.d_length * probe_resolution >= 1.6:
235
+ return ("g" if s.F_fine_detail <= 13 else "a"), s.F_fine_detail
236
+ if s.F_fine_detail < 5.5:
237
+ return "s", s.F_fine_detail
238
+ if s.F_fine_detail < 10.0:
239
+ return ("g" if s.d_length * probe_resolution >= 0.8 else "h"), s.F_fine_detail
240
+ if (s.F_fine_detail < 16.0) or (s.x_length * probe_resolution <= 0.175):
241
+ return "i", s.F_fine_detail
242
+ return "d", s.F_fine_detail
243
+
244
+
245
+ def holroyd_new(image_buffer: Any, *, probe_resolution: Any, tas_ratio: Any,
246
+ bits_per_slice: Any = None) -> HolroydNewResult:
247
+ """``holroyd_new.m:7-208`` -- the 2D-S "modified Holroyd" (Schima et al.
248
+ 2024, doi:10.1029/2024JD040895) scheme. See :func:`holroyd_new_hvps` for the HVPS
249
+ variant -- the two are separate MATLAB files with real algorithmic differences, not one
250
+ function parameterized by probe (module docstring).
251
+
252
+ Every keyword is required -- see :func:`holroyd_new_hvps`.
253
+ """
254
+ return _holroyd_new_impl(image_buffer, probe_resolution, tas_ratio,
255
+ bits_per_slice, hvps=False)
256
+
257
+
258
+ def holroyd_new_hvps(image_buffer: Any, *, probe_resolution: Any, tas_ratio: Any,
259
+ bits_per_slice: Any = None) -> HolroydNewResult:
260
+ """``holroyd_new_HVPS.m:7-169`` -- the HVPS "modified Holroyd" scheme.
261
+
262
+ Every keyword is required -- see :func:`holroyd_new`.
263
+ """
264
+ return _holroyd_new_impl(image_buffer, probe_resolution, tas_ratio,
265
+ bits_per_slice, hvps=True)
266
+
267
+
268
+ def _holroyd_new_impl(image_buffer: Any, probe_resolution: Any, tas_ratio: Any,
269
+ bits_per_slice: Any, *, hvps: bool) -> HolroydNewResult:
270
+ shadow = shadow_mask(image_buffer)
271
+ if shadow.ndim != 2:
272
+ shadow = np.atleast_2d(shadow)
273
+ n_slices = shadow.shape[0]
274
+
275
+ if n_slices == 0:
276
+ # holroyd_new.m:61-64 / holroyd_new_HVPS.m:61-63 -- see
277
+ # ZeroSlicesUnassignedOutputs's docstring: MATLAB itself errors here
278
+ # when called (as imgProc_sm.m always calls it) for all 9 outputs.
279
+ raise ZeroSlicesUnassignedOutputs(
280
+ "holroyd_new%s('M', n_slices=0): only holroyd_habit is assigned "
281
+ "in the source; the other 8 outputs are undefined, matching "
282
+ "MATLAB's own 'element number 9 undefined in return list'"
283
+ % ("_HVPS" if hvps else "")
284
+ )
285
+
286
+ if bits_per_slice is None:
287
+ bits_per_slice = shadow.shape[1]
288
+
289
+ # holroyd_new.m:65 / holroyd_new_HVPS.m:65 -- parabola_fit_center_is_in
290
+ # is still the stub that always returns 1 (unlike v3.5's `holroyd.m`,
291
+ # which deleted this gate outright). Its else-branch (unconditional
292
+ # 'C') is therefore dead by the same construction as the v3.1.4 port's
293
+ # `holroyd`, and is not reachable from this function.
294
+ s = calc_stat_new(shadow, bits_per_slice, tas_ratio)
295
+
296
+ d = s.d * probe_resolution * 1000
297
+ a = s.area * (probe_resolution * 1000) ** 2
298
+ w_l_p = s.w_l_r_p * probe_resolution * 1000
299
+ w_l_m_p = s.w_l_m_p * probe_resolution * 1000
300
+ m_g = s.max_gap * probe_resolution * 1000
301
+ p = s.p_perimeter_change * probe_resolution * 1000
302
+ F = s.F_fine_detail
303
+ O = s.O # noqa: E741 -- the MATLAB variable name (opacity ratio)
304
+ c_r = s.cir_area_ratio
305
+ e_d_r = s.edge_diam_ratio
306
+ a_r = s.aspect_ratio
307
+
308
+ def result(habit: Any) -> Any:
309
+ return HolroydNewResult(habit, F, w_l_p, c_r, e_d_r, m_g, O, a_r, p)
310
+
311
+ if a == 0:
312
+ return result("M")
313
+
314
+ t_threshold = 1000 if hvps else 300
315
+ if d < t_threshold:
316
+ return result("t")
317
+
318
+ if (m_g > (d / 3)) or (m_g >= 10 * (probe_resolution * 1000)) or (a_r > 20):
319
+ return result("o")
320
+
321
+ if e_d_r > 0.5:
322
+ return result("C")
323
+
324
+ if hvps:
325
+ # holroyd_new_HVPS.m:100-109 -- two independent linear tests, not one
326
+ # needed_ratio formula.
327
+ if (a / (probe_resolution * 1000) / d) < 1.6 - m_g / 100 + (a_r - 1) / 5:
328
+ return result("l")
329
+ if a_r > 5:
330
+ return result("l")
331
+ else:
332
+ # holroyd_new.m:107-119.
333
+ needed_ratio = (
334
+ 1
335
+ + ((w_l_p * w_l_m_p) / 40000)
336
+ + (60 / (d * (probe_resolution * 1000))) * w_l_p
337
+ + (d * 0.0005)
338
+ )
339
+ needed_ratio = min(needed_ratio, 5)
340
+ if a_r >= needed_ratio:
341
+ return result("l")
342
+
343
+ c_1, c_2, c_3, c_4 = (0.80, 0.50, 0.30, 0.35) if hvps else (1.0, 1.0, 1.0, 1.0)
344
+
345
+ sphere_f = c_1 * ((13 - (d / 250) - (abs(1 - c_r) * 7.5)) / a_r)
346
+ if d < 1000:
347
+ graupel_f = c_2 * ((25 - ((1 - O) * 15) + (d - 1000) / 30 - (abs(1 - c_r) * 15)) / a_r)
348
+ else:
349
+ graupel_f = c_2 * ((25 - ((1 - O) * 15) + (d - 1000) / 300 - (abs(1 - c_r) * 15)) / a_r)
350
+
351
+ if hvps:
352
+ s_c = s.sym_coeff
353
+ if d < 1000:
354
+ dendrite_f = c_3 * ((35 + d * d / 3e5) * a_r * (1 + (1000 - d) / 200)) * (1.4 - s_c)
355
+ else:
356
+ dendrite_f = c_3 * ((35 + d * d / 3e5) * a_r) * (1.4 - s_c)
357
+ else:
358
+ if d < 1000:
359
+ dendrite_f = c_3 * (35 + d * d / 3e5) * a_r * (1 + (1000 - d) / 200)
360
+ else:
361
+ dendrite_f = c_3 * (35 + d * d / 3e5) * a_r
362
+
363
+ if d < 1000:
364
+ aggregate_f = c_4 * (30 - (d - 1000) / 30 + s.sym_coeff * 10)
365
+ else:
366
+ aggregate_f = c_4 * (30 - (d - 1000) / 300 + s.sym_coeff * 10)
367
+
368
+ if not hvps:
369
+ plate_f = (1.0 * (50 - (((60 - w_l_m_p) / 10) * 8 / a_r)) * (2 * e_d_r + 1)
370
+ * (1 + (2500 / (d * d)) * probe_resolution))
371
+ if d > 1000:
372
+ plate_f = plate_f * (d / 1000)
373
+
374
+ if F <= sphere_f:
375
+ return result("s")
376
+ if F <= graupel_f:
377
+ return result("g")
378
+
379
+ if F > dendrite_f:
380
+ if hvps:
381
+ return result("d")
382
+ if w_l_m_p < 100 - e_d_r * 200:
383
+ return result("h")
384
+ return result("d")
385
+
386
+ if F > aggregate_f:
387
+ return result("a")
388
+
389
+ if not hvps:
390
+ if ((O < 0.3) and (d < 1000)) or (F > plate_f):
391
+ if (d > 700) and (w_l_m_p > 100):
392
+ return result("d")
393
+ return result("h")
394
+
395
+ return result("i")
396
+
397
+
398
+ def calc_stat_new(image_buffer: Any, bits_per_slice: Any, tas_ratio: Any) -> ShapeStatsNew:
399
+ """``holroyd_new.m:211-674`` / ``holroyd_new_HVPS.m:172-635``, identical
400
+ (diffed directly to zero) -- the new scheme's shape statistics.
401
+
402
+ A literal scalar transcription, matching this port's own
403
+ ``calc_stat_scalar`` in style and intent: correctness first, no
404
+ vectorized twin (a future speed-work candidate --
405
+ not
406
+ attempted here). Python's IEEE-754 float arithmetic reproduces MATLAB's
407
+ NaN propagation and NaN-comparisons-are-false semantics directly in a
408
+ scalar loop, the same reasoning the v3.1.4 habit module's ``_finish``
409
+ documents for its vectorized path; the risky divisions (by ``n_count``,
410
+ which is legitimately 0 for an all-background image reaching this
411
+ function before the caller's ``area == 0`` guard) are done in
412
+ ``numpy.float64`` under an ``errstate`` that allows ``0/0 = nan`` and
413
+ ``c/0 = inf`` rather than Python's ``ZeroDivisionError``.
414
+ """
415
+ shadow = shadow_mask(image_buffer)
416
+ n_slices = shadow.shape[0]
417
+ if n_slices <= 0:
418
+ raise ValueError("calc_stat_new requires at least one slice")
419
+ if shadow.shape[1] < bits_per_slice:
420
+ raise IndexError(
421
+ f"image has {shadow.shape[1]} diodes, fewer than bits_per_slice={bits_per_slice}"
422
+ )
423
+
424
+ min_x = float(MAX_TWOD_DATA_LENGTH * 3)
425
+ min_y = float(bits_per_slice * 3)
426
+ max_x = 0.0
427
+ max_y = 0.0
428
+ first_on_edge_x = -1.0
429
+ last_on_edge_x = -2.0
430
+ first_on_edge_y = -1
431
+ last_on_edge_y = -2
432
+ sum_x2 = sum_y2 = sum_x = sum_y = sum_xy = 0.0
433
+ p_perimeter_change = 0.0
434
+ n_count = 0
435
+ spot_on_off = 0
436
+ fully_on_count = 0
437
+ partial_on_count = 0
438
+ px: list[float] = []
439
+ py: list[float] = []
440
+
441
+ # holroyd_new.m:256-339 -- row-major scan, TAS-scaled x-axis.
442
+ for i in range(1, n_slices + 1):
443
+ fully_on_temp = 0
444
+ min_y_temp = float(bits_per_slice * 3)
445
+ max_y_temp = 0.0
446
+ for j in range(1, bits_per_slice + 1):
447
+ if shadow[i - 1, j - 1]:
448
+ tx = i / tas_ratio
449
+ ty = float(j)
450
+ max_x = max(max_x, tx)
451
+ min_x = min(min_x, tx)
452
+ max_y = max(max_y, ty)
453
+ max_y_temp = max(max_y_temp, ty)
454
+ min_y_temp = min(min_y_temp, ty)
455
+ min_y = min(min_y, ty)
456
+ sum_x2 += tx * tx
457
+ sum_y2 += ty * ty
458
+ sum_x += tx
459
+ sum_y += ty
460
+ sum_xy += tx * ty
461
+ n_count += 1
462
+ px.append(tx)
463
+ py.append(ty)
464
+ fully_on_temp += 1
465
+ if spot_on_off == 0:
466
+ spot_on_off = 1
467
+ p_perimeter_change += 1
468
+ elif j == bits_per_slice:
469
+ p_perimeter_change += 1
470
+ else:
471
+ if spot_on_off == 1:
472
+ spot_on_off = 0
473
+ p_perimeter_change += 1
474
+ if shadow[i - 1, 0]:
475
+ tx_edge = i / tas_ratio
476
+ if first_on_edge_x < 0:
477
+ first_on_edge_x = tx_edge
478
+ last_on_edge_x = tx_edge
479
+ if shadow[i - 1, bits_per_slice - 1]:
480
+ tx_edge = i / tas_ratio
481
+ if first_on_edge_x < 0:
482
+ first_on_edge_x = tx_edge
483
+ last_on_edge_x = tx_edge
484
+ if fully_on_temp != 0:
485
+ partial_on_count += 1
486
+ if fully_on_temp >= (max_y_temp - min_y_temp) * 0.8:
487
+ fully_on_count += 1
488
+ area = n_count / tas_ratio
489
+
490
+ # holroyd_new.m:344-400 -- column-major scan, TAS-scaled increments.
491
+ spot_on_off = 0
492
+ fully_on_count_b = 0
493
+ partial_on_count_b = 0
494
+ for j in range(1, bits_per_slice + 1):
495
+ fully_on_temp = 0
496
+ min_x_temp = MAX_TWOD_DATA_LENGTH * 3
497
+ max_x_temp = 0
498
+ for i in range(1, n_slices + 1):
499
+ if shadow[i - 1, j - 1]:
500
+ max_x_temp = max(max_x_temp, i)
501
+ min_x_temp = min(min_x_temp, i)
502
+ fully_on_temp += 1
503
+ if spot_on_off == 0:
504
+ spot_on_off = 1
505
+ p_perimeter_change += 1 / tas_ratio
506
+ elif i == n_slices:
507
+ p_perimeter_change += 1 / tas_ratio
508
+ else:
509
+ if spot_on_off == 1:
510
+ spot_on_off = 0
511
+ p_perimeter_change += 1 / tas_ratio
512
+ if shadow[0, j - 1]:
513
+ if first_on_edge_y < 0:
514
+ first_on_edge_y = j
515
+ last_on_edge_y = j
516
+ if fully_on_temp != 0:
517
+ partial_on_count_b += 1
518
+ if fully_on_temp >= (max_x_temp - min_x_temp) * 0.8:
519
+ fully_on_count_b += 1
520
+
521
+ # holroyd_new.m:402-412 computes x_length/y_length here and never uses
522
+ # them again -- neither in the rest of the function nor in its output
523
+ # list. A dead store in the source; not reproduced, since nothing reads
524
+ # it there either (contrast imgProc_sm.m's size_mat, a dead store the
525
+ # PORT once mistakenly gave a downstream use).
526
+
527
+ with np.errstate(divide="ignore", invalid="ignore"):
528
+ n_count_f = np.float64(n_count)
529
+ sum_x_f, sum_y_f = np.float64(sum_x), np.float64(sum_y)
530
+ sum_x2_f, sum_y2_f, sum_xy_f = np.float64(sum_x2), np.float64(sum_y2), np.float64(sum_xy)
531
+
532
+ cross_xy = sum_xy_f - (sum_x_f * sum_y_f / n_count_f)
533
+ cross_x2 = sum_x2_f - (sum_x_f * sum_x_f / n_count_f)
534
+ cross_y2 = sum_y2_f - (sum_y_f * sum_y_f / n_count_f)
535
+
536
+ slope = cross_xy / cross_x2
537
+ # holroyd_new.m:421. MATLAB's sqrt of a negative real is imaginary, not
538
+ # NaN, and `<` compares real parts. A particle confined to one slice
539
+ # has cross_x2 == 0 in exact arithmetic; with tasRatio != 1 its x
540
+ # coordinates are inexact and cross_x2 can come out a few ULP below
541
+ # zero. MATLAB then gets abs(cross_xy)/(0 + b*1i), whose real part is
542
+ # 0, so the `r2_correlation < 0.3` reset below fires; a float sqrt
543
+ # would give NaN and skip it. The real part is kept.
544
+ r2_prod = cross_x2 * cross_y2
545
+ if r2_prod < 0:
546
+ r2_correlation = 0.0
547
+ else:
548
+ r2_correlation = float(abs(cross_xy) / np.sqrt(r2_prod))
549
+
550
+ angle_radian = float(np.arctan(slope))
551
+ a_angle = angle_radian * (180.0 / math.pi)
552
+ if a_angle < 0:
553
+ a_angle += 180.0
554
+ angle_radian += math.pi
555
+ # holroyd_new.m:431-434 -- a reset absent from the old scheme's
556
+ # calc_stat (arrayprobe.habit); present here.
557
+ if r2_correlation < 0.3:
558
+ a_angle = 0.0
559
+ angle_radian = 0.0
560
+
561
+ if (angle_radian > (math.pi / 2.0)) and (angle_radian <= math.pi):
562
+ angle_radian = math.pi - angle_radian
563
+ elif angle_radian > math.pi: # pragma: no cover - see arrayprobe.habit's analog
564
+ raise ValueError(f"HEY: something is wrong here a_angle = {a_angle}")
565
+
566
+ dmin_x = float(MAX_TWOD_DATA_LENGTH * 3)
567
+ dmin_y = float(bits_per_slice)
568
+ dmax_x = 0.0
569
+ dmax_y = 0.0
570
+ new_x_vals: list[float] = []
571
+ new_y_vals: list[float] = []
572
+ cos_a, sin_a = math.cos(angle_radian), math.sin(angle_radian)
573
+ for k in range(n_count):
574
+ # holroyd_new.m:454-455 -- rounded, unlike the old scheme's
575
+ # calc_stat. round() here is MATLAB's round-half-away-from-zero;
576
+ # Python's banker's-rounding `round()` differs at exact .5, which
577
+ # a rotated real-valued coordinate essentially never lands on, so
578
+ # this is not special-cased.
579
+ new_x = _matlab_round(px[k] * cos_a + py[k] * sin_a)
580
+ new_y = _matlab_round(py[k] * cos_a - px[k] * sin_a)
581
+ new_x_vals.append(new_x)
582
+ new_y_vals.append(new_y)
583
+ if new_x > dmax_x:
584
+ dmax_x = new_x
585
+ if new_y > dmax_y:
586
+ dmax_y = new_y
587
+ if new_x < dmin_x:
588
+ dmin_x = new_x
589
+ if new_y < dmin_y:
590
+ dmin_y = new_y
591
+
592
+ d_length = dmax_x - dmin_x + 1
593
+ w_width = dmax_y - dmin_y + 1
594
+ d = max(d_length, w_width)
595
+
596
+ widths_r: list[float] = []
597
+ lengths_r: list[float] = []
598
+ max_gap_x = -32768.0
599
+ max_gap_y = -32768.0
600
+ prev_x = 32768.0
601
+ prev_y = 32768.0
602
+
603
+ x_unique = sorted(set(new_x_vals))
604
+ for curr_x in x_unique:
605
+ col_ys = [new_y_vals[i] for i in range(n_count) if new_x_vals[i] == curr_x]
606
+ if col_ys:
607
+ widths_r.append(max(col_ys) - min(col_ys) + 1)
608
+ if curr_x - prev_x > max_gap_x:
609
+ max_gap_x = curr_x - prev_x
610
+ prev_x = curr_x
611
+
612
+ y_unique = sorted(set(new_y_vals))
613
+ for curr_y in y_unique:
614
+ row_xs = [new_x_vals[i] for i in range(n_count) if new_y_vals[i] == curr_y]
615
+ if row_xs:
616
+ lengths_r.append(max(row_xs) - min(row_xs) + 1)
617
+ if curr_y - prev_y > max_gap_y:
618
+ max_gap_y = curr_y - prev_y
619
+ prev_y = curr_y
620
+
621
+ if lengths_r and widths_r:
622
+ p_low_x, p_high_x, p_higher_x = _prctile(lengths_r, (25, 75, 95))
623
+ var_x = p_high_x - p_low_x
624
+ var_higher_x = p_higher_x - p_high_x
625
+ p_low_y, p_high_y, p_higher_y = _prctile(widths_r, (25, 75, 95))
626
+ var_y = p_high_y - p_low_y
627
+ var_higher_y = p_higher_y - p_high_y
628
+
629
+ y_midpoint = dmax_y - w_width / 2
630
+ x_midpoint = dmax_x - d_length / 2
631
+ q1 = q2 = q3 = q4 = 0
632
+ for i in range(n_count):
633
+ xv, yv = new_x_vals[i], new_y_vals[i]
634
+ if yv > y_midpoint and xv > x_midpoint:
635
+ q1 += 1
636
+ if yv < y_midpoint and xv > x_midpoint:
637
+ q2 += 1
638
+ if yv > y_midpoint and xv < x_midpoint:
639
+ q3 += 1
640
+ if yv < y_midpoint and xv < x_midpoint:
641
+ q4 += 1
642
+ if (q1 == 0 and q4 == 0) or (q2 == 0 and q3 == 0):
643
+ sym_coeff = 0.0
644
+ else:
645
+ sym_1 = min(q1, q4) / max(q1, q4)
646
+ sym_2 = min(q2, q3) / max(q2, q3)
647
+ sym_coeff = sym_1 * sym_2
648
+ else:
649
+ var_x = var_higher_x = var_y = var_higher_y = sym_coeff = 0.0
650
+
651
+ max_gap = max(max_gap_x, max_gap_y) - 1
652
+ if max_gap < 0:
653
+ max_gap = 32768.0
654
+
655
+ edge_length_y = last_on_edge_y - first_on_edge_y + 1
656
+ edge_length_x = last_on_edge_x - first_on_edge_x + 1
657
+ # holroyd_new.m:643-647. `d` can be 0 for a degenerate image (the
658
+ # scan finds nothing), and division there is MATLAB's IEEE 0/0=NaN /
659
+ # c/0=inf, not Python's ZeroDivisionError -- do the risky divisions
660
+ # in numpy float64, matching arrayprobe.habit's `_finish`.
661
+ d_np = np.float64(d)
662
+ area_np = np.float64(area)
663
+ d_length_np, w_width_np = np.float64(d_length), np.float64(w_width)
664
+ edge_diam_ratio = float(np.float64(edge_length_x) / d_np)
665
+ if edge_length_y > 64:
666
+ edge_diam_ratio = 1.0
667
+
668
+ w_l_r_p = min(var_x, var_y)
669
+ w_l_m_p = min(var_higher_x, var_higher_y)
670
+
671
+ cir_area_ratio = float(area_np / (math.pi * (d_np / 2) ** 2))
672
+
673
+ aspect_ratio = (1.0 if area < 1.5
674
+ else float(max(d_length_np / w_width_np, w_width_np / d_length_np)))
675
+
676
+ f_fine_detail = float(np.float64(p_perimeter_change) * d_np / area_np)
677
+ O = ( # noqa: E741 -- the MATLAB variable name (opacity ratio)
678
+ ((fully_on_count / partial_on_count) + (fully_on_count_b / partial_on_count_b)) / 2
679
+ if (partial_on_count != 0 and partial_on_count_b != 0) else 0.0
680
+ )
681
+
682
+ return ShapeStatsNew(
683
+ d_length=float(d_length),
684
+ w_width=float(w_width),
685
+ d=float(d),
686
+ a_angle=float(a_angle),
687
+ area=float(area),
688
+ r2_correlation=float(r2_correlation),
689
+ F_fine_detail=float(f_fine_detail),
690
+ O=float(O),
691
+ w_l_r_p=float(w_l_r_p),
692
+ w_l_m_p=float(w_l_m_p),
693
+ sym_coeff=float(sym_coeff),
694
+ cir_area_ratio=float(cir_area_ratio),
695
+ edge_diam_ratio=float(edge_diam_ratio),
696
+ max_gap=float(max_gap),
697
+ aspect_ratio=float(aspect_ratio),
698
+ p_perimeter_change=float(p_perimeter_change),
699
+ )
700
+
701
+
702
+ def _matlab_round(x: float) -> float:
703
+ """MATLAB/Octave ``round``: half away from zero, unlike Python's banker's
704
+ rounding; NaN round-trips as NaN rather than raising, as MATLAB's does.
705
+ ``holroyd_new.m:454-455``. A NaN here means the point's rotation angle
706
+ was itself NaN (a single-slice or single-diode particle, see the
707
+ ``slope`` comment above) -- the same degenerate case
708
+ ``arrayprobe.habit``'s ``_finish`` documents for the old scheme.
709
+
710
+ ``floor(x + 0.5)`` is not this function: the addition itself rounds, so
711
+ ``0.49999999999999994`` and every odd integer above 2^52 come out one too
712
+ high. ``x - floor(x)`` is exact for every finite double, so the half is
713
+ tested on that instead (Octave golden: ``tests/data/v35_r10_particle_golden.json``).
714
+ """
715
+ if not math.isfinite(x):
716
+ return x
717
+ if x >= 0:
718
+ f = math.floor(x)
719
+ return f + 1 if x - f >= 0.5 else f
720
+ c = math.ceil(x)
721
+ return c - 1 if c - x >= 0.5 else c
722
+
723
+
724
+ def _prctile(data: Any, percentiles: Any) -> Any:
725
+ """MATLAB/Octave ``prctile`` (linear interpolation between the empirical
726
+ CDF's ``(i-0.5)/n`` plotting positions; extrapolates to min/max outside
727
+ that range) -- ``holroyd_new.m:563-573`` calls it with a plain vector and
728
+ no method argument, which is this variant.
729
+
730
+ No existing port of ``prctile`` was found in ``arrayprobe`` to reuse
731
+ (checked before writing this).
732
+ """
733
+ xs = sorted(data)
734
+ n = len(xs)
735
+ out = []
736
+ for p in percentiles:
737
+ if n == 1:
738
+ out.append(float(xs[0]))
739
+ continue
740
+ pos = (p / 100.0) * n - 0.5 # 0-based position on the plotting-position scale
741
+ if pos <= 0:
742
+ out.append(float(xs[0]))
743
+ elif pos >= n - 1:
744
+ out.append(float(xs[-1]))
745
+ else:
746
+ lo = int(math.floor(pos))
747
+ frac = pos - lo
748
+ out.append(float(xs[lo] + frac * (xs[lo + 1] - xs[lo])))
749
+ return out