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,124 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Build one aircraft TAS sidecar from another probe's housekeeping on the same aircraft.
3
+
4
+ **Why (author, 2026-09-22).** The UND CIP's own NASA-Ames airspeed file declares
5
+ m/s and is almost certainly knots, and converting it leaves a **5.8 %** residual
6
+ against the 2D-S's own series (ratio 1.833 measured over 23,914 shared in-flight
7
+ seconds, against the exact 1.9438). The author's instruction was not to lean on
8
+ that conversion but to *derive the airspeed from the 2D-S*: both instruments fly
9
+ on the same aircraft, so its true airspeed is one physical quantity, and the
10
+ 2D-S housekeeping already records it **in m/s, in the pipeline's own sidecar
11
+ form**. Using it for the CIP removes the units question from the comparison
12
+ instead of carrying it — and it makes both instruments share one airspeed, which
13
+ is what a like-for-like comparison requires anyway.
14
+
15
+ **What this does, and nothing more.** Reads one or more ``<stem>.tas.csv`` files
16
+ written by the SPEC stage 2, puts every sample on a whole second, takes the
17
+ **median** of the samples landing in each second, and writes a single 1 Hz
18
+ sidecar covering the union. The median rather than the mean because SPEC
19
+ housekeeping carries occasional wild values; a single bad packet must not move
20
+ the second it lands in.
21
+
22
+ **It computes no science.** Seconds-to-HHMMSS packing and a per-second median.
23
+ The output is the same nine-column shape every other TAS producer here writes,
24
+ via :func:`arrayprobe.tools.make_tas_file.write_tas_csv`, so the pipeline cannot
25
+ tell which producer made it — except from the ``.call`` stamp, which is why the
26
+ caller must record the source.
27
+
28
+ Usage, from the repository root::
29
+
30
+ python -m arrayprobe.driver.tas_from_probe_housekeeping \\
31
+ ../_decoded/base160906*.tas.csv \\
32
+ --out ../_decoded/cip160906/driver_v35_0921/2016_09_06_07_59_50.tas.csv
33
+
34
+ **The uncertainty this does NOT remove.** The 5.8 % spread between the two
35
+ airspeed series is a real disagreement between two measurements on one platform.
36
+ Choosing the 2D-S series makes the CIP and 2D-S self-consistent; it does not
37
+ make either one right in absolute terms. Any CIP-versus-2D-S figure carries
38
+ that as an uncertainty band, and this module prints the number so the
39
+ caller cannot claim not to know it.
40
+ """
41
+ from __future__ import annotations
42
+
43
+ import argparse
44
+ from pathlib import Path
45
+
46
+ import numpy as np
47
+
48
+ from arrayprobe.tools.make_tas_file import write_tas_csv # noqa: E402
49
+
50
+ #: Below this the aircraft is not flying; those seconds are kept in the series (stage 4 needs a
51
+ #: continuous axis) but excluded from the summary statistics this prints.
52
+ IN_FLIGHT_MPS = 20.0
53
+
54
+
55
+ def hhmmss_to_seconds(hhmmss: np.ndarray) -> np.ndarray:
56
+ """HHMMSS (possibly fractional, possibly hour >= 24) to seconds from midnight."""
57
+ h = np.asarray(hhmmss, dtype=np.float64)
58
+ hh = np.floor(h / 10000.0)
59
+ mm = np.floor((h - hh * 10000.0) / 100.0)
60
+ ss = h - hh * 10000.0 - mm * 100.0
61
+ return hh * 3600.0 + mm * 60.0 + np.floor(ss)
62
+
63
+
64
+ def merge(paths: list[Path]) -> tuple[np.ndarray, np.ndarray, int]:
65
+ """Whole seconds and the median TAS in each, over every input file."""
66
+ sod_all: list[np.ndarray] = []
67
+ tas_all: list[np.ndarray] = []
68
+ n_raw = 0
69
+ for p in paths:
70
+ table = np.loadtxt(p, delimiter=",", usecols=(0, 1), ndmin=2)
71
+ if table.size == 0:
72
+ continue
73
+ n_raw += table.shape[0]
74
+ sod_all.append(hhmmss_to_seconds(table[:, 0]))
75
+ tas_all.append(table[:, 1].astype(np.float64))
76
+ if not sod_all:
77
+ raise SystemExit("no rows read from any input")
78
+ sod = np.concatenate(sod_all)
79
+ tas = np.concatenate(tas_all)
80
+ finite = np.isfinite(sod) & np.isfinite(tas)
81
+ sod, tas = sod[finite], tas[finite]
82
+ order = np.argsort(sod, kind="stable")
83
+ sod, tas = sod[order], tas[order]
84
+ seconds, start = np.unique(sod, return_index=True)
85
+ bounds = list(start[1:]) + [tas.size]
86
+ medians = np.array([np.median(tas[a:b]) for a, b in zip(start, bounds, strict=True)])
87
+ # strict=True: `bounds` is built from `start` and must be the same length by
88
+ # construction, so a mismatch is a bug here rather than ragged input to tolerate.
89
+ return seconds, medians, n_raw
90
+
91
+
92
+ def main(argv=None) -> int:
93
+ """Command line: merge the named .tas.csv files into one whole-second TAS sidecar at --out."""
94
+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
95
+ ap.add_argument("inputs", nargs="+", help="one or more <stem>.tas.csv files")
96
+ ap.add_argument("--out", required=True, help="the .tas.csv to write")
97
+ args = ap.parse_args(argv)
98
+
99
+ paths = [Path(p) for p in args.inputs]
100
+ missing = [p for p in paths if not p.is_file()]
101
+ if missing:
102
+ raise SystemExit(f"not found: {', '.join(str(p) for p in missing)}")
103
+
104
+ seconds, tas, n_raw = merge(paths)
105
+ flying = tas >= IN_FLIGHT_MPS
106
+ rows = write_tas_csv(args.out, _hhmmss(seconds), tas, seconds_of_day=seconds)
107
+
108
+ print(f"wrote {args.out} -- {rows} whole-second rows from {n_raw} housekeeping samples "
109
+ f"across {len(paths)} file(s)")
110
+ if flying.any():
111
+ print(f"in-flight seconds {int(flying.sum())}: TAS median {np.median(tas[flying]):.2f}, "
112
+ f"range {tas[flying].min():.2f}..{tas[flying].max():.2f} m/s")
113
+ print("source: the SPEC probe's own housekeeping on the SAME aircraft, already in m/s -- "
114
+ "used so both instruments share one airspeed. Record it in the run's .call stamp.")
115
+ return 0
116
+
117
+
118
+ def _hhmmss(seconds_of_day: np.ndarray) -> np.ndarray:
119
+ s = np.asarray(seconds_of_day, dtype=np.int64)
120
+ return ((s // 3600) * 10000 + ((s % 3600) // 60) * 100 + (s % 60)).astype(np.float64)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ raise SystemExit(main())
arrayprobe/dropsize.py ADDED
@@ -0,0 +1,519 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Drop sizing by chord lookup -- a port of ``dropsize.m`` (243 lines).
3
+
4
+ ``imgProc_sm.m:833-835`` (stock) / ``:416-418`` (ORACLES variant) calls this once
5
+ per particle and writes all seven returns to the per-particle file:
6
+ ``center_in``, ``axis_ratio``, ``diam_circle_fit``, ``diam_horiz_chord``,
7
+ ``diam_vert_chord``, ``diam_horiz_mean``, ``diam_spheroid``.
8
+
9
+ The method: measure a chord across the shadow, then read the diameter of the
10
+ equivalent-volume **sphere** off a table computed from the equilibrium shape of a
11
+ falling raindrop of that chord. The circle-fit branch is Heymsfield & Parrish
12
+ (1978) for images that touch an array edge, where the true width is unknown and
13
+ a circle is fitted through the two edge chords.
14
+
15
+ **Stock v3.1.4 and the ORACLES variant ship byte-identical copies of this file**
16
+ (verified 2026-08-20 by md5), so nothing here takes a
17
+ :class:`~arrayprobe.profiles.FidelityProfile`. Both callers also pass
18
+ ``corrected_horizontal_diode_size = diode_size = handles.diodesize``
19
+ (``imgProc_sm.m:826-827`` / ``:409-410``), which matters more than it looks --
20
+ see "Latent defects" below.
21
+
22
+ Phase neutrality (binding directive, 2026-08-19)
23
+ -----------------------------------------------------------
24
+
25
+ This module is the one the directive names explicitly. The tables answer *"what
26
+ raindrop would have cast this shadow"*, which is not a question an ice crystal
27
+ has an answer to, so :mod:`arrayprobe.sizing` registers it as ``phase="liquid"``
28
+ and bars it from the universal sizing path. MATLAB has no such guard: it calls
29
+ ``dropsize`` on every particle, in every cloud, and writes the result.
30
+
31
+ Preserved defects, each with a test
32
+ -----------------------------------
33
+
34
+ * ``dropsize.m:198-201, 219-222`` -- **the table lookup extrapolates forward
35
+ using the previous segment's slope.** ``i = round(chord * 10)`` is one less
36
+ than the index of the entry *for* that chord, because ``chords(1)`` is 0.0.
37
+ The code then evaluates ``D(i) + slope[i, i+1] * (chord - chords(i))`` where
38
+ ``chord - chords(i)`` runs up to 0.15. At a grid point this is exact. Above
39
+ one it extrapolates with the slope of the segment *below*, so the sign of the
40
+ error follows each table's curvature: the horizontal table is nearly straight
41
+ and its error stays under 0.4 um (0.03%), while the vertical table is strongly
42
+ convex at the top and reads **low** by up to 23 um (0.29%). The function is
43
+ also discontinuous at half-grid chords, by the same 23 um. See
44
+ :func:`_chord_to_spherical_dia`.
45
+ * ``dropsize.m:199, 220`` -- the bound is ``i + 1 < max_chords`` where
46
+ ``<=`` would still be in range, so **the last entry of each table is
47
+ unreachable**: 8.9998 mm horizontal and 8.9230 mm vertical are never returned.
48
+ The oversize sentinel 9.1 takes over at chord 11.55 / 5.35 instead of 11.65 /
49
+ 5.45.
50
+ * ``dropsize.m:56, 180`` -- ``diodes_added_to_length`` is ``0``, so the "one
51
+ diode added for the missing first slice" that the header comment at ``:10``
52
+ and ``:15`` documents **never happens**. Only the vertical branch at ``:172``
53
+ adds anything, and it adds ``diodes_added_to_height * 0.5`` = 0.5, not 1.
54
+ * ``dropsize.m:143`` -- the ``elseif`` branch taken when the smallest edge
55
+ touching is positive is **dead when
56
+ called from imgProc_sm**, which passes ``largest = max(top, bottom)`` and
57
+ ``smallest = min(top, bottom)``: a positive minimum forces a positive maximum,
58
+ so the ``elseif`` cannot be reached. Kept, because the function is public.
59
+ * ``dropsize.m:220-222`` -- a **negative chord indexes the tables negatively**
60
+ and MATLAB dies. Preserved as :class:`~arrayprobe.matlab_compat.MatlabIndexError`
61
+ rather than clamped; see :func:`_chord_to_spherical_dia`.
62
+
63
+ Latent defects -- masked by the caller, reproduced anyway
64
+ ----------------------------------------------------------
65
+
66
+ Two defects are invisible in every UIOOPS run ever made, because both call sites
67
+ pass ``corrected_horizontal_diode_size == diode_size``, making
68
+ ``scaling_factor_for_horizontal_lengths`` exactly 1.0. They are transcribed
69
+ faithfully so that the day someone passes a real correction -- which is what the
70
+ argument is *for* -- the port and the MATLAB agree on being wrong together:
71
+
72
+ * ``dropsize.m:131, 167, 177`` -- **the correction is applied twice.**
73
+ ``max_horizontal_length`` is scaled by ``corr / ds`` at ``:131``, then
74
+ multiplied by ``corr`` again at ``:167`` and ``:177``, giving a chord of
75
+ ``L * corr**2 / ds`` where ``L * corr`` was meant. Measured in Octave: with
76
+ ``L = 3``, ``ds = 0.010``, ``corr = 0.020`` the chord is 0.12, not 0.06.
77
+ * ``dropsize.m:131, 150`` -- **the centre-in test compares a scaled length with
78
+ an unscaled one.** ``:150`` tests the already-scaled ``max_horizontal_length``
79
+ against the raw ``largest_edge_touching``, not against
80
+ ``largest_edge_touching_length``. Measured in Octave: ``L = 10``,
81
+ ``edge = 12``, ``ds = 0.010`` gives ``center_in = 0`` at ``corr = 0.010`` and
82
+ ``center_in = 1`` at ``corr = 0.020``, on identical geometry.
83
+
84
+ Validation
85
+ ----------
86
+
87
+ Bit-exact against GNU Octave running the unmodified ``dropsize.m``
88
+ (``octave_oracle/run_s1c_oracle.m``, golden fixture
89
+ ``tests/data/s1c_octave_golden.csv``).
90
+ """
91
+
92
+ from __future__ import annotations
93
+
94
+ import math
95
+ from dataclasses import dataclass
96
+
97
+ import numpy as np
98
+
99
+ from .matlab_compat import MatlabIndexError, mdiv, mround, to0
100
+ from .sizing import SizeDefinition, register_size_definition
101
+
102
+ __all__ = [
103
+ "MAX_HORIZONTAL_CHORDS",
104
+ "MAX_VERTICAL_CHORDS",
105
+ "HORIZONTAL_CHORDS",
106
+ "HORIZONTAL_CHORD_ESD",
107
+ "VERTICAL_CHORDS",
108
+ "VERTICAL_CHORD_ESD",
109
+ "DIODES_ADDED_TO_LENGTH",
110
+ "DIODES_ADDED_TO_HEIGHT",
111
+ "OVERSIZE",
112
+ "DropSize",
113
+ "dropsize",
114
+ "horizontal_chord_to_spherical_dia",
115
+ "vertical_chord_to_spherical_dia",
116
+ ]
117
+
118
+
119
+ # --------------------------------------------------------------------------
120
+ # Lookup tables -- dropsize.m:53-100
121
+ # --------------------------------------------------------------------------
122
+
123
+ #: ``dropsize.m:53-54``. Both equal the length of their table, which is what
124
+ #: makes the ``i + 1 < max`` bound at ``:199,220`` drop the final entry.
125
+ MAX_HORIZONTAL_CHORDS = 117
126
+ MAX_VERTICAL_CHORDS = 55
127
+
128
+ #: ``dropsize.m:56-57``. ``diodes_added_to_length`` is zero, so the "+1 diode
129
+ #: for the missing first slice" in the header comment never happens.
130
+ DIODES_ADDED_TO_LENGTH = 0.0
131
+ DIODES_ADDED_TO_HEIGHT = 1.0
132
+
133
+ #: ``dropsize.m:11`` -- "uncalculated size appears as zero; oversize as 9.1".
134
+ OVERSIZE = 9.1
135
+
136
+ #: ``dropsize.m:59-71``. Chord in mm, 0.0 to 11.6 in steps of 0.1.
137
+ HORIZONTAL_CHORDS = np.array(
138
+ [round(0.1 * k, 10) for k in range(MAX_HORIZONTAL_CHORDS)], dtype=np.float64
139
+ )
140
+
141
+ #: ``dropsize.m:73-85``. Equivalent-spherical diameter, mm, for the chord at
142
+ #: the same position in :data:`HORIZONTAL_CHORDS`.
143
+ HORIZONTAL_CHORD_ESD = np.array([
144
+ 0.0000, 0.1000, 0.2000, 0.3000, 0.3998, 0.4996, 0.5992, 0.6986, 0.7976, 0.8964,
145
+ 0.9947, 1.0927, 1.1903, 1.2875, 1.3842, 1.4804, 1.5761, 1.6711, 1.7657, 1.8597,
146
+ 1.9531, 2.0460, 2.1385, 2.2304, 2.3217, 2.4124, 2.5026, 2.5921, 2.6812, 2.7696,
147
+ 2.8574, 2.9448, 3.0319, 3.1185, 3.2046, 3.2903, 3.3755, 3.4603, 3.5446, 3.6286,
148
+ 3.7120, 3.7950, 3.8776, 3.9598, 4.0416, 4.1229, 4.2036, 4.2841, 4.3642, 4.4440,
149
+ 4.5233, 4.6024, 4.6811, 4.7597, 4.8378, 4.9152, 4.9924, 5.0690, 5.1452, 5.2210,
150
+ 5.2961, 5.3711, 5.4457, 5.5201, 5.5942, 5.6681, 5.7416, 5.8148, 5.8877, 5.9602,
151
+ 6.0323, 6.1041, 6.1756, 6.2467, 6.3175, 6.3879, 6.4580, 6.5278, 6.5973, 6.6664,
152
+ 6.7353, 6.8040, 6.8720, 6.9399, 7.0075, 7.0744, 7.1411, 7.2074, 7.2733, 7.3388,
153
+ 7.4040, 7.4688, 7.5332, 7.5973, 7.6610, 7.7241, 7.7864, 7.8490, 7.9117, 7.9739,
154
+ 8.0359, 8.0976, 8.1591, 8.2203, 8.2813, 8.3421, 8.4027, 8.4631, 8.5233, 8.5834,
155
+ 8.6433, 8.7030, 8.7625, 8.8220, 8.8814, 8.9407, 8.9998,
156
+ ], dtype=np.float64)
157
+
158
+ #: ``dropsize.m:87-93``. Chord in mm, 0.0 to 5.4 in steps of 0.1.
159
+ VERTICAL_CHORDS = np.array(
160
+ [round(0.1 * k, 10) for k in range(MAX_VERTICAL_CHORDS)], dtype=np.float64
161
+ )
162
+
163
+ #: ``dropsize.m:94-100``. The vertical table rises much faster than the
164
+ #: horizontal one at the top end: a large drop is flattened, so a given vertical
165
+ #: chord implies a bigger sphere than the same horizontal chord does.
166
+ VERTICAL_CHORD_ESD = np.array([
167
+ 0.0000, 0.1000, 0.2000, 0.3001, 0.4003, 0.5008, 0.6016, 0.7028, 0.8048, 0.9075,
168
+ 1.0110, 1.1155, 1.2208, 1.3271, 1.4348, 1.5438, 1.6545, 1.7668, 1.8809, 1.9967,
169
+ 2.1142, 2.2336, 2.3553, 2.4792, 2.6059, 2.7353, 2.8677, 3.0023, 3.1394, 3.2792,
170
+ 3.4219, 3.5678, 3.7169, 3.8695, 4.0259, 4.1865, 4.3512, 4.5201, 4.6922, 4.8687,
171
+ 5.0525, 5.2438, 5.4432, 5.6474, 5.8580, 6.0775, 6.3073, 6.5485, 6.8018, 7.0729,
172
+ 7.3699, 7.7007, 8.0781, 8.4868, 8.9230,
173
+ ], dtype=np.float64)
174
+
175
+
176
+ # --------------------------------------------------------------------------
177
+ # The chord -> diameter lookup -- dropsize.m:192-229
178
+ # --------------------------------------------------------------------------
179
+
180
+ def _chord_to_spherical_dia(chord, chords, diameters, max_chords, table_name):
181
+ """``dropsize.m:192-209`` and ``:212-229``, which are the same code twice.
182
+
183
+ The two subfunctions differ only in which pair of tables they close over and
184
+ in ``max_vertical_chords`` vs ``max_horizontal_chords``, so they are one
185
+ implementation here with two thin wrappers below for provenance.
186
+
187
+ Transcribed literally, including the index arithmetic that makes it
188
+ extrapolate rather than interpolate::
189
+
190
+ i = round(chord * 10) % :198, :219
191
+ if i + 1 < max_chords & i ~= 0 % :199, :220
192
+ delta = D(i+1) - D(i) % :200, :221
193
+ diameter = D(i) + (delta / 0.1) * (chord - X(i)) % :201, :222
194
+
195
+ ``X(i)`` is ``(i - 1) * 0.1``, one grid step *below* the chord ``i`` was
196
+ derived from, so ``chord - X(i)`` is about 0.1 rather than about 0. At an
197
+ exact grid point the two errors cancel and the result is the table value.
198
+ Off one, the slope comes from the segment below the chord instead of the
199
+ segment containing it.
200
+
201
+ A negative chord makes ``i`` negative, the guard still passes, and MATLAB
202
+ dies indexing ``D(i+1)``. Reproduced -- ``D(i+1)`` is evaluated first at
203
+ ``:200``/``:221``, so that is the index the error names.
204
+ """
205
+ delta_chord = 0.1 # :196, :217
206
+
207
+ i = int(mround(chord * 10)) # :198, :219
208
+
209
+ if i + 1 < max_chords and i != 0: # :199, :220
210
+ if i + 1 < 1:
211
+ raise MatlabIndexError(
212
+ f"{table_name}({i + 1}): MATLAB subscripts must be positive "
213
+ f"integers (dropsize.m indexes with round(chord * 10) and never "
214
+ f"checks the sign; chord = {chord!r})"
215
+ )
216
+ if i < 1:
217
+ raise MatlabIndexError(
218
+ f"{table_name}({i}): MATLAB subscripts must be positive integers "
219
+ f"(chord = {chord!r})"
220
+ )
221
+ delta_diameter = diameters[to0(i + 1)] - diameters[to0(i)]
222
+ diameter = diameters[to0(i)] + (delta_diameter / delta_chord) * (
223
+ chord - chords[to0(i)]
224
+ )
225
+ elif i == 0: # :202, :223
226
+ diameter = 0.0
227
+ else: # :205, :226
228
+ diameter = OVERSIZE
229
+
230
+ return float(diameter)
231
+
232
+
233
+ def vertical_chord_to_spherical_dia(vertical_chord):
234
+ """``dropsize.m:192-209``. See :func:`_chord_to_spherical_dia`."""
235
+ return _chord_to_spherical_dia(
236
+ vertical_chord,
237
+ VERTICAL_CHORDS,
238
+ VERTICAL_CHORD_ESD,
239
+ MAX_VERTICAL_CHORDS,
240
+ "vertical_chord_equivalent_spherical_diameters",
241
+ )
242
+
243
+
244
+ def horizontal_chord_to_spherical_dia(horizontal_chord):
245
+ """``dropsize.m:212-229``. See :func:`_chord_to_spherical_dia`."""
246
+ return _chord_to_spherical_dia(
247
+ horizontal_chord,
248
+ HORIZONTAL_CHORDS,
249
+ HORIZONTAL_CHORD_ESD,
250
+ MAX_HORIZONTAL_CHORDS,
251
+ "horizontal_chord_equivalent_spherical_diameters",
252
+ )
253
+
254
+
255
+ # --------------------------------------------------------------------------
256
+ # dropsize -- dropsize.m:1-187
257
+ # --------------------------------------------------------------------------
258
+
259
+ @dataclass(frozen=True)
260
+ class DropSize:
261
+ """The seven returns of ``dropsize.m:1``, in MATLAB's order.
262
+
263
+ Which of them are set depends entirely on how many array edges the image
264
+ touches -- an image that touches an edge has an unknown true width, so the
265
+ chords that need one are left at their ``:103-108`` initialisers. Measured
266
+ under Octave, with ``.`` for "left at zero":
267
+
268
+ ==================== ====== ========== ======== ======= ========== ========
269
+ branch axis_r circle_fit horiz_ch vert_ch horiz_mean spheroid
270
+ ==================== ====== ========== ======== ======= ========== ========
271
+ ``image_area < 1`` 1.0 . . . . .
272
+ 2 edges, centre in . set set . . .
273
+ 2 edges, centre out . set . . . .
274
+ 1 edge, centre in . set set . . .
275
+ 1 edge, centre out . set . . . .
276
+ 0 edges set set set set set set
277
+ ==================== ====== ========== ======== ======= ========== ========
278
+
279
+ So ``axis_ratio`` is zero for every particle that touches an edge, and 1.0
280
+ -- not zero -- for a particle too small to size. Downstream code that reads
281
+ it as a shape statistic is reading a branch indicator most of the time.
282
+ """
283
+
284
+ center_in: int
285
+ axis_ratio: float
286
+ diameter_circle_fit: float
287
+ diameter_horiz_chord: float
288
+ diameter_vert_chord: float
289
+ diameter_horiz_mean: float
290
+ diameter_spheroid: float
291
+
292
+ def __iter__(self):
293
+ """Unpack in MATLAB's return order, so a call site reads like ``:833``."""
294
+ return iter((
295
+ self.center_in,
296
+ self.axis_ratio,
297
+ self.diameter_circle_fit,
298
+ self.diameter_horiz_chord,
299
+ self.diameter_vert_chord,
300
+ self.diameter_horiz_mean,
301
+ self.diameter_spheroid,
302
+ ))
303
+
304
+
305
+ def dropsize(
306
+ max_horizontal_length,
307
+ max_vertical_length,
308
+ image_area,
309
+ largest_edge_touching,
310
+ smallest_edge_touching,
311
+ diode_size,
312
+ corrected_horizontal_diode_size,
313
+ number_diodes_in_array,
314
+ ):
315
+ """``dropsize.m:1-187``. Equivalent-volume-sphere sizing for liquid drops.
316
+
317
+ Parameters mirror MATLAB's argument order exactly. All are doubles at the
318
+ call site -- they come from ``calculate_reject_unified``'s returns, which are
319
+ counts and sums over a char matrix -- so none of the int16 traps that bite
320
+ ``sizeDist.m:882-890`` apply here.
321
+
322
+ Parameters
323
+ ----------
324
+ max_horizontal_length:
325
+ ``images.image_length`` -- slices spanned, i.e. along-flight extent.
326
+ max_vertical_length:
327
+ ``images.longest_y_within_a_slice`` -- the longest run of shadowed
328
+ diodes inside any one slice.
329
+ image_area:
330
+ Shadowed pixel count. Below 1 the function returns early.
331
+ largest_edge_touching, smallest_edge_touching:
332
+ ``max`` and ``min`` of the top- and bottom-edge contact lengths
333
+ (``imgProc_sm.m:828-829``). The ordering is what makes ``:143`` dead.
334
+ diode_size, corrected_horizontal_diode_size:
335
+ Both ``handles.diodesize`` at both call sites, so their ratio is 1.0 in
336
+ every real run. See "Latent defects" in the module docstring for what
337
+ happens when it is not.
338
+ number_diodes_in_array:
339
+ ``diodenum``. Used only by the two-edge circle fit.
340
+
341
+ Returns
342
+ -------
343
+ DropSize
344
+ Unpackable in MATLAB's return order.
345
+ """
346
+ # :103-109 -- the initialisers that survive on every branch that does not
347
+ # overwrite them. This is why the table in DropSize has so many blanks.
348
+ diameter_circle_fit = 0.0
349
+ diameter_horiz_chord = 0.0
350
+ diameter_vert_chord = 0.0
351
+ diameter_horiz_mean = 0.0
352
+ diameter_spheroid = 0.0
353
+ axis_ratio = 0.0
354
+ center_in = 0
355
+
356
+ # :111
357
+ scaling_factor_for_horizontal_lengths = (
358
+ corrected_horizontal_diode_size / diode_size
359
+ )
360
+
361
+ corrected_diodes_added_to_length = 0 # :114
362
+
363
+ # :116-125. Note the early return uses the :114 initialiser, never the
364
+ # scaled value assigned at :132 -- so every diameter comes back 0.0 even
365
+ # when the scaling factor is not 1.
366
+ if image_area < 1:
367
+ diameter_circle_fit = corrected_diodes_added_to_length
368
+ diameter_horiz_chord = corrected_diodes_added_to_length
369
+ diameter_vert_chord = corrected_diodes_added_to_length
370
+ diameter_horiz_mean = corrected_diodes_added_to_length
371
+ diameter_spheroid = corrected_diodes_added_to_length
372
+ center_in = 0
373
+ axis_ratio = 1.0
374
+ return DropSize(
375
+ center_in,
376
+ axis_ratio,
377
+ float(diameter_circle_fit),
378
+ float(diameter_horiz_chord),
379
+ float(diameter_vert_chord),
380
+ float(diameter_horiz_mean),
381
+ float(diameter_spheroid),
382
+ )
383
+
384
+ # :129-132. max_horizontal_length is rebound to its scaled self here, which
385
+ # is what the :150 comparison below then gets wrong.
386
+ largest_edge_touching_length = (
387
+ largest_edge_touching * scaling_factor_for_horizontal_lengths
388
+ )
389
+ smallest_edge_touching_length = (
390
+ smallest_edge_touching * scaling_factor_for_horizontal_lengths
391
+ )
392
+ max_horizontal_length = (
393
+ max_horizontal_length * scaling_factor_for_horizontal_lengths
394
+ )
395
+ corrected_diodes_added_to_length = (
396
+ DIODES_ADDED_TO_LENGTH * scaling_factor_for_horizontal_lengths
397
+ )
398
+
399
+ # :136-145 -- determine no. of edges. The elseif is dead from imgProc_sm,
400
+ # where smallest = min(top, bottom) <= largest = max(top, bottom).
401
+ number_edges_touching = 0
402
+ if largest_edge_touching > 0:
403
+ number_edges_touching = number_edges_touching + 1
404
+ if smallest_edge_touching > 0:
405
+ number_edges_touching = number_edges_touching + 1
406
+ elif smallest_edge_touching > 0:
407
+ number_edges_touching = number_edges_touching + 1
408
+
409
+ # :148-152. Scaled length vs UNSCALED edge -- see "Latent defects".
410
+ center_in = 1
411
+ if max_horizontal_length <= largest_edge_touching:
412
+ center_in = 0
413
+
414
+ if number_edges_touching == 2 and center_in == 1:
415
+ # :155-159. Heymsfield-Parrish circle through both edge chords. The
416
+ # "+ is replaced by -" comment (Will, 2013-10-17) refers to the sign
417
+ # inside the parentheses, not to the leading term.
418
+ temp = number_diodes_in_array + (
419
+ largest_edge_touching_length**2 - smallest_edge_touching_length**2
420
+ ) / (4 * number_diodes_in_array)
421
+ horizontal_size = math.sqrt(temp**2 + smallest_edge_touching_length**2)
422
+ horizontal_chord = horizontal_size * diode_size
423
+ diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord)
424
+ diameter_horiz_chord = horizontal_chord_to_spherical_dia(horizontal_chord)
425
+ elif number_edges_touching == 2:
426
+ # :161-165. Same fit, but centre-out, so only the circle fit is
427
+ # trusted; diameter_horiz_chord stays 0.
428
+ largest_edge_touching_length = (
429
+ largest_edge_touching_length + corrected_diodes_added_to_length
430
+ )
431
+ temp = number_diodes_in_array + (
432
+ largest_edge_touching_length**2 - smallest_edge_touching_length**2
433
+ ) / (4 * number_diodes_in_array)
434
+ horizontal_size = math.sqrt(temp**2 + smallest_edge_touching_length**2)
435
+ horizontal_chord = horizontal_size * diode_size
436
+ diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord)
437
+ elif number_edges_touching == 1 and center_in == 1:
438
+ # :167-169. Second application of the diode-size correction; see
439
+ # "Latent defects".
440
+ horizontal_chord = (
441
+ max_horizontal_length + DIODES_ADDED_TO_LENGTH
442
+ ) * corrected_horizontal_diode_size
443
+ diameter_horiz_chord = horizontal_chord_to_spherical_dia(horizontal_chord)
444
+ diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord)
445
+ elif number_edges_touching == 1:
446
+ # :171-175. The only branch that uses diodes_added_to_height, and it
447
+ # uses half of it. max_vertical_length is rebound before the divide, so
448
+ # the denominator cannot be zero unless it was -0.5.
449
+ largest_edge_touching_length = (
450
+ largest_edge_touching_length + corrected_diodes_added_to_length
451
+ )
452
+ max_vertical_length = max_vertical_length + DIODES_ADDED_TO_HEIGHT * 0.5
453
+ horizontal_size = mdiv(
454
+ 0.25 * largest_edge_touching_length**2 + max_vertical_length**2,
455
+ max_vertical_length,
456
+ )
457
+ horizontal_chord = horizontal_size * diode_size
458
+ diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord)
459
+ else:
460
+ # :177-185. Entirely-in image: everything is measurable, so this is the
461
+ # only branch that fills all seven returns.
462
+ horizontal_chord = (
463
+ max_horizontal_length + DIODES_ADDED_TO_LENGTH
464
+ ) * corrected_horizontal_diode_size
465
+ diameter_horiz_chord = horizontal_chord_to_spherical_dia(horizontal_chord)
466
+ diameter_circle_fit = horizontal_chord_to_spherical_dia(horizontal_chord)
467
+ # :180 uses diodes_added_to_LENGTH (0), not _to_height -- so the
468
+ # vertical chord gets no addition either.
469
+ vertical_chord = (max_vertical_length + DIODES_ADDED_TO_LENGTH) * diode_size
470
+ # :181. 0/0 is NaN in MATLAB, not an exception -- mdiv keeps that.
471
+ axis_ratio = float(mdiv(vertical_chord, horizontal_chord))
472
+ diameter_vert_chord = vertical_chord_to_spherical_dia(vertical_chord)
473
+ horizontal_mean_chord = math.sqrt(horizontal_chord * vertical_chord)
474
+ diameter_horiz_mean = horizontal_chord_to_spherical_dia(horizontal_mean_chord)
475
+ # :185. exp(log(x)/3), not x**(1/3) -- kept verbatim: they differ in
476
+ # the last ulp, and at x == 0 they differ in kind. MATLAB's log(0) is
477
+ # -Inf and exp(-Inf) is 0, where Python's math.log(0) raises; np.log
478
+ # gives MATLAB's answer, so a zero-length particle returns 0.0 here
479
+ # rather than blowing up. Verified against Octave (both_zero_lengths).
480
+ with np.errstate(divide="ignore", invalid="ignore"):
481
+ diameter_spheroid = math.exp(
482
+ np.log(horizontal_chord**2 * vertical_chord) / 3
483
+ )
484
+
485
+ return DropSize(
486
+ center_in,
487
+ float(axis_ratio),
488
+ float(diameter_circle_fit),
489
+ float(diameter_horiz_chord),
490
+ float(diameter_vert_chord),
491
+ float(diameter_horiz_mean),
492
+ float(diameter_spheroid),
493
+ )
494
+
495
+
496
+ # --------------------------------------------------------------------------
497
+ # Registration -- the registry seam
498
+ # --------------------------------------------------------------------------
499
+
500
+ register_size_definition(SizeDefinition(
501
+ key="dropsize",
502
+ func=dropsize,
503
+ phase="liquid",
504
+ description=(
505
+ "Equivalent-volume-sphere diameters from measured chords, via the "
506
+ "raindrop equilibrium-shape tables; circle fit after Heymsfield & "
507
+ "Parrish (1978) for edge-touching images."
508
+ ),
509
+ provenance="dropsize.m:1-187, called at imgProc_sm.m:833",
510
+ outputs=(
511
+ "center_in",
512
+ "axis_ratio",
513
+ "diameter_circle_fit",
514
+ "diameter_horiz_chord",
515
+ "diameter_vert_chord",
516
+ "diameter_horiz_mean",
517
+ "diameter_spheroid",
518
+ ),
519
+ ))