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,814 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Shared leaf: the sizeDist time-conversion helpers both engines use.
3
+
4
+ Moved verbatim from ``arrayprobe.sizedist``;
5
+ that module re-imports them, so its names still resolve. Pure functions: no
6
+ module state, no numba, nothing a worker pickles.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from dataclasses import dataclass
13
+
14
+ import numpy as np
15
+
16
+ from arrayprobe_uiops.matlab_compat import (
17
+ madd,
18
+ mcolon,
19
+ mdiv,
20
+ mfind,
21
+ mmax,
22
+ mmul,
23
+ mpow,
24
+ msqrt,
25
+ msum,
26
+ msum_extra,
27
+ nanmean,
28
+ nansum,
29
+ )
30
+
31
+
32
+ def _hhmmss_to_insec(a):
33
+ """``hhmmss2insec.m``, vectorised.
34
+
35
+ ``time_convert.hhmmss_to_insec`` is scalar (it calls ``float()``); this stage
36
+ applies it to whole arrays. All three terms are floored, seconds included
37
+ (``floor(mod(timehhmmss,100))`` in stock v3.1.4, the ORACLES variant and v3.5
38
+ alike; Octave 11.3 gives ``hhmmss2insec(120000.5) = 43200`` on all three).
39
+ Every file-driven caller passes whole seconds, so the floor on the seconds
40
+ term changes no written value.
41
+ """
42
+ t = np.asarray(a, dtype=np.float64)
43
+ return (t // 10000) * 3600 + ((t % 10000) // 100) * 60 + np.floor(t % 100)
44
+
45
+
46
+ def _insec_to_hhmmss(a):
47
+ """``insec2hhmmss.m``, vectorised -- the inverse of :func:`_hhmmss_to_insec`.
48
+
49
+ ``timehhmmss = floor(insec/3600)*10000 + floor(mod(insec,3600)/60)*100 +
50
+ floor(mod(insec,60))`` -- unlike :func:`_hhmmss_to_insec`, EVERY term is
51
+ floored here, matching the real ``insec2hhmmss.m`` (confirmed by reading
52
+ it directly, not assumed from the sibling function's convention).
53
+ """
54
+ s = np.asarray(a, dtype=np.float64)
55
+ return (np.floor(s / 3600) * 10000
56
+ + np.floor((s % 3600) / 60) * 100
57
+ + np.floor(s % 60))
58
+
59
+
60
+ #: ``:1080`` -- the reject codes that count as an accepted particle.
61
+ GOOD_REJECT_CODES: str = "0HhuR"
62
+
63
+
64
+ #: ``:441`` -- the fourteen reject-criterion columns, in source order. Computed
65
+ #: by MATLAB and never written to the file; kept because it is cheap and is the
66
+ #: only per-code breakdown the stage produces.
67
+ REJECT_CRITERION_CODES: tuple[str, ...] = (
68
+ "centerin", "0", "H", "h", "u", "a", "t", "p", "s", "z", "i", "A", "S", "R",
69
+ )
70
+
71
+
72
+ _VARS = (
73
+ ("time", ("Time",), (("units", "HHMMSS"), ("name", "Time"))),
74
+ ("bin_min", ("CIPcorrlen",), (("units", "millimeter"),
75
+ ("long_name", "bin minimum size"), ("short_name", "bin min"))),
76
+ ("bin_max", ("CIPcorrlen",), (("units", "millimeter"),
77
+ ("long_name", "bin maximum size"), ("short_name", "bin max"))),
78
+ ("bin_mid", ("CIPcorrlen",), (("units", "millimeter"),
79
+ ("long_name", "bin midpoint size"), ("short_name", "bin mid"))),
80
+ ("bin_dD", ("CIPcorrlen",), (("units", "millimeter"),
81
+ ("long_name", "bin size"), ("short_name", "bin size"))),
82
+ ("conc_minR", ("CIPcorrlen", "Time"), (("units", "cm-4"),
83
+ ("long_name", "Size distribution using Dmax"), ("short_name", "N(Dmax)"))),
84
+ ("area", ("CIParealen", "CIPcorrlen", "Time"), (("units", "cm-4"),
85
+ ("long_name", "binned area ratio"), ("short_name", "binned area ratio"))),
86
+ ("conc_AreaR", ("CIPcorrlen", "Time"), (("units", "cm-4"),
87
+ ("long_name", "Size distribution using area-equivalent Diameter"),
88
+ ("short_name", "N(Darea)"))),
89
+ ("n", ("Time",), (("units", "cm-3"),
90
+ ("long_name", "number concentration"), ("short_name", "N"))),
91
+ ("total_area", ("CIPcorrlen", "Time"), (("units", "mm2/cm4"),
92
+ ("long_name", "projected area (extinction)"), ("short_name", "Ac"))),
93
+ ("mass", ("CIPcorrlen", "Time"), (("units", "g/cm4"),
94
+ ("long_name", "mass using m-D relations"), ("short_name", "mass"))),
95
+ ("habitsd", ("Habit", "CIPcorrlen", "Time"), (("units", "cm-4"),
96
+ ("long_name", "Size Distribution with Habit"),
97
+ ("short_name", "habit SD"))),
98
+ # 'mm' is the variant text; _write swaps in AttributeText.re_units
99
+ # (stock :1935/:2031 says 'um').
100
+ ("re", ("Time",), (("units", "mm"),
101
+ ("long_name", "effective radius"), ("short_name", "Re"))),
102
+ ("ar", ("Time",), (("units", "100/100"),
103
+ ("long_name", "Area Ratio"), ("short_name", "AR"))),
104
+ ("massBL", ("CIPcorrlen", "Time"), (("units", "g/cm4"),
105
+ ("long_name", "mass using Baker and Lawson method"),
106
+ ("short_name", "mass_BL"))),
107
+ ("Reject_ratio", ("Time",), (("units", "100/100"),
108
+ ("long_name", "Reject Ratio"),)),
109
+ ("vt", ("CIPcorrlen", "Time"), (("units", "g/cm4"),
110
+ ("long_name", "Mass-weighted terminal velocity"),)),
111
+ ("Prec_rate", ("CIPcorrlen", "Time"), (("units", "mm/hr"),
112
+ ("long_name", "Precipitation Rate"),)),
113
+ ("habitmsd", ("Habit", "CIPcorrlen", "Time"), (("units", "g/cm-4"),
114
+ ("long_name", "Mass Size Distribution with Habit"),
115
+ ("short_name", "Habit Mass SD"))),
116
+ ("Calcd_area", ("CIPcorrlen", "Time"), (("units", "mm^2/cm4"),
117
+ ("long_name", "Particle Area Calculated using A-D realtions"),
118
+ ("short_name", "Ac_calc"))),
119
+ ("count", ("CIPcorrlen", "Time"), (("units", "1"),
120
+ ("long_name",
121
+ "number count for partial images without any correction"),)),
122
+ )
123
+
124
+ _VARS_ASPECT = (
125
+ ("mean_aspect_ratio_rectangle", ("CIPcorrlen", "Time"), (("units", "1"),
126
+ ("long_name", "Aspect Ratio by Rectangle fit"),)),
127
+ ("mean_aspect_ratio_ellipse", ("CIPcorrlen", "Time"), (("units", "1"),
128
+ ("long_name", "Aspect Ratio by Ellipse fit"),)),
129
+ )
130
+
131
+ _VARS_TAIL = (
132
+ ("mean_area_ratio", ("CIPcorrlen", "Time"), (("units", "1"),
133
+ ("long_name", "Area Ratio"),)),
134
+ ("mean_perimeter", ("CIPcorrlen", "Time"), (("units", "um"),
135
+ ("long_name", "mean perimeter"),)),
136
+ )
137
+
138
+ _VARS_INTARR = (
139
+ ("sum_IntArr", ("Time",), (("units", "s"), ("long_name",
140
+ "sum of inter-arrival times, excluding the overload time for particles "
141
+ "affected by saving of image data"),)),
142
+ ("sample_vol", ("CIPcorrlen", "Time"), (("units", "cm^3"),
143
+ ("long_name", "sample volume for each bin"),)),
144
+ )
145
+
146
+ #: ``:1852-1938`` -- the nineteen ``REJ_`` twins, in definition order. There is
147
+ #: **no** ``REJ_Reject_ratio``, and the two aspect-ratio variables appear here
148
+ #: whether or not ``iCreateAspectRatio`` is set.
149
+ _REJ_ORDER = (
150
+ "conc_minR", "area", "conc_AreaR", "n", "total_area", "mass", "habitsd",
151
+ "re", "ar", "massBL", "vt", "Prec_rate", "habitmsd", "Calcd_area", "count",
152
+ "mean_aspect_ratio_rectangle", "mean_aspect_ratio_ellipse",
153
+ "mean_area_ratio", "mean_perimeter",
154
+ )
155
+
156
+
157
+ def _num2str(x):
158
+ """MATLAB ``num2str`` for the two reacceptance numbers in the attribute."""
159
+ v = float(x)
160
+ if v == int(v):
161
+ return str(int(v))
162
+ return f"{v:.4g}"
163
+
164
+
165
+ def _optional_parameters(bad, aspect, intarr):
166
+ """``:1705-1728`` -- the eight-way attribute string, in source order."""
167
+ parts = []
168
+ if bad:
169
+ parts.append("SDs from rejected particles")
170
+ if aspect:
171
+ parts.append("SDs w/ aspect ratio")
172
+ if intarr:
173
+ parts.append("Sample volume info")
174
+ return ", ".join(parts) if parts else "None"
175
+
176
+
177
+ _REJ_ATTS = {
178
+ "conc_minR": (("units", "cm-4"),
179
+ ("long_name",
180
+ "Size distribution of rejected particles using Dmax"),
181
+ ("short_name", "N(Dmax) rejected")),
182
+ "area": (("units", "cm-4"),
183
+ ("long_name", "binned area ratio of rejected particles"),
184
+ ("short_name", "binned area ratio of rejected particles")),
185
+ "conc_AreaR": (("units", "cm-4"),
186
+ ("long_name", "Size distribution of rejected particles "
187
+ "using area-equivalent Diameter"),
188
+ ("short_name", "N(Darea) rejected")),
189
+ "n": (("units", "cm-3"),
190
+ ("long_name", "number concentration of rejected particles"),
191
+ ("short_name", "N_rejected")),
192
+ "total_area": (("units", "mm2/cm4"),
193
+ ("long_name",
194
+ "projected area (extinction) of rejected particles"),
195
+ ("short_name", "Ac_rejected")),
196
+ "mass": (("units", "g/cm4"),
197
+ ("long_name", "mass of rejected particles using m-D relations"),
198
+ ("short_name", "mass_rejected")),
199
+ "habitsd": (("units", "cm-4"),
200
+ ("long_name",
201
+ "Size Distribution with Habit of rejected particles"),
202
+ ("short_name", "habit SD rejected")),
203
+ # 'mm' is the variant text; _write swaps in AttributeText.re_units
204
+ # (stock :1935/:2031 says 'um').
205
+ "re": (("units", "mm"),
206
+ ("long_name", "effective radius of rejected particles"),
207
+ ("short_name", "Re_rejected")),
208
+ "ar": (("units", "100/100"),
209
+ ("long_name", "Area Ratio of rejected particles"),
210
+ ("short_name", "AR_rejected")),
211
+ "massBL": (("units", "g/cm4"),
212
+ ("long_name", "mass of rejected particles using Baker and "
213
+ "Lawson method"),
214
+ ("short_name", "mass_BL_rejected")),
215
+ "Reject_ratio": (("units", "100/100"), ("long_name", "Reject Ratio")),
216
+ "vt": (("units", "g/cm4"),
217
+ ("long_name",
218
+ "Mass-weighted terminal velocity of rejected particles")),
219
+ "Prec_rate": (("units", "mm/hr"),
220
+ ("long_name", "Precipitation Rate of rejected particles")),
221
+ "habitmsd": (("units", "g/cm-4"),
222
+ ("long_name", "Mass Size Distribution with Habit of "
223
+ "rejected particles"),
224
+ ("short_name", "Habit Mass SD rejected")),
225
+ "Calcd_area": (("units", "mm^2/cm4"),
226
+ ("long_name", "Particle Area of rejected particles "
227
+ "Calculated using A-D realtions"),
228
+ ("short_name", "Ac_calc_rejected")),
229
+ "count": (("units", "1"),
230
+ ("long_name", "number count of rejected particles for partial "
231
+ "images without any correction")),
232
+ "mean_aspect_ratio_rectangle": (("units", "1"),
233
+ ("long_name", "Aspect Ratio of rejected "
234
+ "particles by Rectangle fit")),
235
+ "mean_aspect_ratio_ellipse": (("units", "1"),
236
+ ("long_name", "Aspect Ratio of rejected "
237
+ "particles by Ellipse fit")),
238
+ "mean_area_ratio": (("units", "1"),
239
+ ("long_name", "Area Ratio of rejected particles")),
240
+ "mean_perimeter": (("units", "um"),
241
+ ("long_name", "mean perimeter of rejected particles")),
242
+ }
243
+
244
+
245
+ # ---------------------------------------------------------------------------
246
+ # Moved verbatim from arrayprobe.sizedist (v3.1.4 cut S2, 2026-10-10): the
247
+ # population binner, shattered-particle reacceptance, midnight rollover, the six
248
+ # d_choice definitions and the module constants they read. arrayprobe.sizedist
249
+ # re-exports every name (same objects).
250
+ # ---------------------------------------------------------------------------
251
+
252
+ #: ``warn_suspect_rollover`` logs under the v3.1.4 module's name, as before the move.
253
+ _logger = logging.getLogger("arrayprobe.sizedist")
254
+
255
+ #: ``:1207-1248`` -- the ten habit codes, in the order they are binned into the
256
+ #: ``Habit`` dimension. ``holroyd.m`` can emit more than these ten; anything not
257
+ #: listed simply lands in no habit slice, which is upstream behaviour, not a
258
+ #: transcription gap.
259
+ HABIT_ORDER: str = "slothigdaI"
260
+
261
+
262
+ #: ``:475`` -- ``area_bins = 0:.1:1.01``, giving eleven edges and ten slices.
263
+ AREA_BINS: np.ndarray = np.array(
264
+ [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
265
+ )
266
+
267
+
268
+ @dataclass(frozen=True)
269
+ class RejectThresholds:
270
+ """The reject constants that live in ``sizeDist.m`` rather than in
271
+ ``calculate_reject_unified.m``.
272
+
273
+ One field today. It is a dataclass and not a bare float because the value
274
+ is a *provable* divergence between the trees with ``file:line`` provenance on
275
+ both sides -- the same standard ``FidelityProfile`` holds itself to -- and
276
+ because hard-wiring either number is exactly the error this project has
277
+ made three times.
278
+ """
279
+
280
+ area_ratio_z: float
281
+ """``:849`` -- ``auto_reject(area_ratio < X) = 'z'``."""
282
+
283
+ provenance: str
284
+
285
+
286
+ ORACLES_REJECT = RejectThresholds(
287
+ area_ratio_z=0.5,
288
+ provenance=(
289
+ "sizeDist.m:849 of the variant that wrote the archived product sets "
290
+ "area_ratio < .5, where stock sizeDist.m uses .2."
291
+ ),
292
+ )
293
+
294
+
295
+ STOCK_REJECT = RejectThresholds(
296
+ area_ratio_z=0.2,
297
+ provenance=(
298
+ "UIOPS-v3.1.4 sizeDist.m and the OptArrProbDataProcessing variant tree "
299
+ "both use .2 -- measured, both trees, 2026-08-19."
300
+ ),
301
+ )
302
+
303
+
304
+ def _d_length(im_length, im_width, diodesize, minr):
305
+ """``:756`` -- ``d_choice == 1``.
306
+
307
+ ``im_length`` is ``int16`` (``imgProc_sm.m:299``); MATLAB keeps the integer
308
+ type across ``* diodesize`` and saturates.
309
+ :func:`arrayprobe.matlab_compat.mmul` carries
310
+ that rule; a plain ``*`` would let NumPy silently promote to float64 and
311
+ fix the bug.
312
+ """
313
+ return mmul(im_length, diodesize)
314
+
315
+
316
+ def _d_width(im_length, im_width, diodesize, minr):
317
+ """``:758`` -- ``d_choice == 2``. Same int16 diameter saturation trap as :func:`_d_length`."""
318
+ return mmul(im_width, diodesize)
319
+
320
+
321
+ def _d_mean(im_length, im_width, diodesize, minr):
322
+ """``:760`` -- ``d_choice == 3``.
323
+
324
+ ``(im_length + im_width)/2 * diodesize`` -- three int-dominant ops in a
325
+ row, each saturating in turn.
326
+ """
327
+ return mmul(mdiv(madd(im_length, im_width), 2.0), diodesize)
328
+
329
+
330
+ def _d_hypot(im_length, im_width, diodesize, minr):
331
+ """``:762`` -- ``d_choice == 4``.
332
+
333
+ ``sqrt(im_width.^2+im_length.^2) * diodesize``. The squares and their sum
334
+ saturate as int16, but ``sqrt`` **promotes** to double, so the final
335
+ ``* diodesize`` is an ordinary double multiply -- this is the one d_choice
336
+ that escapes the zero-collapse, though the radicand still saturates above
337
+ 181 diodes. See :func:`arrayprobe.matlab_compat.msqrt`.
338
+ """
339
+ return msqrt(madd(mpow(im_width, 2.0), mpow(im_length, 2.0))) * diodesize
340
+
341
+
342
+ def _d_max(im_length, im_width, diodesize, minr):
343
+ """``:764`` -- ``d_choice == 5``.
344
+
345
+ ``max`` on two int16 arrays stays int16 (no promotion), so the trailing
346
+ ``* diodesize`` still saturates. Uses :func:`arrayprobe.matlab_compat.mmax`
347
+ rather than a bare ``np.maximum`` -- behaviourally identical for this port's
348
+ actual inputs (``im_width``/``im_length`` are always the same dtype as each
349
+ other), but correct rather than coincidental if that ever stops being true.
350
+ """
351
+ return mmul(mmax(im_width, im_length), diodesize)
352
+
353
+
354
+ def _d_minr(im_length, im_width, diodesize, minr):
355
+ """``:766`` -- ``d_choice == 6``, the default in every UIOOPS run script.
356
+
357
+ Reads ``image_diam_minR`` straight out of the proc file and does **not**
358
+ rescale it; the struck-out ``% * diodesize`` at the end of that line is the
359
+ author noticing the value is already in millimetres. Contrast ``:669``.
360
+ """
361
+ return minr
362
+
363
+
364
+ _D_CHOICE_SPECS = (
365
+ (1, "sizedist_length", _d_length, "L_x", "sizeDist.m:1054"),
366
+ (2, "sizedist_width", _d_width, "L_y", "sizeDist.m:1056"),
367
+ (3, "sizedist_mean", _d_mean, "mean(L_x,L_y)", "sizeDist.m:1058"),
368
+ (4, "sizedist_hypot", _d_hypot, "hypotenuse(L_x,L_y)", "sizeDist.m:1060"),
369
+ (5, "sizedist_max", _d_max, "max(L_x,L_y)", "sizeDist.m:1062"),
370
+ (6, "sizedist_minR", _d_minr, "D of minimum enclosing circle",
371
+ "sizeDist.m:1064"),
372
+ )
373
+
374
+
375
+ def _rollover_240000(x):
376
+ """``:83-84`` and ``:544-545`` -- the midnight correction, bug included.
377
+
378
+ ``x(find(diff(x)<0)+1:end) = x(find(diff(x)<0)+1:end) + 240000``. MATLAB's
379
+ colon operator collapses each vector operand to its **first** element, so
380
+ only the first decrease is ever corrected; a flight crossing midnight twice
381
+ keeps the second discontinuity. An empty ``find`` makes the whole statement
382
+ a silent no-op, which is the common case and must not raise.
383
+
384
+ Mutates and returns ``x``, as the MATLAB statement does.
385
+ """
386
+ idx = mfind(np.diff(x) < 0) + 1 # 1-based, as MATLAB's find is
387
+ rng = mcolon(idx, len(x)) # ...collapsed to its first element
388
+ if rng.size:
389
+ x[rng - 1] += 240000
390
+ return x
391
+
392
+
393
+ def warn_suspect_rollover(x, engine: str) -> int:
394
+ """Say so when the midnight correction is about to shift particles on no crossover.
395
+
396
+ Diagnostic only -- it reads ``x`` and changes nothing, so the written bytes are the MATLAB's.
397
+ ``sizeDist``'s correction (v3.1.4 ``:544-545``; v3.5's single-decrease branch ``:790-792``)
398
+ adds 240000 to every particle after the first decrease in the particle clock, whatever its
399
+ size. When that decrease fails the developers' own crossover test from v3.5
400
+ (``sizeDist.m:796-797``: previous value ``> 230000`` and a drop ``> 230000``), it is a clock
401
+ glitch, not midnight, and every later particle is filed a day late -- 2,899,268 of 3,796,565
402
+ session-2 CIP particles on 2016-09-06, with nothing printed. Returns the number of particles
403
+ the correction will move (0 when it is a real crossover or there is no decrease).
404
+ """
405
+ x = np.asarray(x, dtype=np.float64).ravel()
406
+ dec = np.flatnonzero(np.diff(x) < 0)
407
+ if dec.size == 0:
408
+ return 0
409
+ d = int(dec[0])
410
+ if x[d] > 230000 and x[d] - x[d + 1] > 230000:
411
+ return 0
412
+ moved = int(x.size - d - 1)
413
+ _logger.warning(
414
+ "sizeDist midnight correction (engine %s): particle %d steps back from %06d to %06d, "
415
+ "which is not a day crossover (sizeDist.m:796-797's test fails), yet all %d later "
416
+ "particles (%.1f %%) are shifted +240000 and filed a day late -- reproduced faithfully. "
417
+ "To keep them, run the enhancement particle_time_glitch_fix "
418
+ "(arrayprobe-enhancements, [enhancements] particle_time_glitch_fix = true) or a "
419
+ "SODA-2 run.", engine, d + 1, int(x[d]), int(x[d + 1]), moved,
420
+ 100.0 * moved / x.size)
421
+ return moved
422
+
423
+
424
+ def bin_index(values, kk):
425
+ """Which ``kk`` bin each value falls in, or ``-1``.
426
+
427
+ Source: the per-bin ``>= kk(j) & < kk(j+1)`` counts of ``sizeDist.m`` (UIOOPS v3.1.4), e.g.
428
+ ``:1330-1333``.
429
+
430
+ The source writes ``>= kk(j) & < kk(j+1)`` explicitly for every ``j``. For a
431
+ strictly increasing ``kk`` that is exactly a right-side search minus one,
432
+ with everything below ``kk(1)`` or at/above ``kk(end)`` excluded. NaN sorts
433
+ to the end and is therefore excluded too, which is the MATLAB behaviour --
434
+ both comparisons are false for NaN.
435
+
436
+ Returned indices are 0-based, because they index Python accumulators rather
437
+ than appearing in a transcribed expression.
438
+ """
439
+ v = np.asarray(values, dtype=np.float64)
440
+ idx = np.searchsorted(kk, v, side="right") - 1
441
+ idx[~((v >= kk[0]) & (v < kk[-1]))] = -1
442
+ return idx
443
+
444
+
445
+ def _count_by_bin(idx, num_bins, mask=None):
446
+ """``length(find(... >= kk(j) & ... < kk(j+1)))`` for every ``j`` at once."""
447
+ sel = idx >= 0 if mask is None else (idx >= 0) & mask
448
+ return np.bincount(idx[sel], minlength=num_bins).astype(np.float64)
449
+
450
+
451
+ def _nansum_by_bin(idx, values, num_bins, mask=None):
452
+ """``nansum`` over each bin -- NaN counted as zero, empty bin giving 0."""
453
+ v = np.asarray(values, dtype=np.float64)
454
+ sel = (idx >= 0) & np.isfinite(v)
455
+ if mask is not None:
456
+ sel = sel & mask
457
+ return np.bincount(idx[sel], weights=v[sel], minlength=num_bins)
458
+
459
+
460
+ def _nanmean_by_bin(idx, values, num_bins, mask=None):
461
+ """``nanmean`` over each bin -- NaN ignored, empty or all-NaN bin giving NaN."""
462
+ v = np.asarray(values, dtype=np.float64)
463
+ sel = (idx >= 0) & np.isfinite(v)
464
+ if mask is not None:
465
+ sel = sel & mask
466
+ total = np.bincount(idx[sel], weights=v[sel], minlength=num_bins)
467
+ n = np.bincount(idx[sel], minlength=num_bins)
468
+ out = np.full(num_bins, np.nan)
469
+ np.divide(total, n, out=out, where=n > 0)
470
+ return out
471
+
472
+
473
+ def _mean_or_nan(v, extra=False):
474
+ """MATLAB ``mean`` of a possibly empty vector -- ``NaN``, silently.
475
+
476
+ ``sum(x)/length(x)`` with MATLAB's in-order accumulation, not NumPy's
477
+ pairwise one; see :func:`arrayprobe.matlab_compat.msum`.
478
+
479
+ ``extra=True`` switches to Octave 11.3's compensated accumulator instead.
480
+ That is **not** MATLAB behaviour and exists only so the oracle comparison
481
+ can be exact -- see :func:`arrayprobe.matlab_compat.msum_extra` and
482
+ ``run(octave_mean_extra=...)``.
483
+ """
484
+ a = np.asarray(v, dtype=np.float64)
485
+ if a.size == 0:
486
+ return np.float64(np.nan)
487
+ total = msum_extra(a) if extra else msum(a)
488
+ return np.float64(total / a.size)
489
+
490
+
491
+ @dataclass
492
+ class _BinnedSecond:
493
+ """One second's per-bin accumulators, before binwidth normalisation."""
494
+
495
+ dist_minR: np.ndarray
496
+ dist_AreaR: np.ndarray
497
+ habitsd: np.ndarray # (num_bins, 10)
498
+ habitmsd: np.ndarray # (num_bins, 10)
499
+ area: np.ndarray
500
+ meanp: np.ndarray
501
+ areaRatio1: np.ndarray
502
+ #: ``:1257-1263`` -- filled only under ``iCreateAspectRatio``; ``None``
503
+ #: otherwise, so the flag-off path allocates nothing and the flag-on path
504
+ #: cannot silently fall back to a NaN row.
505
+ aspectRatio: np.ndarray | None
506
+ aspectRatio1: np.ndarray | None
507
+ iwc: np.ndarray
508
+ partarea: np.ndarray
509
+ iwcbl: np.ndarray
510
+ vt: np.ndarray
511
+ pr: np.ndarray
512
+ area_dist2: np.ndarray # (num_bins, 10)
513
+
514
+
515
+ def _bin_second(sel, kk, num_bins):
516
+ """Vectorised ``:1200-1289``. ``sel`` is a :class:`_Selection`."""
517
+ idx = bin_index(sel.diameter, kk)
518
+ idx1 = bin_index(sel.diameter1, kk)
519
+
520
+ habitsd = np.zeros((num_bins, 10))
521
+ habitmsd = np.zeros((num_bins, 10))
522
+ for h, code in enumerate(HABIT_ORDER):
523
+ is_h = sel.habit == ord(code)
524
+ habitsd[:, h] = _count_by_bin(idx, num_bins, is_h)
525
+ # :1229 -- the mask is built over `good_one_sec_locs` and then applied to
526
+ # the UNSLICED `good_iwc`. Reproduced by slicing to the mask's length
527
+ # first, which is what MATLAB's logical indexing does.
528
+ habitmsd[:, h] = _nansum_by_bin(idx, sel.iwc_unsliced[:idx.size],
529
+ num_bins, is_h)
530
+
531
+ area_dist2 = np.zeros((num_bins, 10))
532
+ for k in range(10):
533
+ in_slice = (sel.ar >= AREA_BINS[k]) & (sel.ar < AREA_BINS[k + 1])
534
+ area_dist2[:, k] = _count_by_bin(idx, num_bins, in_slice)
535
+
536
+ return _BinnedSecond(
537
+ dist_minR=_count_by_bin(bin_index(sel.diameter_minR, kk), num_bins),
538
+ dist_AreaR=_count_by_bin(bin_index(sel.diameter_AreaR, kk), num_bins),
539
+ habitsd=habitsd,
540
+ habitmsd=habitmsd,
541
+ area=_nansum_by_bin(idx, sel.area, num_bins),
542
+ meanp=_nanmean_by_bin(idx, sel.perimeter, num_bins),
543
+ areaRatio1=_nanmean_by_bin(idx1, sel.ar1, num_bins),
544
+ # :1259,:1262 -- both indexed by `good_one_sec_locs1` and
545
+ # `good_particle_diameter1`, i.e. the entire-in-excluded set, exactly
546
+ # like areaRatio1 above and unlike every `idx` sibling.
547
+ aspectRatio=(None if sel.aspect is None
548
+ else _nanmean_by_bin(idx1, sel.aspect, num_bins)),
549
+ aspectRatio1=(None if sel.aspect1 is None
550
+ else _nanmean_by_bin(idx1, sel.aspect1, num_bins)),
551
+ iwc=_nansum_by_bin(idx, sel.iwc, num_bins),
552
+ partarea=_nansum_by_bin(idx, sel.partarea, num_bins),
553
+ iwcbl=_nansum_by_bin(idx, sel.iwcbl, num_bins),
554
+ vt=_nansum_by_bin(idx, sel.vt, num_bins),
555
+ pr=_nansum_by_bin(idx, sel.pr, num_bins),
556
+ area_dist2=area_dist2,
557
+ )
558
+
559
+
560
+ def _bin_second_literal(sel, kk, num_bins):
561
+ """``:1200-1289`` transcribed as written -- one ``j`` loop, one test per line.
562
+
563
+ Not used in production (it is O(num_bins x n) per second); it exists so the
564
+ vectorised path above has something to be proved equal to, and so a reader
565
+ can check the transcription against the MATLAB without unpicking a bincount.
566
+ """
567
+ d = np.asarray(sel.diameter, dtype=np.float64)
568
+ d1 = np.asarray(sel.diameter1, dtype=np.float64)
569
+ # Named, not positional: the positional form silently mis-slotted every
570
+ # field after the insertion point when `aspectRatio` was added in the
571
+ # middle, which a `*(... for _ in range(8))` spread cannot make visible.
572
+ out = _BinnedSecond(
573
+ dist_minR=np.zeros(num_bins), dist_AreaR=np.zeros(num_bins),
574
+ habitsd=np.zeros((num_bins, 10)), habitmsd=np.zeros((num_bins, 10)),
575
+ area=np.zeros(num_bins), meanp=np.zeros(num_bins),
576
+ areaRatio1=np.zeros(num_bins),
577
+ aspectRatio=None if sel.aspect is None else np.zeros(num_bins),
578
+ aspectRatio1=None if sel.aspect1 is None else np.zeros(num_bins),
579
+ iwc=np.zeros(num_bins), partarea=np.zeros(num_bins),
580
+ iwcbl=np.zeros(num_bins), vt=np.zeros(num_bins), pr=np.zeros(num_bins),
581
+ area_dist2=np.zeros((num_bins, 10)))
582
+ dminR = np.asarray(sel.diameter_minR, dtype=np.float64)
583
+ dAreaR = np.asarray(sel.diameter_AreaR, dtype=np.float64)
584
+
585
+ for j in range(num_bins):
586
+ lo, hi = kk[j], kk[j + 1]
587
+ out.dist_minR[j] = np.count_nonzero((dminR >= lo) & (dminR < hi))
588
+ out.dist_AreaR[j] = np.count_nonzero((dAreaR >= lo) & (dAreaR < hi))
589
+
590
+ in_bin = (d >= lo) & (d < hi)
591
+ in_bin1 = (d1 >= lo) & (d1 < hi)
592
+
593
+ for h, code in enumerate(HABIT_ORDER):
594
+ is_h = (sel.habit == ord(code)) & in_bin
595
+ out.habitsd[j, h] = np.count_nonzero(is_h)
596
+ out.habitmsd[j, h] = nansum(sel.iwc_unsliced[:is_h.size][is_h])
597
+
598
+ out.area[j] = nansum(sel.area[in_bin])
599
+ out.meanp[j] = nanmean(sel.perimeter[in_bin])
600
+ out.areaRatio1[j] = nanmean(sel.ar1[in_bin1])
601
+ if sel.aspect is not None: # :1257-1263
602
+ out.aspectRatio[j] = nanmean(sel.aspect[in_bin1])
603
+ out.aspectRatio1[j] = nanmean(sel.aspect1[in_bin1])
604
+ out.iwc[j] = nansum(sel.iwc[in_bin])
605
+ out.partarea[j] = nansum(sel.partarea[in_bin])
606
+ out.iwcbl[j] = nansum(sel.iwcbl[in_bin])
607
+ out.vt[j] = nansum(sel.vt[in_bin])
608
+ out.pr[j] = nansum(sel.pr[in_bin])
609
+
610
+ for k in range(10):
611
+ out.area_dist2[j, k] = np.count_nonzero(
612
+ (sel.ar >= AREA_BINS[k]) & (sel.ar < AREA_BINS[k + 1]) & in_bin
613
+ )
614
+
615
+ return out
616
+
617
+
618
+ @dataclass
619
+ class _Selection:
620
+ """One second's accepted (or rejected) particles -- ``:1126-1147``.
621
+
622
+ ``diameter`` and ``diameter_minR`` are the same array in the source
623
+ (``:1146``); both names are kept because the MATLAB uses both and a later
624
+ change to one and not the other should be visible.
625
+ """
626
+
627
+ diameter_minR: np.ndarray
628
+ diameter_AreaR: np.ndarray
629
+ diameter: np.ndarray
630
+ diameter1: np.ndarray
631
+ habit: np.ndarray
632
+ area: np.ndarray
633
+ perimeter: np.ndarray
634
+ ar: np.ndarray
635
+ ar1: np.ndarray
636
+ iwc: np.ndarray
637
+ iwc_unsliced: np.ndarray
638
+ partarea: np.ndarray
639
+ iwcbl: np.ndarray
640
+ vt: np.ndarray
641
+ pr: np.ndarray
642
+ #: ``:685-686`` -- ``image_RectangleW/L`` and ``image_EllipseW/L``, read
643
+ #: only under ``iCreateAspectRatio``. ``None`` when the flag is off, which
644
+ #: is the default in both MATLAB trees; last with a default so the callers
645
+ #: that predate the flag construct unchanged.
646
+ aspect: np.ndarray | None = None
647
+ aspect1: np.ndarray | None = None
648
+
649
+
650
+ def _reaccept_shattered(auto_reject, int_arr, int_arr3, ia_thresh,
651
+ particle_diameter_minR, cfg) -> None:
652
+ """``sizeDist.m:894-912`` / ``:1155-1173`` -- put one shattered particle back.
653
+
654
+ **The source carries this block twice, once under each shattering gate**, and
655
+ the two copies differ only in which threshold array they read: `iaThresh`
656
+ under `iaThreshType == 1`, `intar_threshold(i)` under `== 2`. Passing the
657
+ threshold in is therefore a faithful sharing of one behaviour, not a merge of
658
+ two -- and it means a future correction cannot be applied to one copy and
659
+ forgotten in the other, which is how the two drifted apart in the first place
660
+ (the `:1155` copy still carries Stechman's original attribution while `:894`
661
+ carries Finlon's 2017 revision).
662
+
663
+ The rationale, in the source's own words: particles flagged as shattered "may
664
+ in fact be the result of diffraction fringes", which are expected to be
665
+ LARGER than fragments and to arrive with a particularly small inter-arrival.
666
+ So within one shattering event the largest particle above ``reaccptD`` that
667
+ also arrives faster than ``reaccptMaxIA`` is restored with the code ``'R'``,
668
+ which ``GOOD_REJECT_CODES`` counts as accepted.
669
+
670
+ **TWO PRESERVED BUGS, both from one MATLAB idiom.**
671
+ The reacceptance loop (``sizeDist.m:1036``) builds its range from two *vectors*
672
+ (the found begin and end indices), and ``a:b`` uses only the first element of each:
673
+
674
+ 1. only the FIRST shattering event in a second is ever scanned, however many
675
+ the second holds; and
676
+ 2. if the first ``rEnd`` precedes the first ``rBegin`` -- which an event
677
+ beginning at a block boundary produces, because that block's first
678
+ inter-arrival is the sentinel 0 -- the range is empty and **nothing is
679
+ reaccepted at all**.
680
+
681
+ The second was demonstrated rather than argued: stock, run under Octave on a
682
+ fixture of exactly that shape, binned one particle where a reacceptance would
683
+ have made it two (``octave_oracle/run_reacceptance_bank.py``).
684
+ """
685
+ r_begin = (int_arr > ia_thresh) & (int_arr3 < ia_thresh)
686
+ r_end = (int_arr < ia_thresh) & (int_arr3 > ia_thresh)
687
+
688
+ max_particle = cfg.reaccpt_d
689
+ e_index = None
690
+ begins = np.flatnonzero(r_begin)
691
+ ends = np.flatnonzero(r_end)
692
+ if begins.size and ends.size:
693
+ # `find(...)` on an empty match yields an empty range in MATLAB and the
694
+ # loop simply does not run; the same is true here, without the ambiguity
695
+ # of an empty argmax.
696
+ for i_event in range(int(begins[0]), int(ends[0]) + 1):
697
+ if (particle_diameter_minR[i_event] > max_particle
698
+ and int_arr[i_event] < cfg.reaccpt_max_ia):
699
+ max_particle = particle_diameter_minR[i_event]
700
+ e_index = i_event
701
+ if e_index is not None:
702
+ # `auto_reject(eIndex) = 'R'` with `eIndex = []` is a no-op in MATLAB,
703
+ # which is what "no candidate" means.
704
+ auto_reject[e_index] = ord("R")
705
+
706
+
707
+ def _process_population(i, mask, entirein, image_time, one_sec_times, kk,
708
+ num_bins, binwidth, diameter_minR, diameter_AreaR,
709
+ habit1, area, perimeter, area_ratio, particle_mass,
710
+ calcd_area, particle_massbl, particle_vt, particle_pr,
711
+ store, octave_mean_extra=False,
712
+ aspect_ratio=None, aspect_ratio1=None):
713
+ """``:1126-1342`` for one population (accepted or rejected).
714
+
715
+ The MATLAB writes this block twice, once per population, with every name
716
+ prefixed ``bad_`` in the second copy. The two are identical line for line
717
+ -- verified by diffing ``:1126-1342`` against ``:1151-1482`` -- so they are
718
+ one function here. Two asymmetries between the populations sit outside it
719
+ and are preserved at their own call sites: the ``entirein``/``centerin``
720
+ filter at ``:1094-1100``, and the four scalars ``:1327``/``:1337-1340``
721
+ rewrite when the accepted population is empty.
722
+
723
+ Returns True when this second produced no particles of this population,
724
+ which is what the caller needs in order to apply that second asymmetry.
725
+ """
726
+ mask1 = mask & (entirein == 0)
727
+ times = image_time[mask]
728
+ times1 = image_time[mask1]
729
+
730
+ locs = np.flatnonzero((times >= one_sec_times[i])
731
+ & (times < one_sec_times[i + 1]))
732
+ locs1 = np.flatnonzero((times1 >= one_sec_times[i])
733
+ & (times1 < one_sec_times[i + 1]))
734
+
735
+ ar1_all = area_ratio[mask1]
736
+ store["one_sec_ar"][i] = _mean_or_nan(ar1_all[locs1], octave_mean_extra)
737
+
738
+ if locs.size == 0:
739
+ # :1316-1327. Note what is NOT reset: `particle_area` (-> total_area)
740
+ # and `cip2_meanp` (-> mean_perimeter) keep their NaN fill, while every
741
+ # sibling goes to 0. So a second with data but no accepted particle has
742
+ # conc_minR == 0 and total_area == NaN. Upstream asymmetry, preserved.
743
+ store["dist_minR"][i, :] = 0
744
+ store["dist_AreaR"][i, :] = 0
745
+ store["area_dist2"][i, :, :] = 0
746
+ store["partarea"][i, :] = 0
747
+ store["iwc"][i, :] = 0
748
+ store["iwcbl"][i, :] = 0
749
+ store["vt"][i, :] = 0
750
+ store["pr"][i, :] = 0
751
+ store["re"][i] = 0
752
+ store["habitsd"][i, :, :] = 0
753
+ store["habitmsd"][i, :, :] = 0
754
+ return True
755
+
756
+ d_all = diameter_minR[mask]
757
+ sel = _Selection(
758
+ diameter_minR=d_all[locs],
759
+ diameter_AreaR=diameter_AreaR[mask][locs],
760
+ diameter=d_all[locs],
761
+ diameter1=diameter_minR[mask1][locs1],
762
+ habit=habit1[mask][locs],
763
+ area=area[mask][locs],
764
+ perimeter=perimeter[mask][locs],
765
+ ar=area_ratio[mask][locs],
766
+ ar1=ar1_all[locs1],
767
+ # :1134-1135 / :1159-1160 -- sliced by `mask1`, the entire-in-excluded
768
+ # population, then by `locs1`. The same two-step every `1`-suffixed
769
+ # name in this block takes.
770
+ aspect=(None if aspect_ratio is None else aspect_ratio[mask1][locs1]),
771
+ aspect1=(None if aspect_ratio1 is None else aspect_ratio1[mask1][locs1]),
772
+ iwc=particle_mass[mask][locs],
773
+ iwc_unsliced=particle_mass[mask],
774
+ partarea=calcd_area[mask][locs],
775
+ iwcbl=particle_massbl[mask][locs],
776
+ vt=particle_vt[mask][locs],
777
+ pr=particle_pr[mask][locs],
778
+ )
779
+ b = _bin_second(sel, kk, num_bins)
780
+
781
+ # :1293-1309 -- normalise by binwidth and convert mm -> cm.
782
+ store["dist_minR"][i, :] = b.dist_minR / binwidth * 10
783
+ store["dist_AreaR"][i, :] = b.dist_AreaR / binwidth * 10
784
+ store["iwc"][i, :] = b.iwc / binwidth * 10
785
+ store["iwcbl"][i, :] = b.iwcbl / binwidth * 10
786
+ store["vt"][i, :] = b.vt / binwidth * 10
787
+ store["pr"][i, :] = b.pr / binwidth * 10
788
+ store["partarea"][i, :] = b.partarea / binwidth * 10
789
+ store["area"][i, :] = b.area / binwidth * 10
790
+ store["habitsd"][i, :, :] = b.habitsd / binwidth[:, None] * 10
791
+ store["habitmsd"][i, :, :] = b.habitmsd / binwidth[:, None] * 10
792
+ store["area_dist2"][i, :, :] = b.area_dist2 / binwidth[:, None] * 10
793
+ store["meanp"][i, :] = b.meanp
794
+ store["areaRatio1"][i, :] = b.areaRatio1
795
+ if b.aspectRatio is not None:
796
+ store["aspectRatio"][i, :] = b.aspectRatio
797
+ store["aspectRatio1"][i, :] = b.aspectRatio1
798
+
799
+ # :1312 -- Fu (1996) generalized effective radius. Plain `sum`, not
800
+ # `nansum`, so a NaN anywhere in the row propagates; neither input can carry
801
+ # one, both having just come out of a nansum.
802
+ with np.errstate(divide="ignore", invalid="ignore"):
803
+ store["re"][i] = ((np.sqrt(3) / (3 * 0.91)) * 1000
804
+ * (msum(store["iwc"][i, :] / binwidth)
805
+ / msum(store["area"][i, :] / binwidth)) * 1000)
806
+ return False
807
+
808
+
809
+ #: ``d_choice`` -> registry key, and the ``Dmax Definition`` attribute string the
810
+ #: file carries for it (``:1680-1692``). Filled here; ``arrayprobe.sizedist``
811
+ #: registers the same six functions with ``arrayprobe.sizing``.
812
+ D_CHOICE: dict[int, tuple[str, str]] = {
813
+ _n: (_key, _label) for _n, _key, _fn, _label, _prov in _D_CHOICE_SPECS
814
+ }