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,1923 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """v3.5's ``sizeDist.m`` DRIVER: the record/second loop, the
3
+ netCDF writer, and the ``iat_threshold`` output variable.
4
+
5
+ ``sizedist_tables.py`` ports the pure, case-griddable pieces: the
6
+ per-campaign/per-probe bin tables, ``iaThreshType == 3``'s pure per-second
7
+ functions, and ``iNewHabit`` detection. This module is the rest: every
8
+ *discrete* new-or-changed driver behaviour the v3.1.4->v3.5 diff contains --
9
+ the shattering dispatch across all three ``iaThreshType`` conventions, the
10
+ multi-day/corrupt particle-time fix, one-second block resolution, the
11
+ overload dead-time cap, the ``d_choice`` diameter definitions and
12
+ ``particle_diameter_AreaR``, the ``area_ratio`` clip, and the writer's
13
+ variable-definition/attribute/transpose deltas -- each independently
14
+ oracle-validated on its own -- assembled into :func:`run`, a real
15
+ record-by-record netCDF-in/netCDF-out driver for **all four probetypes** --
16
+ probetype 2 as first written, probetype 1 (CIP/PIP) added 2026-09-17, probetypes 0
17
+ (2DC/2DP) and 3 (Fast2DC) added 2026-09-23 with the CIP pipeline, each against an Octave run of
18
+ the unmodified v3.5 ``sizeDist.m`` (``octave_oracle/run_v35_probetype03_sizedist_bank.py``,
19
+ ``tests/test_v35_sizedist_probetype03.py``); see "Scope" below.
20
+ *(This line said "probetype 2 only" until 2026-09-18, twenty-four hours after
21
+ the extension forty lines below it landed. The same drift -- a docstring
22
+ contradicting its own module -- put a false capability claim on two shared
23
+ artifact pages the same week, so it is corrected here rather than noted.)*
24
+
25
+ **What is, and is not, validated end to end.** Every discrete piece above
26
+ carries its own Octave-oracle or documented-semantics validation, the
27
+ same
28
+ "validate the signal you claim" standard every other stage in this port
29
+ holds itself to. The *assembly* in :func:`run`/:func:`_run` reuses
30
+ the v3.1.4 validation engine's ``sizedist``'s own unchanged numeric core directly --
31
+ :func:`arrayprobe_uiops.sizedist_core._process_population` for the per-second binning
32
+ (confirmed unchanged: the v3.5 diff across that whole region is pure
33
+ reindentation, no logic change) and :func:`arrayprobe_uiops.sizedist_core._reaccept_shattered`
34
+ for the two D3-preserving loops -- rather than re-deriving it, but the
35
+ *assembly itself* has not been run end-to-end against a real MATLAB v3.5
36
+ execution on a full synthetic per-particle netCDF fixture (no archived
37
+ product exists to validate against either, since v3.5 postdates every
38
+ campaign this project holds -- oracle layer 1 does not apply to any v3.5
39
+ stage). That full differential is V9's job, once V8's own imgProc output
40
+ exists to feed it. :class:`TestRunOnASyntheticFile` exercises :func:`run`
41
+ top-to-bottom on a small netCDF fixture built directly with
42
+ :mod:`arrayprobe_uiops.ncio` (not MATLAB/Octave) to prove the assembly does not
43
+ crash and produces the expected shape and gross values -- a real but weaker
44
+ claim than the piece-level Octave validation, and stated as such rather than
45
+ conflated with it.
46
+
47
+ **Scope, decided up front rather than discovered by a half-finished
48
+ transcription.** v3.5's driver changes touch every probetype's shared
49
+ scaffolding (the particle-time rollover, the block-resolution logic feeding
50
+ the main loop) but only ONE probetype-specific line (the 0.8/1.0 s
51
+ overload-dead-time cap, explicitly gated ``probetype==2``). This driver ports
52
+ **probetype 2 only** (2D-S / HVPS / the IMPACTS 3VCPI probes) -- the probe
53
+ family the measurement-block and driver stages already scoped to, so
54
+ an end-to-end differential has a complete probetype-2 chain to run.
55
+
56
+ **Extended to probetype 1 (CIP/PIP) on 2026-09-17.** v3.5 is the default
57
+ engine, so refusing probetype 1 here refused a CIP or PIP flight by way of the
58
+ engine this project tells a stranger to use, while stage 3 (V-PT) already
59
+ covered all four probetypes. Five sites separate probetype 1 from probetype 2
60
+ and each is now ported and cited in place: the ``particle_time`` source for
61
+ ``image_time_hhmmssall`` (``:758-759``), the ``'D'`` DOF-overload mark
62
+ (``:975-977``), the ABSENCE of any counter-rollover correction (``:1025-1029``
63
+ has arms for probetypes 2 and 0 only), the ABSENCE of the 0.8/1.0 s dead-time
64
+ cap (``:1118`` gates it ``probetype==2``), and the count-ratio live-time
65
+ fraction ``TotalPC1./TotalPC2`` clamped at 1 (``:1931-1958``) in place of
66
+ ``1 - dead_time``. The tail block is Octave-goldened; the other four are
67
+ branch structure read from the source. A whole-file probetype-1 differential
68
+ has not been run.
69
+
70
+ **Extended to probetypes 0 (2DC/2DP) and 3 (Fast2DC) on 2026-09-23** (with the CIP pipeline).
71
+ Their record-loop branches, each cited in place: ``parent_rec_num`` and the
72
+ record-start dead time (``:945-947``, ``:1111-1113``), the SEA-convention overload
73
+ zeroing (``:964-966``), the skipped ``Particle_number_all`` read (``:969-973``), and
74
+ probetype 0's absolute-time ``int_arr`` with its ``2^24`` rollback (``:984-985``,
75
+ ``:1027-1028``; Fast2DC takes the differenced arm and no rollback). The two latent
76
+ undefined-variable defects come across preserved: a probetype-0 run dies on
77
+ ``int_arr2`` at ``:1311`` under ``iaThreshType == 2`` (measured under Octave) and on
78
+ ``int_arr3`` with reacceptance on, and the port raises at both. Validated against the
79
+ unmodified v3.5 ``sizeDist.m`` under Octave on synthetic 2DC and Fast2DC inputs built so
80
+ each branch changes a written number (``run_v35_probetype03_sizedist_bank.py``; each
81
+ branch's mutation fails ``tests/test_v35_sizedist_probetype03.py``) -- layer 2, and
82
+ synthetic: the held real files (a 1995 ACE-1 2DC/2DP RAF file, reader checked only; a
83
+ CAESAR 2024 Fast-2DC file) have not been run through this stage in a validated way.
84
+
85
+ PECAN (``getPECANparams`` missing from both vendored trees) and
86
+ ``save_workspace_mat`` (a ~380 MB whole-workspace ``.mat`` dump) are refused
87
+ for the same reason the v3.1.4 port refuses them -- see
88
+ the module docstring of the v3.1.4 validation engine's ``sizedist`` (not included in this package).
89
+
90
+ **No FidelityProfile / no "tree" parameter, deliberately.** v3.5 has exactly
91
+ one source tree -- there is no v3.5 analogue of the ORACLES-variant tree's
92
+ ORACLES-only fork (established when the SPEC reader was ported, restated here
93
+ because it decides this module's whole signature). So this driver's positional signature matches
94
+ v3.5's ``sizeDist.m`` *exactly*, including ``iaThreshType``,
95
+ ``iCreateAspectRatio``, ``iCreateBad`` and ``iSaveIntArrSV`` as required
96
+ positional arguments (stock's own shape, unchanged by the v3.5 diff) rather
97
+ than the keyword-defaulted style ``sizedist.run`` in the v3.1.4 validation engine (not included in
98
+ this package) uses to
99
+ paper over the "stock vs. production" ambiguity that v3.5 does not have.
100
+
101
+ **Reuse, not re-transcription, wherever the diff proves nothing changed.**
102
+ Everything below cites the exact v3.1.4/v3.5 line(s) that license it. Three
103
+ findings are
104
+ upstream *fixes*,
105
+ not defects:
106
+ v3.5 no longer loses the int16xdouble saturation on d_choice sizing
107
+ (im_width/im_length are cast to double before use), no longer scales an
108
+ already-scaled ``particle_diameter_AreaR``, and writes
109
+ ``mean_area_ratio``/the two aspect-ratio means/their three ``REJ_`` twins
110
+ **with** the transpose the v3.1.4 port's own docstring names as a defect.
111
+ A port that "preserved" any of the three here would be preserving a bug the
112
+ source no longer has, which is the wrong direction of infidelity. Two further
113
+ findings -- the ``re``/``REJ_re`` units label, ``'um'`` -> ``'mm'``, on an
114
+ unchanged microns-valued formula (preserved AS v3.5 has it, not corrected),
115
+ and :func:`fix_multiday_particle_times`'s "no crossover detected" path, which
116
+ leaves corrupt-looking particle times uncorrected with only a printed
117
+ diagnostic -- are read/measured gaps, not fixes. A third, the past-end-of-data
118
+ branch (``:1848-1875``), touches only good-side variables, so
119
+ ``bad_one_sec_ar`` keeps its own zero pre-allocation there rather than the NaN
120
+ a naive good/bad-symmetric loop would write -- caught only by the end-to-end
121
+ Octave comparison (``REJ_ar`` was the one variable that disagreed); the same
122
+ line is in v3.1.4, so the register records it as a both-releases finding.
123
+ """
124
+
125
+ from __future__ import annotations
126
+
127
+ import logging
128
+ import math
129
+ from dataclasses import dataclass, replace
130
+ from typing import cast
131
+
132
+ import numpy as np
133
+
134
+ from arrayprobe_uiops.matlab_compat import MatlabIndexError, datestr, mfind, mint32, msum, nansum
135
+ from arrayprobe_uiops.sample_area import calc_sa_randombins
136
+ from arrayprobe_uiops.sizedist_core import (
137
+ _REJ_ATTS,
138
+ _REJ_ORDER,
139
+ _VARS,
140
+ _VARS_ASPECT,
141
+ _VARS_INTARR,
142
+ _VARS_TAIL,
143
+ D_CHOICE,
144
+ GOOD_REJECT_CODES,
145
+ REJECT_CRITERION_CODES,
146
+ STOCK_REJECT,
147
+ _d_hypot,
148
+ _d_length,
149
+ _d_max,
150
+ _d_mean,
151
+ _d_minr,
152
+ _d_width,
153
+ _hhmmss_to_insec,
154
+ _insec_to_hhmmss,
155
+ _num2str,
156
+ _optional_parameters,
157
+ _process_population,
158
+ _reaccept_shattered,
159
+ _rollover_240000,
160
+ warn_suspect_rollover,
161
+ )
162
+
163
+ from . import lwc as _lwc
164
+ from . import ncio, provenance
165
+ from .particle_physics import single_area, single_mass, single_vt
166
+ from .pecan_params import pecan_intar_threshold, resolve_pecan_params
167
+
168
+ # Re-exported deliberately (the retracted 2D-S bin table): `scripts/run_flight.py` reaches
169
+ # `arrayprobe_uiops` only through the `uiops` selector, and the selector is keyed
170
+ # by the v3.1.4 port's own module names -- `probe_cases` has no v3.1.4
171
+ # counterpart, so it is not in `uiops.CATALOGUE` and cannot be. Naming both
172
+ # symbols here makes the registry reachable as
173
+ # `_v35().module("sizedist").resolve_probe_case`, through a catalogued module,
174
+ # rather than by a direct `import arrayprobe_uiops.probe_cases` that would bypass
175
+ # the selector.
176
+ from .probe_cases import (
177
+ ACCEPTED_IA_THRESH_TYPES,
178
+ REQUIRED_IA_THRESH_TYPE,
179
+ UnknownProbeCase,
180
+ register_v35_2ds_ladder_fix,
181
+ resolve_probe_case,
182
+ resolve_shipped_probe_case,
183
+ )
184
+ from .sizedist_tables import (
185
+ InterarrivalThresholdSpec,
186
+ ProbeDefaults,
187
+ detect_habit_scheme,
188
+ flag_shattered_1hz,
189
+ probe_defaults,
190
+ reaccept_shattered_1hz,
191
+ select_interarrival_threshold,
192
+ )
193
+
194
+ __all__ = [
195
+ "TasMaxUndefined",
196
+ "run",
197
+ "UnsupportedProbetype",
198
+ "resolve_probe_case",
199
+ "resolve_shipped_probe_case",
200
+ "register_v35_2ds_ladder_fix",
201
+ "UnknownProbeCase",
202
+ "REQUIRED_IA_THRESH_TYPE",
203
+ "ACCEPTED_IA_THRESH_TYPES",
204
+ "AREA_RATIO_Z",
205
+ "AREA_RATIO_UPPER_CLIP",
206
+ "OVERLOAD_WARN_SEC",
207
+ "OVERLOAD_CAP_SEC",
208
+ "fix_multiday_particle_times",
209
+ "apply_flight_day_carryover",
210
+ "resolve_particle_blocks",
211
+ "overload_dead_time",
212
+ "d_choice_diameter",
213
+ "area_r_diameter",
214
+ "clip_area_ratio",
215
+ "apply_shattering",
216
+ "WRITER_GAPS",
217
+ ]
218
+
219
+ # Since 2026-09-15 the three ``fprintf``/``display`` reproductions
220
+ # below (``fix_multiday_particle_times``, ``overload_dead_time``,
221
+ # :func:`run`) now go through this module logger instead of a bare
222
+ # ``print``, so a library caller can capture or redirect them; the package
223
+ # ``__init__`` installs only a ``NullHandler``, so importing this module
224
+ # alone stays silent, same as before. ``arrayprobe.cli`` attaches a real
225
+ # handler for the console script, at the same default (INFO/WARNING)
226
+ # visibility a bare ``print`` always had.
227
+ _logger = logging.getLogger(__name__)
228
+
229
+
230
+ class TasMaxUndefined(NameError):
231
+ """``tasMax`` read where the case never assigns it (2DP), as MATLAB dies there."""
232
+
233
+
234
+ _TASMAX_UNDEFINED = (
235
+ "tasMax is not assigned for this project/probe case (2DP: v3.5 sizeDist.m:595-617 omits "
236
+ "it), and :771, :1026-1088 (the 2^32 x res/1e6/tasMax clock rollover), :1144 (area "
237
+ "reconstruction above tasMax) and :1926 read it, so MATLAB dies with \"'tasMax' "
238
+ "undefined\". No default exists: tasMax is the fastest airspeed the probe's clock samples "
239
+ "without skewed images, a property of the individual instrument's electronics that no "
240
+ "UIOPS release states for the 2DP. Pass tas_max=<m/s> "
241
+ "with the value for your probe."
242
+ )
243
+
244
+ _PECAN_UNDEFINED = (
245
+ "{case} calls getPECANparams(ddate, probename) (v3.5 sizeDist.m:164/:195), which ships in "
246
+ "no UIOPS release, so MATLAB dies there. Pass pecan_params=<file>: a CSV of spiral start_s, "
247
+ "end_s and intar_threshold_s (arrayprobe_uiops.pecan_params)."
248
+ )
249
+
250
+
251
+ class UnsupportedProbetype(NotImplementedError):
252
+ """Raised for a (campaign, probe) resolving to a probetype outside 0-3.
253
+
254
+ No v3.5 probetype is refused here: probetypes 0-3 are all ported (probetype 1
255
+ is CIP/PIP). The class remains for a
256
+ table row that names a probetype no stock release defines.
257
+
258
+ This docstring must track the module docstring's "Scope" section: it is the
259
+ half a reader meets first -- it is what an exception class is *for*. A version
260
+ that lagged the probetype-1 port by a day was copied onto two shared artifact
261
+ pages, which told readers that v3.5 stage 4 refuses probetypes
262
+ 0, 1 and 3 -- denying the engine capability the entire CIP result rests on.
263
+ It was caught by the artifact refresh, not by any test: no check compares a
264
+ docstring against the code it describes.
265
+ """
266
+
267
+
268
+ #: ``sizeDist.m:1162`` (v3.5) and ``:985`` (v3.1.4 stock) -- both stock trees
269
+ #: use ``.2``; the ORACLES-only ``.5`` override lives solely in
270
+ #: the ORACLES-variant tree, a v3.1.4-era fork with no v3.5 sibling (the SPEC
271
+ #: reader's "No FidelityProfile, deliberately" finding). Reused directly rather than
272
+ #: re-declared.
273
+ AREA_RATIO_Z = STOCK_REJECT.area_ratio_z
274
+
275
+
276
+ # ---------------------------------------------------------------------------
277
+ # Opt-in probe-clock offset (not MATLAB): particle times moved onto aircraft time
278
+ # ---------------------------------------------------------------------------
279
+
280
+ #: Where the per-second ``timehhmmss``/``tas`` rows came from, which decides whether a time
281
+ #: offset moves them too: ``"probe"`` (the probe's own record, stamped by the same off clock as
282
+ #: the particles: shifted) or ``"aircraft"`` (an aircraft file, already on aircraft time: not).
283
+ TAS_CLOCKS = ("probe", "aircraft")
284
+
285
+
286
+ @dataclass(frozen=True)
287
+ class TimeOffset:
288
+ """A whole-second correction ADDED to the probe clock's particle times, with its evidence.
289
+
290
+ Not part of v3.5's ``sizeDist``: an opt-in for a probe whose own clock is measured off
291
+ aircraft time (raw SPEC clock ~100-115 s and ~78 s off on two ARM ACE-ENA flights), so the
292
+ product inherits the error. ``seconds`` is whole: ``sizeDist`` files a particle by the whole
293
+ HHMMSS second of its ``Time`` (``hhmmss2insec`` of it, :func:`_diameters_and_mass`) and never
294
+ by ``particle_millisec``, so a fractional shift would have to re-split seconds the file does
295
+ not resolve -- refused rather than rounded. ``tas_clock`` is one of :data:`TAS_CLOCKS`.
296
+ """
297
+
298
+ seconds: int
299
+ evidence: str
300
+ tas_clock: str
301
+
302
+ @classmethod
303
+ def build(cls, seconds, evidence, tas_clock) -> TimeOffset:
304
+ if isinstance(seconds, bool) or not isinstance(
305
+ seconds, (int, float, np.integer, np.floating)) or not math.isfinite(
306
+ float(seconds)) or float(seconds) != int(float(seconds)):
307
+ raise ValueError("time_offset_s is a whole number of seconds (sizeDist files particles "
308
+ f"by whole HHMMSS seconds); got {seconds!r}")
309
+ if int(float(seconds)) == 0:
310
+ raise ValueError("time_offset_s = 0 changes nothing; leave it unset")
311
+ if abs(int(float(seconds))) >= 86400:
312
+ raise ValueError(f"time_offset_s is under one day in magnitude; got {seconds!r}")
313
+ if not isinstance(evidence, str) or not evidence.strip():
314
+ raise ValueError("time_offset_s needs time_offset_evidence: a non-empty statement of "
315
+ "how the offset was measured")
316
+ if tas_clock not in TAS_CLOCKS:
317
+ raise ValueError(f"time_offset_tas_clock is one of {TAS_CLOCKS} (whether the "
318
+ f"timehhmmss/tas rows share the particles' clock); got {tas_clock!r}")
319
+ return cls(int(float(seconds)), evidence.strip(), tas_clock)
320
+
321
+
322
+ def shift_hhmmss(hhmmss, seconds: int) -> np.ndarray:
323
+ """``hhmmss`` (HHMMSS, whole seconds of the day) moved by ``seconds``, wrapped onto one day.
324
+
325
+ The result reads as the clock would have read had it been right: a value moved past midnight
326
+ wraps to ``000000`` onward and one moved before it to ``2359xx``, so the midnight logic
327
+ downstream (:func:`fix_multiday_particle_times`, :func:`apply_flight_day_carryover`,
328
+ ``_rollover_240000``) sees the same form of data it sees from a real clock. Any fraction of a
329
+ second in the input is dropped, as ``hhmmss2insec`` drops it.
330
+ """
331
+ insec = _hhmmss_to_insec(hhmmss) + int(seconds)
332
+ return _insec_to_hhmmss(np.mod(insec, 86400.0))
333
+
334
+ #: ``sizeDist.m:1161`` (v3.5 only) -- ``area_ratio(area_ratio > 1.) = 1.;``,
335
+ #: added 2023-03-19 with no v3.1.4 analogue. Applied BEFORE the ``.2``
336
+ #: rejection test, so it can only ever raise a value into acceptance range,
337
+ #: never push one out of it.
338
+ AREA_RATIO_UPPER_CLIP = 1.0
339
+
340
+ #: ``sizeDist.m:1123-1128`` (v3.5), replacing v3.1.4's silent reset-to-zero
341
+ #: at the same site. Gated ``probetype == 2`` in the source; this module
342
+ #: enforces probetype 2 everywhere, so the gate is unconditional here.
343
+ OVERLOAD_WARN_SEC = 0.8
344
+ OVERLOAD_CAP_SEC = 1.0
345
+
346
+
347
+ # ---------------------------------------------------------------------------
348
+ # 1. The new multi-day particle-time fix (sizeDist.m ~:127-149, v3.5)
349
+ # ---------------------------------------------------------------------------
350
+
351
+
352
+
353
+ def _libm_pow(base: np.ndarray, exponent: float) -> np.ndarray:
354
+ """``base .^ exponent`` element by element through ``math.pow`` (the platform libm), so the
355
+ result does not depend on numpy's SIMD dispatch; NaN and inf propagate as in libm."""
356
+ def one(v: float) -> float:
357
+ try:
358
+ return math.pow(v, exponent)
359
+ except ValueError: # negative base, fractional exponent: numpy's nan
360
+ return math.nan
361
+ except OverflowError: # numpy, libm and MATLAB give inf (review F4)
362
+ return math.inf
363
+
364
+ flat = np.asarray(base, dtype=np.float64).ravel()
365
+ out = np.fromiter((one(float(v)) for v in flat), dtype=np.float64, count=flat.size)
366
+ return out.reshape(np.shape(base))
367
+
368
+ def fix_multiday_particle_times(image_time_hhmmssall: np.ndarray) -> tuple[np.ndarray, bool]:
369
+ """v3.5's replacement for the ``image_time_hhmmssall`` midnight rollover.
370
+
371
+ v3.1.4 (``:652-654``, reused here for ``timehhmmss`` itself via
372
+ :func:`arrayprobe_uiops.sizedist_core._rollover_240000` -- **unchanged in v3.5**, see
373
+ the module docstring) corrects a midnight crossing with
374
+ ``x(find(diff(x)<0)+1:end) += 240000``, which MATLAB's first-element colon
375
+ rule collapses to only the FIRST decrease. v3.5's own authors worked
376
+ around exactly that trap for the *particle*-time array by branching on
377
+ ``numel(find(...))`` explicitly, rather than by fixing the colon idiom:
378
+
379
+ * **Zero decreases**: no-op, unchanged.
380
+ * **Exactly one decrease**: apply the same ``+240000`` shift v3.1.4 always
381
+ applied -- identical result to the old code for this case.
382
+ * **More than one decrease**: scan the decreases in order for a genuine
383
+ day crossover -- ``x[d] > 230000 and x[d] - x[d+1] > 230000`` -- and
384
+ shift everything after the FIRST one found, then stop. If none of the
385
+ decreases looks like a real crossover (all of them look like corrupt,
386
+ briefly-reversed particle times instead), the array is returned
387
+ **unmodified** and a message is printed; see the v3.5 ``sizeDist`` driver design
388
+ record for why this is a real, if narrow, gap.
389
+
390
+ Returns ``(fixed_array, crossover_applied)``. Mutates a **copy**, unlike
391
+ :func:`arrayprobe_uiops.sizedist_core._rollover_240000`, which mutates in place --
392
+ the v3.5 source assigns back to the same name either way, so an in-place
393
+ mutation would be equally faithful; a copy is used here so a caller
394
+ cannot be surprised by an aliased array from an earlier stage.
395
+ """
396
+ x = np.array(image_time_hhmmssall, dtype=np.float64, copy=True)
397
+ decreases = np.flatnonzero(np.diff(x) < 0) # 0-based, matches MATLAB's find()-1
398
+ if decreases.size == 0:
399
+ return x, False
400
+ if decreases.size == 1:
401
+ warn_suspect_rollover(x, "3.5") # user caution, diagnostic only
402
+ x[decreases[0] + 1 :] += 240000.0
403
+ return x, True
404
+ for d in decreases:
405
+ if x[d] > 230000 and x[d] - x[d + 1] > 230000:
406
+ # User caution, diagnostic only: the test is applied to single values, so an all-ones
407
+ # header (316363 = 31:63:63, not a valid HHMMSS) passes it and moves every later
408
+ # particle; say so rather than let it pass silently.
409
+ if (x[d] // 100) % 100 >= 60 or x[d] % 100 >= 60:
410
+ _logger.warning(
411
+ "sizeDist crossover (engine 3.5): particle %d reads %06d, not a valid "
412
+ "HHMMSS, yet passes sizeDist.m:796-797's crossover test, so all %d later "
413
+ "particles are shifted +240000 and filed a day late -- reproduced "
414
+ "faithfully. To keep them, run the enhancement particle_time_glitch_fix "
415
+ "([enhancements] particle_time_glitch_fix = true) or a SODA-2 run.",
416
+ int(d) + 1, int(x[d]), int(x.size - d - 1))
417
+ x[d + 1 :] += 240000.0
418
+ return x, True
419
+ _logger.warning(
420
+ "Multiple instances of decreasing particle time were found,\n"
421
+ " but a crossover between dates was not detected."
422
+ )
423
+ return x, False
424
+
425
+
426
+ def apply_flight_day_carryover(
427
+ image_time_hhmmssall: np.ndarray, timehhmmss: np.ndarray
428
+ ) -> np.ndarray:
429
+ """v3.5 ``sizeDist.m:806-810``: *"Fix particle times if they do not span
430
+ multiple days but the flight file does - Added by Joe Finlon - 02/09/18"*.
431
+
432
+ When any flight time exceeds 240000 but no particle time does, every
433
+ particle time is shifted by +240000 (v3.1.4 ``sizeDist.m:662-663``).
434
+
435
+ A THIRD, independent particle-time correction, not caught when this
436
+ module's :func:`fix_multiday_particle_times` was first written from this
437
+ file's own diff/read summary -- found only by reading the source lines
438
+ immediately after it (``:786-805``) through to ``:829`` (the block-start
439
+ predicate) and noticing the ``if`` at ``:807`` does not belong to either
440
+ branch above it. It runs unconditionally after
441
+ :func:`fix_multiday_particle_times`, regardless of what that function did:
442
+ if the per-second ``timehhmmss`` (already midnight-corrected by
443
+ :func:`arrayprobe_uiops.sizedist_core._rollover_240000`, called before this) crossed
444
+ into the next day but the particle-time array's own ``diff`` never showed
445
+ a decrease at all -- possible when the particle stream itself starts
446
+ exactly at, or resumes after, the crossing with no reversal to detect --
447
+ then every particle time is shifted by ``+240000`` unconditionally, with
448
+ no idiom bug of its own (``numel(find(...))`` counts are scalars here,
449
+ not vectors sliced with the first-element colon rule the other two
450
+ corrections in this module inherit or avoid).
451
+
452
+ **Correction, made while writing this module's tests**: this block is
453
+ **byte-identical in v3.1.4** (``UIOPS-v3.1.4/.../sizeDist.m:661-664``,
454
+ same three lines, same comment) -- it is not new to v3.5 at all, unlike
455
+ :func:`fix_multiday_particle_times`'s own genuine v3.5 improvement (the
456
+ ``numel(find(...))`` branching). What IS new here is narrower than first
457
+ written: **the earlier translation never implemented it** -- it
458
+ reused ``_rollover_240000`` for ``image_time_hhmmssall`` (its own
459
+ ``:927``) but had no code for this second, independent ``if``. That is
460
+ a gap in the earlier translation, not a v3.5 finding, and this function
461
+ is kept as v3.5's own copy of the same three lines rather than left
462
+ unported a second time.
463
+ """
464
+ x = np.asarray(image_time_hhmmssall, dtype=np.float64)
465
+ tt = np.asarray(timehhmmss, dtype=np.float64)
466
+ if np.any(tt > 240000) and not np.any(x > 240000):
467
+ return x + 240000.0
468
+ return x.copy()
469
+
470
+
471
+ # ---------------------------------------------------------------------------
472
+ # 2. The new block-resolution logic (sizeDist.m ~:160-208, v3.5)
473
+ # ---------------------------------------------------------------------------
474
+
475
+
476
+ def resolve_particle_blocks(
477
+ image_time_hhmmssall: np.ndarray, num_of_part: int
478
+ ) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
479
+ """v3.5's replacement for the ``start_all``/``count_all`` resolution.
480
+
481
+ v3.1.4 finds one-second block starts in file order, sorts them by time,
482
+ de-duplicates by first-occurrence, and only THEN computes ``count_all``
483
+ as ``diff(start_all)`` on the final, sorted array -- valid only if the
484
+ sort left ``start_all`` monotonic, which a corrupted/out-of-order
485
+ particle-time series need not. A negative count from a non-monotonic
486
+ ``diff`` is clamped to 1, silently under-counting the block.
487
+
488
+ v3.5 (02/13/19) computes ``count_all`` ONCE, in original file order
489
+ (where ``start_all`` is inherently increasing, since it comes from
490
+ ``find`` on a monotonically-scanned buffer), and carries that same
491
+ ``count_all`` through every later sort/filter/dedupe step by index --
492
+ never recomputing it from a ``diff`` that could go negative. It also:
493
+
494
+ * widens the block-start predicate from ``diff(...)>0`` to
495
+ ``diff(...)~=0``, so a DECREASE (as well as an increase) in particle
496
+ time starts a new block -- corrupt/out-of-order particle times are,
497
+ unlike v3.1.4, not silently absorbed into the previous block;
498
+ * inserts a corrupt-time-removal pass, active only when the
499
+ chronologically-first block is not also the file-order-first block
500
+ (``newindexofsort(1) ~= 1``): it keeps a sorted-order position only
501
+ when the NEXT position in sorted order is exactly one more in file
502
+ order (``newindexofsort(k+1) - newindexofsort(k) == 1``), i.e. only
503
+ where sorting by time reproduces a genuinely contiguous run of file
504
+ order -- dropping isolated, out-of-place blocks a real day crossing or
505
+ clock glitch can produce.
506
+
507
+ Returns ``(starttime, start_all, count_all)`` -- ``start_all`` 0-based,
508
+ ready to index the proc file exactly as :func:`resolve_particle_blocks`'s
509
+ caller does.
510
+ """
511
+ insec = _hhmmss_to_insec(image_time_hhmmssall)
512
+ startindex = np.concatenate([[True], np.diff(insec) != 0]) # v3.5: != 0, not > 0
513
+ starttime = image_time_hhmmssall[startindex]
514
+ start_all = mfind(startindex) - 1 # 0-based, file order (inherently increasing)
515
+ count_all = np.concatenate([np.diff(start_all), [num_of_part - start_all[-1]]])
516
+
517
+ order = np.argsort(starttime, kind="stable")
518
+ starttime = starttime[order]
519
+ start_all = start_all[order]
520
+ count_all = count_all[order]
521
+
522
+ if order[0] != 0:
523
+ keep = []
524
+ k = 0
525
+ n = len(order)
526
+ while k < n - 1:
527
+ if k == 0 and order[k] == 0:
528
+ keep.append(k)
529
+ elif k > 0 and order[k + 1] - order[k] == 1:
530
+ keep.append(k)
531
+ k += 1
532
+ keep_idx = np.asarray(keep, dtype=np.int64)
533
+ starttime = starttime[keep_idx]
534
+ start_all = start_all[keep_idx]
535
+ count_all = count_all[keep_idx]
536
+
537
+ if starttime.size:
538
+ keep_first = np.concatenate([[True], np.diff(starttime) != 0])
539
+ starttime = starttime[keep_first]
540
+ start_all = start_all[keep_first]
541
+ count_all = count_all[keep_first]
542
+ count_all = count_all.copy()
543
+ count_all[count_all < 0] = 1
544
+ return starttime, start_all, count_all
545
+
546
+
547
+ # ---------------------------------------------------------------------------
548
+ # 3. The overload dead-time cap (sizeDist.m ~:1120-1128, v3.5; probetype==2)
549
+ # ---------------------------------------------------------------------------
550
+
551
+
552
+ def overload_dead_time(
553
+ int_arr: np.ndarray, dof_overload: np.ndarray, probetype: int = 2
554
+ ) -> float:
555
+ """v3.1.4 ``:813`` / v3.5 ``:1116-1126``, the ``else`` arm's ``time_interval72``.
556
+
557
+ v3.1.4 computed the same sum and silently reset it to 0 whenever it
558
+ exceeded 1 second ("EXPERIMENTAL correction... Joe Finlon 02/09/18").
559
+ v3.5 instead warns above 0.8 s and only caps (to 1.0, not 0.0) above
560
+ 1.0 s -- real overload time under 1 s reaches the file where v3.1.4
561
+ discarded it whenever the sum passed 1 s at all.
562
+
563
+ **The warn-and-cap is gated ``probetype==2`` at v3.5 ``:1118``**, inside an
564
+ ``else`` arm that probetypes 1 AND 2 both reach (``:1111``'s ``if`` takes
565
+ probetypes 0 and 3 down the ``rec_start`` path instead). So a probetype-1
566
+ (CIP/PIP) run takes the bare ``sum(int_arr(DMT_DOF_SPEC_OVERLOAD~=0))`` of
567
+ ``:1116`` with **no warning and no cap** -- a probetype-1 second whose
568
+ overload sum exceeds 1 s writes that value through, where the same sum on a
569
+ 2D-S is clamped to 1. Ported as a gate, not "fixed" to apply everywhere.
570
+ ``probetype`` defaults to 2 so existing probetype-2 call sites are
571
+ unchanged.
572
+ """
573
+ total = float(msum(int_arr[dof_overload != 0]))
574
+ if probetype == 2 and total > OVERLOAD_WARN_SEC:
575
+ _logger.warning(
576
+ "Sum of overloaded particles (%.2f sec) exceeds "
577
+ "%s sec. Use caution when interpreting results.",
578
+ total, OVERLOAD_WARN_SEC,
579
+ )
580
+ if total > OVERLOAD_CAP_SEC:
581
+ total = OVERLOAD_CAP_SEC
582
+ return total
583
+
584
+
585
+ # ---------------------------------------------------------------------------
586
+ # 3b. d_choice diameters (the int16 diameter saturation no longer reproduces), and
587
+ # particle_diameter_AreaR (the double-scaled area-ratio concentration no longer reproduces)
588
+ # ---------------------------------------------------------------------------
589
+
590
+
591
+ def d_choice_diameter(d_choice, im_length, im_width, diodesize, minr):
592
+ """v3.5 ``sizeDist.m:1054-1066`` (stock v3.1.4 ``:876-890``).
593
+
594
+ **What v3.5 changed.** v3.5 adds ``im_width = double(netcdf.getVar(...))`` /
595
+ ``im_length = double(...)`` (``:941-942``) immediately before this
596
+ computation; stock keeps them the file's native ``int16`` and multiplies
597
+ in place -- a bug the earlier translation preserves (upstream finding: the int16 diameter
598
+ saturation): ``int16 x double``
599
+ saturation collapses ``particle_diameter_minR`` toward zero for
600
+ ``d_choice`` 1, 2, 3 and 5). Casting to double first removes the integer
601
+ dominance that causes it, so **the saturation does not reproduce under v3.5**.
602
+
603
+ Implemented as exactly that precondition and nothing else:
604
+ :func:`arrayprobe.matlab_compat.mmul`/``mpow``/``mmax`` already dispatch
605
+ on the *actual* dtype of their arguments -- integer-dominant only when an
606
+ operand really is an integer array -- so calling
607
+ the earlier translation's own ``_d_length`` &c. on ``float64`` inputs
608
+ reuses that arithmetic correctly with no new saturating-arithmetic code
609
+ of its own. ``d_choice == 6`` (the default) is unaffected either way: it
610
+ reads ``image_diam_minR`` straight from the file, untouched by the cast.
611
+ """
612
+ length64 = np.asarray(im_length, dtype=np.float64)
613
+ width64 = np.asarray(im_width, dtype=np.float64)
614
+ fn = {
615
+ 1: _d_length, 2: _d_width, 3: _d_mean,
616
+ 4: _d_hypot, 5: _d_max, 6: _d_minr,
617
+ }.get(d_choice)
618
+ if fn is None:
619
+ raise ValueError(f"sizeDist v3.5: d_choice must be 1-6, got {d_choice!r}")
620
+ return fn(length64, width64, diodesize, np.asarray(minr, dtype=np.float64))
621
+
622
+
623
+ def area_r_diameter(image_diam_areaR: np.ndarray) -> np.ndarray:
624
+ """v3.5 ``sizeDist.m:954-956`` vs. stock v3.1.4 ``:783``.
625
+
626
+ **What v3.5 changed.** Stock v3.1.4 reads ``particle_diameter_AreaR`` from the
627
+ file and multiplies it by ``diodesize`` a SECOND time -- a bug the earlier
628
+ translation preserves (upstream finding: the double-scaled area-ratio
629
+ concentration; ``:669`` in the line numbering of the production-configuration variant of
630
+ ``sizeDist.m``, not shipped): ``imgProc_sm.m`` already writes it scaled, so the second
631
+ scaling is a 100x-too-small double-scale for a 2D-S, and the consequence
632
+ is total (``conc_AreaR`` identically zero wherever finite).
633
+ v3.5 comments the multiply out (``%particle_diameter_AreaR
634
+ = particle_diameter_AreaR * diodesize; % Removed/ not needed (see
635
+ imgProc_sm variable reference) ~ Joe Finlon 3/4/19``) -- an independent
636
+ upstream fix of the exact defect this project documents, the same shape
637
+ as the habit-'C' case. **The double scaling does
638
+ not reproduce under v3.5.** This function is the identity: there is no
639
+ MATLAB operation left here to transcribe.
640
+ """
641
+ return np.asarray(image_diam_areaR, dtype=np.float64)
642
+
643
+
644
+ def clip_area_ratio(area_ratio: np.ndarray) -> np.ndarray:
645
+ """v3.5 ``sizeDist.m:1161`` -- ``area_ratio(area_ratio > 1.) = 1.;``,
646
+ "Added by Joe Finlon 03/19/23". Absent from stock v3.1.4, which lets
647
+ ``area_ratio`` exceed 1 (a geometrically impossible value the ``.2``
648
+ reject test never filters, since it only rejects *small* ratios). Runs
649
+ immediately before that reject test; this function is only the clip,
650
+ using :data:`AREA_RATIO_UPPER_CLIP`.
651
+ """
652
+ out = np.asarray(area_ratio, dtype=np.float64).copy()
653
+ out[out > AREA_RATIO_UPPER_CLIP] = AREA_RATIO_UPPER_CLIP
654
+ return out
655
+
656
+
657
+ # ---------------------------------------------------------------------------
658
+ # 4. Reacceptance dispatch -- the three loops, two behaviours
659
+ # ---------------------------------------------------------------------------
660
+
661
+
662
+ @dataclass(frozen=True)
663
+ class _ReaccptCfg:
664
+ """Adapts :class:`~.sizedist_tables.ProbeDefaults`' field names to what
665
+ :func:`arrayprobe_uiops.sizedist_core._reaccept_shattered` reads off its ``cfg``."""
666
+
667
+ reaccpt_d: float
668
+ reaccpt_max_ia: float
669
+
670
+
671
+ def _reaccpt_cfg(cfg: ProbeDefaults) -> _ReaccptCfg:
672
+ return _ReaccptCfg(reaccpt_d=cfg.reaccptD, reaccpt_max_ia=cfg.reaccptMaxIA)
673
+
674
+
675
+ def _auto_reject_to_chars(auto_reject: np.ndarray) -> np.ndarray:
676
+ return np.array([chr(int(c)) for c in auto_reject], dtype="<U1")
677
+
678
+
679
+ def _auto_reject_from_chars(chars: np.ndarray, dtype) -> np.ndarray:
680
+ return np.array([ord(c) for c in chars], dtype=dtype)
681
+
682
+
683
+ def apply_shattering(
684
+ *,
685
+ ia_thresh_type: int,
686
+ cfg: ProbeDefaults,
687
+ spec: InterarrivalThresholdSpec,
688
+ i: int,
689
+ auto_reject: np.ndarray,
690
+ int_arr: np.ndarray,
691
+ int_arr2: np.ndarray | None,
692
+ int_arr3: np.ndarray | None,
693
+ particle_diameter_minR: np.ndarray,
694
+ start: int,
695
+ count: int,
696
+ intar_threshold: np.ndarray | None = None,
697
+ ) -> np.ndarray:
698
+ """Dispatch to whichever of the THREE reacceptance loops this second's
699
+ ``ia_thresh_type`` selects, mutating and returning ``auto_reject``.
700
+
701
+ **This function IS the trap the brief calls "the most important thing in
702
+ this brief," made explicit as code.** v3.5's ``sizeDist.m`` carries three
703
+ structurally similar shattering blocks that do NOT all behave the same:
704
+
705
+ * ``ia_thresh_type == 1`` (``:1213``) and ``== 2`` (``:1346``) both scan
706
+ a colon range from ``find(rBegin)`` to ``find(rEnd)`` -- MATLAB's first-element colon
707
+ rule collapses this to the FIRST shattering event only, the same
708
+ preserved defect documented at v3.1.4 ``sizeDist.m:1036``,
709
+ ``:1169``. **Reused verbatim** via
710
+ :func:`arrayprobe_uiops.sizedist_core._reaccept_shattered` -- not re-transcribed,
711
+ since the block is byte-for-byte the same idiom v3.1.4 already has and
712
+ already tests. Regression tests:
713
+ ``TestThreeLoopsTwoBehaviours::test_type1_and_type2_use_the_v314_preserved_bug_reaccept_shattered``.
714
+ * ``ia_thresh_type == 3`` (``:1416-1419``, "JF 11/5/25") is NEW in v3.5
715
+ and was deliberately rewritten to scan
716
+ from the first ``rBegin`` index to the last ``rEnd`` index
717
+ (v3.5 ``sizeDist.m:1419``) -- one continuous bracket spanning
718
+ EVERY shattering event in the second, not just the first. Uses
719
+ :func:`~.sizedist_tables.reaccept_shattered_1hz`, which
720
+ implements exactly this bracketed scan. Regression test:
721
+ ``TestThreeLoopsTwoBehaviours::test_type3_uses_the_fixed_bracketed_reaccept``.
722
+ * ``TestThreeLoopsTwoBehaviours::test_the_two_conventions_differ_on_the_same_second``
723
+ asserts, on one synthetic second carrying two separate shattering
724
+ events, that dispatching it through type 1/2 reaccepts nothing from the
725
+ second event while dispatching the SAME data through type 3 does --
726
+ the two conventions provably differing within the same file, as the
727
+ brief requires.
728
+ """
729
+ def _refuse_missing_int_arr3(line: int) -> None:
730
+ # int_arr3 is None only on probetype 0 (see _interarrival), where MATLAB never
731
+ # assigns it, so the block about to read it dies there. Refused, never invented.
732
+ if int_arr3 is None:
733
+ raise NotImplementedError(
734
+ f"v3.5 sizeDist.m:{line} reads int_arr3, which :1004-1018 builds only for "
735
+ "probetype != 0: this probetype-0 run with reaccptShatrs=1 dies in MATLAB "
736
+ "with \"'int_arr3' undefined\".")
737
+
738
+ if ia_thresh_type == 0:
739
+ return auto_reject # :1179's `if iaThreshType==1...`/`==2`/`==3` all
740
+ # false; neither of the three blocks runs (measured for v3.1.4 on a
741
+ # 2DC fixture, restated here for v3.5's identical gating -- see
742
+ # arrayprobe.sizedist.run's own docstring for that measurement).
743
+
744
+ if ia_thresh_type == 1:
745
+ if not (cfg.applyIntArrThresh and spec.ia_thresh_file not in (None, "NONE")):
746
+ return auto_reject
747
+ # Invariant: with iaThreshType == 1 and one argument, select_interarrival_threshold
748
+ # hands back varargin{1} itself, the threshold file's name (sizeDist.m:1179 opens it).
749
+ ia_thresh_path = cast(str, spec.ia_thresh_file)
750
+ with ncio.open(ia_thresh_path, "nowrite") as ia_nc:
751
+ ia_thresh = ia_nc.get_var(
752
+ ia_nc.inq_var_id("threshold"), start, count
753
+ ).reshape(-1)
754
+ if len(int_arr) == 1 and int_arr[0] <= ia_thresh[0]:
755
+ auto_reject[0] = ord("S")
756
+ else:
757
+ if int_arr[0] <= ia_thresh[0]:
758
+ auto_reject[0] = ord("S")
759
+ hits = np.flatnonzero(int_arr[1:] <= ia_thresh[1:]) + 1
760
+ for ix in hits:
761
+ auto_reject[ix - 1 : ix + 1] = ord("S")
762
+ if cfg.reaccptShatrs:
763
+ _refuse_missing_int_arr3(1204)
764
+ _reaccept_shattered(
765
+ auto_reject, int_arr, int_arr3, ia_thresh,
766
+ particle_diameter_minR, _reaccpt_cfg(cfg),
767
+ )
768
+ return auto_reject
769
+
770
+ if ia_thresh_type == 2:
771
+ if not cfg.applyIntArrThresh:
772
+ return auto_reject
773
+ if not cfg.intar_threshold_defaulted and intar_threshold is None:
774
+ # (PECAN assigns it through its spiral loop, supplied as `intar_threshold`.)
775
+ # The case sets applyIntArrThresh = 1 but never assigns intar_threshold, so the
776
+ # block's first read of intar_threshold(i) is where MATLAB dies: :1312 when int_arr2
777
+ # is non-empty, else :1317 for a one-particle second, else :1320 (Octave 11.3 on
778
+ # GPM/2DS and IMPACTS/2DS: "'intar_threshold' undefined near line 1320").
779
+ has_int_arr2 = int_arr2 is not None and int_arr2.size > 0
780
+ line = 1312 if has_int_arr2 else 1317 if len(int_arr) == 1 else 1320
781
+ raise NotImplementedError(
782
+ f"v3.5 sizeDist.m:{line} reads intar_threshold(i), which this project/probe "
783
+ "case never assigns although it sets applyIntArrThresh = 1: with "
784
+ "iaThreshType = 2 MATLAB dies with \"'intar_threshold' undefined\". "
785
+ "Refused, never invented.")
786
+ # `intar_threshold(i)`: the case's constant every second, except under PECAN, where a
787
+ # supplied parameter file's spirals set it per second (pecan_params.py, :160-172).
788
+ thresh_i = (cfg.defaultIntArrThresh if intar_threshold is None
789
+ else float(intar_threshold[i]))
790
+ ia_thresh = np.full(count, thresh_i)
791
+ if int_arr2 is not None and int_arr2.size and int_arr2[0] <= thresh_i:
792
+ auto_reject[-1] = ord("S")
793
+ if len(int_arr) == 1 and int_arr[0] <= thresh_i:
794
+ auto_reject[0] = ord("S")
795
+ else:
796
+ if int_arr[0] <= thresh_i:
797
+ auto_reject[0] = ord("S")
798
+ hits = np.flatnonzero(int_arr[1:] <= thresh_i) + 1
799
+ for ix in hits:
800
+ auto_reject[ix - 1 : ix + 1] = ord("S")
801
+ if cfg.reaccptShatrs:
802
+ _refuse_missing_int_arr3(1337)
803
+ _reaccept_shattered(
804
+ auto_reject, int_arr, int_arr3, ia_thresh,
805
+ particle_diameter_minR, _reaccpt_cfg(cfg),
806
+ )
807
+ return auto_reject
808
+
809
+ if ia_thresh_type == 3:
810
+ if not (cfg.applyIntArrThresh and spec.iat_thresh is not None):
811
+ return auto_reject
812
+ thresh_i = float(spec.iat_thresh[i])
813
+ int_arr_list = np.asarray(int_arr, dtype=np.float64).tolist()
814
+ chars = _auto_reject_to_chars(auto_reject)
815
+ chars = flag_shattered_1hz(int_arr_list, thresh_i, auto_reject=chars.tolist())
816
+ if cfg.reaccptShatrs:
817
+ _refuse_missing_int_arr3(1403)
818
+ assert int_arr3 is not None # the line above raises otherwise
819
+ chars, _e_index = reaccept_shattered_1hz(
820
+ chars.tolist(), int_arr_list,
821
+ np.asarray(int_arr3, dtype=np.float64).tolist(),
822
+ np.asarray(particle_diameter_minR, dtype=np.float64).tolist(), thresh_i,
823
+ reaccptD=cfg.reaccptD, reaccptMaxIA=cfg.reaccptMaxIA,
824
+ )
825
+ return _auto_reject_from_chars(chars, auto_reject.dtype)
826
+
827
+ raise ValueError(f"iaThreshType is 0, 1, 2 or 3 in v3.5's sizeDist.m; got {ia_thresh_type!r}")
828
+
829
+
830
+ # ---------------------------------------------------------------------------
831
+ # 5. The writer -- NETCDF4, renamed/added attributes, iat_threshold, and the
832
+ # three fixed transposes
833
+ # ---------------------------------------------------------------------------
834
+
835
+ #: Declared gaps, same convention as ``arrayprobe_uiops.spec.WRITER_GAPS``:
836
+ #: ``arrayprobe_uiops.ncio.def_var`` (the project's single netCDF encoder) exposes
837
+ #: no ``deflate`` parameter, and extending it is a change to
838
+ #: ``src/arrayprobe/``, out of scope while a regression run is live in that
839
+ #: tree at the time. Deflate is lossless -- ``TestWriterGaps`` proves that
840
+ #: rather than asserting it -- so the port's v3.5 files are NETCDF4 but
841
+ #: uncompressed.
842
+ WRITER_GAPS = {
843
+ "deflate": (
844
+ "sizeDist.m gains `netcdf.defVarDeflate(..., true, true, 9)` on every "
845
+ "variable (v3.5 diff). `ncio.def_var` has no deflate parameter; "
846
+ "closes with one keyword there. Lossless -- values are unaffected."
847
+ ),
848
+ }
849
+
850
+ _NOT_TRANSPOSED_V314 = frozenset(
851
+ {"mean_area_ratio", "mean_aspect_ratio_rectangle", "mean_aspect_ratio_ellipse"}
852
+ )
853
+
854
+
855
+ def _vars_v35():
856
+ """v3.1.4's ``_VARS``/``_VARS_ASPECT``/``_REJ_ATTS`` with the one
857
+ attribute-text change v3.5 makes (``re``'s ``units`` -- ``:12`` below):
858
+ ``'um'`` -> ``'mm'`` (``sizeDist.m`` diff, ``varid12``/``varid32``). The
859
+ schema (names, dims, which vars exist under which flag) is otherwise
860
+ unchanged; only the ``re``/``REJ_re`` unit LABEL and the six transposes
861
+ (handled at the value-assembly step, not here) differ.
862
+
863
+ That diff is against the stock v3.1.4 MATLAB. The v3.1.4 *port's* own
864
+ tables already carry ``'mm'`` -- the ORACLES fork's label -- and
865
+ the v3.1.4 validation engine's ``sizedist.run(attribute_text=...)`` (not included in this
866
+ package) swaps in stock's ``'um'``
867
+ at write time (2026-09-13), so this patch is a no-op on today's tables.
868
+ It stays so v3.5's label never depends on that table's literal.
869
+ """
870
+ def _patch_units(defs):
871
+ out = []
872
+ for name, dims, atts in defs:
873
+ if name in ("re",):
874
+ atts = tuple(
875
+ ("units", "mm") if a == "units" else (a, v) for a, v in atts
876
+ )
877
+ out.append((name, dims, atts))
878
+ return tuple(out)
879
+
880
+ return _patch_units(_VARS), _VARS_ASPECT, _VARS_TAIL, _VARS_INTARR
881
+
882
+
883
+ def _rej_atts_v35():
884
+ atts = dict(_REJ_ATTS)
885
+ re_atts = atts["re"]
886
+ atts["re"] = tuple(("units", "mm") if a == "units" else (a, v) for a, v in re_atts)
887
+ return atts
888
+
889
+
890
+ def _write_v35(
891
+ mainf, out, num_bins, n_sec, infile, projectname, probename, sa_method,
892
+ d_choice, apply_int_arr_thresh, reaccpt_shatrs, cfg, i_create_bad,
893
+ i_create_aspect_ratio, i_save_int_arr_sv, attr_habit, iat_threshold,
894
+ software, creation_time, stamp_profile=None, tas_qc=None, area_ratio_z=None,
895
+ default_int_arr_thresh=None, time_offset=None,
896
+ ):
897
+ """v3.5 ``sizeDist.m:~2026-2450``. Structurally ``sizedist._write`` in the v3.1.4
898
+ validation engine (not included in this package),
899
+ with: ``netcdf.create(...,'NETCDF4')`` (done by the caller, at ``ncio.create``
900
+ time -- nothing to redo here), the renamed/added/dropped global attributes,
901
+ the new ``iat_threshold`` variable when ``iat_threshold is not None``, and
902
+ deflate declared as a gap (:data:`WRITER_GAPS`) rather than silently
903
+ dropped.
904
+ """
905
+ dim = {
906
+ "CIPcorrlen": mainf.def_dim("CIPcorrlen", num_bins),
907
+ "CIParealen": mainf.def_dim("CIParealen", 10),
908
+ "Time": mainf.def_dim("Time", n_sec),
909
+ "Habit": mainf.def_dim("Habit", 10),
910
+ }
911
+
912
+ g = ncio.get_constant("NC_GLOBAL")
913
+ mainf.put_att(g, "Software", software)
914
+ # 'Institution' is commented out in v3.5's own source (same hunk as the
915
+ # Software rewrite) -- dropped, not renamed.
916
+ mainf.put_att(
917
+ g, "Creation_Time",
918
+ creation_time if creation_time is not None else datestr(None, "yyyy/mm/dd HH:MM:SS"),
919
+ )
920
+ mainf.put_att(g, "Description", "Contains size distributions of particle "
921
+ "count, mass, etc. & various bulk properties.")
922
+ mainf.put_att(g, "Project", projectname)
923
+ mainf.put_att(g, "Data_Source", str(infile))
924
+ mainf.put_att(g, "Probe_Type", probename)
925
+ mainf.put_att(g, "Habit_Scheme", attr_habit)
926
+ sa_label = {0: "Center-in", 1: "Entire-in",
927
+ 2: "Using Heymsfield & Parrish (1978) correction"}
928
+ if sa_method in sa_label:
929
+ mainf.put_att(g, "SA Method", sa_label[sa_method])
930
+ if d_choice in D_CHOICE:
931
+ mainf.put_att(g, "Dmax Definition", D_CHOICE[d_choice][1])
932
+ if apply_int_arr_thresh and reaccpt_shatrs:
933
+ mainf.put_att(g, "Shattering Algorithm", "Applied w/ reacceptance of particles")
934
+ mainf.put_att(
935
+ g, "Reacceptance Criteria",
936
+ f"D > {_num2str(cfg.reaccptD * 1000)} um; inter-arrival "
937
+ f"< {_num2str(cfg.reaccptMaxIA)} sec",
938
+ )
939
+ elif apply_int_arr_thresh:
940
+ mainf.put_att(g, "Shattering Algorithm", "Applied without reacceptance of particles")
941
+ else:
942
+ mainf.put_att(g, "Shattering Algorithm", "Not applied")
943
+ mainf.put_att(
944
+ g, "Optional Parameters Saved",
945
+ _optional_parameters(i_create_bad, i_create_aspect_ratio, i_save_int_arr_sv),
946
+ )
947
+ # In-file provenance: arrayprobe_engine / arrayprobe_profile, not MATLAB output.
948
+ for name, value in provenance.engine_attrs(engine="3.5", profile=stamp_profile).items():
949
+ mainf.put_att(g, name, value)
950
+ # The airspeed data-quality record, written by default on this engine: which seconds
951
+ # were sized with a substituted or default TAS, and why. ``None`` (the run named no TAS
952
+ # source, so there is no record to state) writes nothing.
953
+ # Sorted, as the .tasqc.json sidecar is, so a re-run from the sidecar writes the same order.
954
+ for key, value in sorted((tas_qc or {}).items()):
955
+ mainf.put_att(g, f"{provenance.ATTR_PREFIX}{key}", value)
956
+ # The opt-in 'z' threshold (run()'s docstring), written only when set so the default
957
+ # file is byte-for-byte the one that was always written.
958
+ if area_ratio_z is not None:
959
+ mainf.put_att(g, f"{provenance.ATTR_PREFIX}area_ratio_z", float(area_ratio_z))
960
+ # The opt-in default inter-arrival threshold (run()'s docstring), likewise written only
961
+ # when set.
962
+ if default_int_arr_thresh is not None:
963
+ mainf.put_att(g, f"{provenance.ATTR_PREFIX}default_int_arr_thresh",
964
+ float(default_int_arr_thresh))
965
+ # The opt-in probe-clock offset (TimeOffset), likewise written only when set.
966
+ if time_offset is not None:
967
+ mainf.put_att(g, f"{provenance.ATTR_PREFIX}time_offset_s", float(time_offset.seconds))
968
+ mainf.put_att(g, f"{provenance.ATTR_PREFIX}time_offset_evidence", time_offset.evidence)
969
+ mainf.put_att(g, f"{provenance.ATTR_PREFIX}time_offset_tas_clock", time_offset.tas_clock)
970
+
971
+ vars_, vars_aspect, vars_tail, vars_intarr = _vars_v35()
972
+ defs = list(vars_)
973
+ if i_create_aspect_ratio:
974
+ defs += list(vars_aspect)
975
+ defs += list(vars_tail)
976
+ if i_create_bad:
977
+ by_name = {name: (dims, atts) for name, dims, atts in vars_ + vars_aspect + vars_tail}
978
+ rej_atts = _rej_atts_v35()
979
+ defs += [("REJ_" + name, by_name[name][0], rej_atts[name]) for name in _REJ_ORDER]
980
+ if i_save_int_arr_sv:
981
+ defs += list(vars_intarr)
982
+ if iat_threshold is not None:
983
+ defs.append((
984
+ "iat_threshold", ("Time",),
985
+ (("units", "s"), ("long_name",
986
+ "inter-arrival time threshold used to determine which particles "
987
+ "are likely shattered artifacts")),
988
+ ))
989
+
990
+ varid = {}
991
+ for name, dims, atts in defs:
992
+ varid[name] = mainf.def_var(name, "double", [dim[d] for d in dims])
993
+ for att, value in atts:
994
+ mainf.put_att(varid[name], att, value)
995
+
996
+ mainf.end_def()
997
+
998
+ for name in varid:
999
+ mainf.put_var(varid[name], np.asarray(out[name]))
1000
+
1001
+
1002
+ # ---------------------------------------------------------------------------
1003
+ # 6. The driver
1004
+ # ---------------------------------------------------------------------------
1005
+
1006
+
1007
+ def run(
1008
+ infile, outfile, tas, timehhmmss, probename, d_choice, sa_method, pres, temp,
1009
+ ia_thresh_type, i_create_aspect_ratio, i_create_bad, i_save_int_arr_sv,
1010
+ projectname, ddate, *varargin,
1011
+ software,
1012
+ probe_case=None,
1013
+ mmethod=0,
1014
+ mmethod_pow=0.0,
1015
+ area_ratio_z=None,
1016
+ default_int_arr_thresh=None,
1017
+ pecan_params=None,
1018
+ tas_max=None,
1019
+ octave_mean_extra=False,
1020
+ octave_colon=False,
1021
+ creation_time=None,
1022
+ progress=None,
1023
+ stamp_profile=None,
1024
+ tas_qc=None,
1025
+ time_offset_s=None,
1026
+ time_offset_evidence=None,
1027
+ time_offset_tas_clock=None,
1028
+ zero_sv_nan=False,
1029
+ ):
1030
+ """``sizeDist(infile, outfile, tas, timehhmmss, probename, d_choice,
1031
+ SAmethod, Pres, Temp, iaThreshType, iCreateAspectRatio, iCreateBad,
1032
+ iSaveIntArrSV, projectname, ddate, varargin)`` -- v3.5's own positional
1033
+ signature (unchanged from v3.1.4 stock; see the module docstring).
1034
+
1035
+ ``mmethod``/``mmethod_pow`` are NOT part of stock v3.5's signature -- they
1036
+ port Peter Brechner's ``Mmethod`` argument to his forked
1037
+ ``sizeDist_decibel3.m`` (``:1186-1211``), an opt-in flag defaulting to 0,
1038
+ stock v3.5's own habit M-D and textually the same code path this function
1039
+ always ran before ``mmethod`` existed --
1040
+ ``tests/test_held_back_modules_refuse_cleanly.py`` asserts the default never
1041
+ reaches ``mass_b26``.
1042
+ ``mmethod`` 1, 2 or 3 reaches ``arrayprobe_uiops.mass_b26``, which this
1043
+ release does not include because the method is not yet published. The
1044
+ import is lazy and guarded: with the module absent, ``mmethod`` 1-3
1045
+ refuses by name, so only ``mmethod=0`` runs.
1046
+
1047
+ ``software`` is required, no default -- v3.5 reads it from a
1048
+ ``version.txt`` beside the MATLAB source at runtime (``:2033-2035``,
1049
+ "Added dynamic software version to netCDF metadata"), the same cwd-relative,
1050
+ unchecked-``fopen`` pattern already found and named an upstream finding for
1051
+ ``read_binary_SPEC.m`` and ``imgProc_sm.m``. Reproducing the
1052
+ cwd-dependence itself would make this port's OUTPUT depend on where Python
1053
+ was started; naming the string explicitly instead makes the same fact
1054
+ recordable rather than accidental, the same choice ``arrayprobe_uiops.spec``
1055
+ already made for its own ``software``/``creation_time`` arguments.
1056
+
1057
+ ``tas_qc`` is the airspeed data-quality record
1058
+ (:func:`arrayprobe.tools.tas_sources.qc_record`), not a MATLAB argument: each key is
1059
+ written as an ``arrayprobe_<key>`` global attribute beside the engine attributes, so the
1060
+ file itself says which seconds were sized with a substituted or default TAS.
1061
+ ``None`` writes nothing; no variable changes either way.
1062
+
1063
+ ``area_ratio_z`` is NOT part of stock v3.5's signature either. ``None`` (default)
1064
+ keeps ``sizeDist.m:1162``'s literal ``.2`` through :data:`AREA_RATIO_Z`, so the path is
1065
+ textually the one that always ran (``tests/test_v35_area_ratio_z.py::
1066
+ TestDefaultIsBitIdentical``). A value in ``[0, 1]`` replaces only that literal: a particle
1067
+ whose clipped area ratio is below it is rejected as ``'z'``. ``0.0`` is the gate off (an
1068
+ area ratio is ``area / (pi/4 d^2)`` with ``area >= 0``, so never below 0, and NaN compares
1069
+ false; asserted against the Octave oracle, not assumed). Anything else raises. The
1070
+ oracle is named: the vendored ``sizeDist.m`` with that one literal changed in a
1071
+ shadowing copy (the Octave bank ``run_v35_area_ratio_z_bank.py``, dev repository only,
1072
+ ``tests/test_v35_area_ratio_z_oracle.py``). A run that sets it writes one global
1073
+ attribute, ``arrayprobe_area_ratio_z``; a run that does not writes nothing new.
1074
+
1075
+ ``default_int_arr_thresh`` is NOT part of stock v3.5's signature either. ``None``
1076
+ (default) keeps the case's own ``defaultIntArrThresh = <literal>`` assignment
1077
+ (``sizeDist.m:139-642``, e.g. ``:313`` for SOCRATES/2DS), so the path is textually the
1078
+ one that always ran. A finite value ``>= 0`` (seconds) replaces only that constant in
1079
+ the resolved ``ProbeDefaults``, after the switch or probe-case lookup. v3.5 reads
1080
+ ``defaultIntArrThresh`` in exactly one place: ``intar_threshold =
1081
+ ones(size(tas_time))*defaultIntArrThresh`` (e.g. ``:318``), which is read only by the
1082
+ ``iaThreshType == 2 && applyIntArrThresh`` block (``:1308-1338``). So the value is
1083
+ unused when ``iaThreshType`` is not 2, when the case sets ``applyIntArrThresh = 0``,
1084
+ and it does not rescue a case that never assigns ``intar_threshold`` (GPM/2DS,
1085
+ IMPACTS/2DS: still refused at the read site, as MATLAB dies there). A run that sets it
1086
+ writes the attribute ``arrayprobe_default_int_arr_thresh`` whether or not the gate used it;
1087
+ one that does not writes nothing new. Octave oracle: ``run_v35_default_int_arr_thresh_bank.py``.
1088
+
1089
+ ``pecan_params`` is NOT part of stock v3.5's signature either. The PECAN CIP and PIP
1090
+ cases call ``getPECANparams`` (``:164``, ``:195``), which ships in no release, so without
1091
+ it the run is refused as MATLAB dies there. A path to a parameter file (or a
1092
+ :class:`~arrayprobe_uiops.pecan_params.PecanParams`) supplies the call's three used outputs,
1093
+ and the case then runs exactly as MATLAB would with them: ``intar_threshold`` is the
1094
+ case's ``defaultIntArrThresh`` every second except inside a spiral, read only under
1095
+ ``iaThreshType == 2``. Refused on any other case. Format: ``pecan_params.py``.
1096
+
1097
+ ``tas_max`` is NOT part of stock v3.5's signature either. The 2DP case (``:595-617``)
1098
+ assigns no ``tasMax``, which ``:771``, ``:1026-1088``, ``:1144`` and ``:1926`` read, so
1099
+ without it the run is refused as MATLAB dies there (:class:`TasMaxUndefined`). A finite
1100
+ value ``> 0`` (m/s) is used as that case's ``tasMax``; there is no default. Refused on a
1101
+ case that assigns its own ``tasMax``. Neither keyword writes anything when unset.
1102
+
1103
+ ``time_offset_s`` is NOT part of stock v3.5's signature either: a whole number of seconds
1104
+ ADDED to every particle's ``Time``/``particle_time`` where it is read, for a probe whose own
1105
+ clock is measured off aircraft time (:class:`TimeOffset`). It needs
1106
+ ``time_offset_evidence`` (how it was measured) and ``time_offset_tas_clock``: ``"probe"``
1107
+ when ``timehhmmss``/``tas`` came from the probe's own record (same off clock: shifted too),
1108
+ ``"aircraft"`` when they came from an aircraft file (already aircraft time: left alone).
1109
+ Inter-arrival times are differences of ``Time_in_seconds`` and do not move. ``None``
1110
+ (default) leaves the path textually the one that always ran; a run that sets it writes
1111
+ ``arrayprobe_time_offset_s``, ``arrayprobe_time_offset_evidence`` and
1112
+ ``arrayprobe_time_offset_tas_clock``.
1113
+
1114
+ Probetypes 0-3 are supported -- see the module docstring's "Scope".
1115
+ Everything else this function refuses is refused explicitly, as an error
1116
+ naming the source line, never a silent fallback.
1117
+ """
1118
+ if ia_thresh_type not in (0, 1, 2, 3):
1119
+ raise ValueError(
1120
+ f"iaThreshType is 0, 1, 2 or 3 in v3.5's sizeDist.m; got {ia_thresh_type!r}"
1121
+ )
1122
+
1123
+ if area_ratio_z is not None:
1124
+ if isinstance(area_ratio_z, bool) or not (
1125
+ isinstance(area_ratio_z, (int, float, np.integer, np.floating))
1126
+ and math.isfinite(float(area_ratio_z)) and 0.0 <= float(area_ratio_z) <= 1.0):
1127
+ raise ValueError(
1128
+ "area_ratio_z replaces the literal .2 at v3.5 sizeDist.m:1162 and is a finite "
1129
+ f"number in [0, 1] (0 is the gate off); got {area_ratio_z!r}"
1130
+ )
1131
+ area_ratio_z = float(area_ratio_z)
1132
+
1133
+ if default_int_arr_thresh is not None:
1134
+ if isinstance(default_int_arr_thresh, bool) or not (
1135
+ isinstance(default_int_arr_thresh, (int, float, np.integer, np.floating))
1136
+ and math.isfinite(float(default_int_arr_thresh))
1137
+ and float(default_int_arr_thresh) >= 0.0):
1138
+ raise ValueError(
1139
+ "default_int_arr_thresh replaces the case's defaultIntArrThresh constant "
1140
+ "(v3.5 sizeDist.m:139-642, read through intar_threshold at :1308-1338) and "
1141
+ f"is a finite number of seconds >= 0; got {default_int_arr_thresh!r}"
1142
+ )
1143
+ default_int_arr_thresh = float(default_int_arr_thresh)
1144
+
1145
+ if tas_max is not None:
1146
+ if isinstance(tas_max, bool) or not (
1147
+ isinstance(tas_max, (int, float, np.integer, np.floating))
1148
+ and math.isfinite(float(tas_max)) and float(tas_max) > 0.0):
1149
+ raise ValueError(f"tas_max is an airspeed in m/s, finite and > 0; got {tas_max!r}")
1150
+ tas_max = float(tas_max)
1151
+ time_offset = None
1152
+ if time_offset_s is not None:
1153
+ time_offset = TimeOffset.build(time_offset_s, time_offset_evidence, time_offset_tas_clock)
1154
+ elif time_offset_evidence is not None or time_offset_tas_clock is not None:
1155
+ raise ValueError("time_offset_evidence/time_offset_tas_clock given without time_offset_s")
1156
+
1157
+ spec = select_interarrival_threshold(ia_thresh_type, varargin)
1158
+ if spec.too_many_inputs:
1159
+ _logger.warning("You have added too many inputs!")
1160
+
1161
+ tas = np.asarray(tas, dtype=np.float64).reshape(-1)
1162
+ timehhmmss = np.array(timehhmmss, dtype=np.float64).reshape(-1)
1163
+ pres = np.asarray(pres, dtype=np.float64).reshape(-1)
1164
+ temp = np.asarray(temp, dtype=np.float64).reshape(-1)
1165
+
1166
+ f = ncio.open(infile, "nowrite")
1167
+ try:
1168
+ # v3.5 sizeDist.m:100-108 -- `ncinfo(infile)` / `{pbpinfo.Variables.Name}`,
1169
+ # read here through `.dataset` deliberately: this is metadata
1170
+ # enumeration (variable NAMES), never data, so none of the
1171
+ # shape/orientation contract `.dataset`'s own docstring warns ported
1172
+ # call sites off of applies.
1173
+ var_names = list(f.dataset.variables.keys())
1174
+ i_new_habit, attr_habit = detect_habit_scheme(var_names)
1175
+
1176
+ if probe_case is None:
1177
+ cfg = probe_defaults(projectname, probename, version="3.5")
1178
+ else:
1179
+ # Opt-in, default-off (the retracted 2D-S bin table): a NAMED case replaces the switch's
1180
+ # lookup for this run, and nothing else about the driver changes --
1181
+ # `cfg` is the same ProbeDefaults record either way. `probe_case`
1182
+ # is None on every run that does not name one, so the stock path
1183
+ # above is bit-identical to what it always was
1184
+ # (tests/test_v35_probe_cases.py::TestDefaultIsBitIdentical).
1185
+ # Why a registry rather than a table entry, and why the ladder is
1186
+ # not "fixed" in V35_TABLES: arrayprobe_uiops/probe_cases.py.
1187
+ cfg = resolve_probe_case(probe_case).defaults
1188
+ pecan = None
1189
+ if cfg.calls_getPECANparams:
1190
+ if pecan_params is None:
1191
+ raise NotImplementedError(
1192
+ _PECAN_UNDEFINED.format(case=f"{projectname!r}/{probename!r}"))
1193
+ pecan = resolve_pecan_params(pecan_params, ddate=ddate, probename=probename)
1194
+ elif pecan_params is not None:
1195
+ raise ValueError(
1196
+ f"pecan_params replaces getPECANparams, which only the PECAN CIP/PIP cases "
1197
+ f"call; {projectname!r}/{probename!r} does not")
1198
+ if tas_max is not None:
1199
+ if cfg.tasMax is not None:
1200
+ raise ValueError(
1201
+ f"tas_max supplies a tasMax the case leaves unassigned (2DP); "
1202
+ f"{projectname!r}/{probename!r} assigns tasMax = {cfg.tasMax:g}")
1203
+ cfg = replace(cfg, tasMax=tas_max)
1204
+ if cfg.probetype not in (0, 1, 2, 3):
1205
+ raise UnsupportedProbetype(
1206
+ f"{projectname!r}/{probename!r} (v3.5) is probetype {cfg.probetype}. "
1207
+ "This driver ports probetypes 0 (2DC/2DP), 1 (CIP/PIP), "
1208
+ "2 (2D-S/HVPS/3VCPI) and 3 (Fast2DC) and no other; see the "
1209
+ "module docstring's Scope section."
1210
+ )
1211
+ if default_int_arr_thresh is not None:
1212
+ # Opt-in, default-off: only the constant changes. `intar_threshold_defaulted`
1213
+ # is the case's own (whether it assigns intar_threshold at all), so a case
1214
+ # MATLAB dies on stays refused rather than invented.
1215
+ cfg = replace(cfg, defaultIntArrThresh=default_int_arr_thresh)
1216
+
1217
+ mainf = ncio.create(outfile, "clobber", format="NETCDF4")
1218
+ try:
1219
+ out = _run(
1220
+ f, mainf, infile, tas, timehhmmss, probename, d_choice, sa_method,
1221
+ pres, temp, projectname, ddate, ia_thresh_type, spec, cfg,
1222
+ i_new_habit, attr_habit, bool(i_create_bad),
1223
+ bool(i_create_aspect_ratio), bool(i_save_int_arr_sv),
1224
+ octave_mean_extra, octave_colon, software, creation_time, progress,
1225
+ mmethod, mmethod_pow, stamp_profile=stamp_profile, tas_qc=tas_qc,
1226
+ area_ratio_z=area_ratio_z, default_int_arr_thresh=default_int_arr_thresh,
1227
+ pecan=pecan,
1228
+ time_offset=time_offset,
1229
+ zero_sv_nan=zero_sv_nan,
1230
+ )
1231
+ finally:
1232
+ mainf.close()
1233
+ finally:
1234
+ f.close()
1235
+ return out
1236
+
1237
+
1238
+ def _read_block(gv, i, old_style, i_create_aspect_ratio, probetype, total_pc1, total_pc2):
1239
+ """Phase 1 of `_run`'s per-second body: the particle-block reads (v3.5 `:925-977`).
1240
+
1241
+ Extracted verbatim from `_run` (V35_CODE_REVIEW item 1): the same `gv` reads in the
1242
+ same order, the same casts, the same in-place writes to `total_pc1[i]`/`total_pc2[i]`
1243
+ (the caller's arrays), and every array returned is the object `_run` bound before.
1244
+ """
1245
+ auto_reject = gv("image_auto_reject").copy()
1246
+ # -- v3.5 fix for the int16 diameter saturation: cast to double BEFORE the d_choice arithmetic,
1247
+ # so `mmul`/`mdiv`/`mpow`/`mmax` (matlab_compat's saturating ops)
1248
+ # never see an int16 operand and never saturate.
1249
+ im_width = gv("image_width").astype(np.float64)
1250
+ im_length = gv("image_length").astype(np.float64)
1251
+ area = gv("image_area").astype(np.float64).copy()
1252
+ perimeter = gv("image_perimeter")
1253
+ habit1 = gv("holroyd_habit")
1254
+ centerin = gv("image_center_in")
1255
+ entirein = gv("image_touching_edge")
1256
+
1257
+ if i_create_aspect_ratio:
1258
+ with np.errstate(divide="ignore", invalid="ignore"):
1259
+ aspect_ratio = gv("image_RectangleW") / gv("image_RectangleL")
1260
+ aspect_ratio1 = gv("image_EllipseW") / gv("image_EllipseL")
1261
+ else:
1262
+ aspect_ratio = aspect_ratio1 = None
1263
+
1264
+ # -- v3.5 fix: NO second scaling by diodesize. `image_diam_AreaR` is read and
1265
+ # used exactly as `imgProc_sm.m` wrote it, unlike v3.1.4's `:669`, which the
1266
+ # v3.1.4 port's own docstring names as the double-scaled area-ratio
1267
+ # concentration (conc_AreaR effectively always zero on a 2D-S).
1268
+ particle_diameter_AreaR = gv("image_diam_AreaR")
1269
+
1270
+ time_in_seconds = gv("Time_in_seconds")
1271
+
1272
+ rec_nums = gv("parent_rec_num") if old_style else None # `:945-947`
1273
+ dof_overload = gv("DMT_DOF_SPEC_OVERLOAD")
1274
+ # `:964-966` -- a 2DC/2DP/Fast2DC file written in the SEA convention flags
1275
+ # EVERY particle overloaded; the source zeroes the whole array, "since
1276
+ # overload can't be treated using SEA convention".
1277
+ if old_style and np.sum(dof_overload) == len(dof_overload):
1278
+ dof_overload = 0 * dof_overload
1279
+ # `:969-973` -- gated `(probetype~=0) && (probetype~=3)`: probetypes 0/3 never
1280
+ # read the probe's own count, so TotalPC1/TotalPC2 keep their zeros.
1281
+ if not old_style:
1282
+ particle_count = gv("Particle_number_all")
1283
+ total_pc1[i] = len(particle_count)
1284
+ total_pc2[i] = particle_count[-1] - particle_count[0]
1285
+
1286
+ # `:975-977` -- probetype 1 ONLY: every particle in an overloaded
1287
+ # DOF sample is marked rejected with 'D'. No such mark exists for
1288
+ # probetype 2, which is why the same second on a 2D-S keeps its
1289
+ # particles and only loses the dead TIME (`:1116`) instead.
1290
+ if probetype == 1:
1291
+ auto_reject[dof_overload != 0] = ord("D")
1292
+ return (auto_reject, im_width, im_length, area, perimeter, habit1, centerin,
1293
+ entirein, aspect_ratio, aspect_ratio1, particle_diameter_AreaR,
1294
+ time_in_seconds, rec_nums, dof_overload)
1295
+
1296
+
1297
+ def _interarrival(f, vid, start, count, start_all_max, time_in_seconds, probetype,
1298
+ res, tas_max, reaccpt_shatrs):
1299
+ """Per-block interarrival times ``int_arr``/``int_arr2``/``int_arr3``
1300
+ (``sizeDist.m:984-1046``), moved verbatim out of ``_run`` (2026-09-25 code review, item 1,
1301
+ phase 2). Returns the three arrays ``_run`` reads afterwards; ``int_arr2``
1302
+ and ``int_arr3`` stay ``None`` on the arms that do not build them."""
1303
+ if probetype == 0:
1304
+ # `:984-985` -- not a difference: probetype 0's `int_arr` IS the
1305
+ # absolute `Time_in_seconds`. Fast2DC (3) takes the `else` arm below.
1306
+ int_arr = time_in_seconds.astype(np.float64).copy()
1307
+ elif start - 1 <= 0:
1308
+ int_arr = np.concatenate([[0.0], np.diff(time_in_seconds)])
1309
+ else:
1310
+ t2 = f.get_var(vid["Time_in_seconds"], start - 1, count + 1).reshape(-1)
1311
+ int_arr = np.diff(t2)
1312
+ int_arr = int_arr.copy()
1313
+ # `:1025-1029` -- the counter-rollover correction exists for
1314
+ # probetype 2 (`<-10`, 2^32-1) and probetype 0 (`<0`, 2^24-1) ONLY.
1315
+ # There is no `elseif 1==probetype` arm, so a CIP/PIP run gets no
1316
+ # rollover correction of any kind and its negative interarrival
1317
+ # times fall straight through to `:1046`'s `int_arr(int_arr<0)=0`.
1318
+ # Preserved as written.
1319
+ if probetype == 2:
1320
+ roll = int_arr < -10
1321
+ int_arr[roll] += (2 ** 32 - 1) * (res / 1e6 / tas_max)
1322
+ elif probetype == 0:
1323
+ # `:1027-1028` -- the 24-bit clock's rollback, threshold 0 (not -10).
1324
+ roll = int_arr < 0
1325
+ int_arr[roll] += (2 ** 24 - 1) * (res / 1e6 / tas_max)
1326
+
1327
+ # -- int_arr2: NEW in v3.5, `max(start_all)` not `start_all(end)` --
1328
+ int_arr2 = None
1329
+ if probetype != 0 and start - 1 > 0 and start != start_all_max:
1330
+ t3 = f.get_var(vid["Time_in_seconds"], (start + count) - 1, 2).reshape(-1)
1331
+ int_arr2 = np.diff(t3)
1332
+ int_arr2 = int_arr2.copy()
1333
+ int_arr2[int_arr2 < 0] = 0
1334
+
1335
+ # -- int_arr3: same `max(start_all)` change; stock's own
1336
+ # single-particle-at-last-block guard, unconditional here since
1337
+ # v3.5 IS the (only) stock lineage continued (no FidelityProfile).
1338
+ int_arr3 = None
1339
+ # `:1004-1018` builds int_arr3 only in the `else` of `:984`, so a probetype-0 run leaves
1340
+ # it unassigned (None here). Whether MATLAB then dies depends on whether one of the
1341
+ # shattering blocks that read it (`:1204`, `:1337`, `:1403`) runs, each gated on
1342
+ # iaThreshType and applyIntArrThresh; apply_shattering raises exactly there
1343
+ # (_refuse_missing_int_arr3), so a run in which no block runs completes, as MATLAB's does.
1344
+ if reaccpt_shatrs and probetype != 0:
1345
+ if start != start_all_max:
1346
+ t4 = f.get_var(vid["Time_in_seconds"], start, count + 1).reshape(-1)
1347
+ int_arr3 = np.diff(t4)
1348
+ elif len(time_in_seconds) > 1:
1349
+ d3 = np.diff(time_in_seconds)
1350
+ int_arr3 = np.concatenate([d3, [d3[-1]]])
1351
+ else:
1352
+ int_arr3 = np.zeros(1)
1353
+ int_arr3 = int_arr3.copy()
1354
+ int_arr3[int_arr3 < 0] = 0
1355
+ return int_arr, int_arr2, int_arr3
1356
+
1357
+
1358
+ def _diameters_and_mass(gv, i, start, count, cfg, d_choice, diodesize, old_style, im_length,
1359
+ im_width, area, perimeter, habit1, centerin, entirein, rec_nums, dof_overload,
1360
+ auto_reject, int_arr, int_arr2, int_arr3, image_time_hhmmssall, tas, tas_max, pres,
1361
+ temp, mmethod, mmethod_pow, i_new_habit, ia_thresh_type, apply_int_arr_thresh, spec,
1362
+ sa_method, one_sec_times, time_interval72, time_interval2, good_partpercent,
1363
+ reject_by_criterion, total_one_sec_locs, area_ratio_z=None, intar_threshold=None):
1364
+ """Per-block diameters, mass, area ratio, fall speed, shattering and the
1365
+ good/bad masks (``sizeDist.m:1050-1211``), moved verbatim out of ``_run``
1366
+ (2026-09-25 code review, item 1, phase 3). Writes ``time_interval72``, ``time_interval2``,
1367
+ ``good_partpercent``, ``reject_by_criterion``, ``total_one_sec_locs`` and
1368
+ ``auto_reject`` in place, as the inline block did, and returns what the
1369
+ ``_process_population`` loop reads."""
1370
+ minr = gv("image_diam_minR") if d_choice == 6 else None
1371
+ particle_diameter_minR = d_choice_diameter(
1372
+ d_choice, im_length, im_width, diodesize, minr)
1373
+
1374
+ if old_style:
1375
+ # `:1111-1113` -- 2DC/2DP/Fast2DC overload: the first particle of each
1376
+ # record carries the record's overload time in ms. MATLAB indexes the
1377
+ # length-n array with the length-(n-1) mask `diff(rec_nums)>0`, which
1378
+ # reads the first n-1 elements.
1379
+ rec_start = np.diff(rec_nums) > 0
1380
+ time_interval72[i] = float(np.sum(dof_overload[:-1][rec_start])) / 1000.0
1381
+ else:
1382
+ time_interval72[i] = overload_dead_time(
1383
+ int_arr, dof_overload, cfg.probetype)
1384
+
1385
+ image_time_hhmmss = image_time_hhmmssall[start:start + count]
1386
+
1387
+ if tas[i] > tas_max:
1388
+ area = area * tas[i] / tas_max
1389
+ if mmethod == 0:
1390
+ # Unchanged: literally the same computation this function
1391
+ # always ran before `mmethod` existed --
1392
+ # tests/test_mmethod_default_is_bit_identical.py.
1393
+ particle_mass = np.array([
1394
+ single_mass(d / 10, chr(int(h)), i_new_habit)
1395
+ for d, h in zip(particle_diameter_minR, habit1, strict=True)
1396
+ ])
1397
+ else:
1398
+ # Peter Brechner's `sizeDist_decibel3.m:1186-1211` `Mmethod`
1399
+ # ladder -- opt-in, folded into this engine from the
1400
+ # sibling package `arrayprobe_v35_brechner` on 2026-09-17
1401
+ # (the no-new-packages rule). Only `mmethod` in (1, 2, 3)
1402
+ # reaches it, and `mass_b26` is not part of every
1403
+ # distribution, so its absence is a named refusal rather
1404
+ # than a bare ImportError.
1405
+ try:
1406
+ from arrayprobe_uiops.mass_b26 import particle_mass_dispatch
1407
+ except ImportError as exc:
1408
+ raise ImportError(
1409
+ f"Mmethod={mmethod} is not available in this release: it needs "
1410
+ "arrayprobe_uiops.mass_b26, which this distribution does not ship. "
1411
+ "Use Mmethod=0 (the default)."
1412
+ ) from exc
1413
+ mass_diameter_minR = (
1414
+ particle_diameter_minR if d_choice == 6 else gv("image_diam_minR")
1415
+ )
1416
+ holroyd_perimeter = gv("Holroyd_perimeter") if mmethod == 3 else None
1417
+ hollow_mask = (auto_reject == ord("h")) if mmethod == 3 else None
1418
+ particle_mass = particle_mass_dispatch(
1419
+ mmethod,
1420
+ area=area,
1421
+ particle_diameter_minR=particle_diameter_minR,
1422
+ mass_diameter_minR=mass_diameter_minR,
1423
+ holroyd_perimeter=holroyd_perimeter,
1424
+ outer_perimeter=perimeter,
1425
+ hollow_mask=hollow_mask,
1426
+ diodesize=diodesize,
1427
+ pow=mmethod_pow,
1428
+ )
1429
+ calcd_area = np.array([
1430
+ single_area(d / 10, chr(int(h)), i_new_habit)
1431
+ for d, h in zip(particle_diameter_minR, habit1, strict=True)
1432
+ ])
1433
+ # Elementwise through the platform libm, as Octave's `.^` does: numpy's array `**` takes a
1434
+ # SIMD pow whose last bit depends on the CPU's dispatch (AVX-512 differed from the Octave
1435
+ # golden in 1-2 ULP where the libm pow did not; cloud pass 7 item 4).
1436
+ particle_massbl = 0.115 / 1000 * _libm_pow(area, 1.218)
1437
+
1438
+ with np.errstate(divide="ignore", invalid="ignore"):
1439
+ area_ratio = area / (np.pi / 4 * particle_diameter_minR ** 2)
1440
+ # v3.5-only: clip (:1161) before the 'z' rejection test (:1162).
1441
+ area_ratio = np.minimum(area_ratio, AREA_RATIO_UPPER_CLIP)
1442
+ # `area_ratio_z` None is the literal `.2` of :1162 through AREA_RATIO_Z, the path that
1443
+ # always ran; a value replaces only that literal (run()'s docstring).
1444
+ z = AREA_RATIO_Z if area_ratio_z is None else area_ratio_z
1445
+ auto_reject[area_ratio < z] = ord("z")
1446
+
1447
+ with np.errstate(divide="ignore", invalid="ignore"):
1448
+ particle_vt = np.array([
1449
+ single_vt(d / 1000, ar, m / 1000, pres[i], temp[i])
1450
+ for d, ar, m in zip(particle_diameter_minR, area_ratio,
1451
+ particle_mass, strict=True)
1452
+ ])
1453
+ particle_pr = particle_mass * particle_vt
1454
+
1455
+ if cfg.probetype == 0 and ia_thresh_type == 2 and apply_int_arr_thresh:
1456
+ # `:1310-1311` reads `~isempty(int_arr2)`, and `:984`'s probetype-0 arm
1457
+ # never assigns int_arr2 in any second, so v3.5 MATLAB dies with
1458
+ # "'int_arr2' undefined" -- the GPM 2DC int_arr2 crash, unchanged by the diff
1459
+ # and demonstrated under Octave for v3.1.4 on ('GPM','2DC').
1460
+ raise NotImplementedError(
1461
+ "v3.5 sizeDist.m:1311 reads int_arr2, which :984-985 never assigns "
1462
+ "for probetype 0: MATLAB dies with \"'int_arr2' undefined\" "
1463
+ "(an upstream finding). Reached via iaThreshType == 2.")
1464
+ auto_reject = apply_shattering(
1465
+ ia_thresh_type=ia_thresh_type, cfg=cfg, spec=spec, i=i,
1466
+ auto_reject=auto_reject, int_arr=int_arr, int_arr2=int_arr2,
1467
+ int_arr3=int_arr3, particle_diameter_minR=particle_diameter_minR,
1468
+ start=start, count=count, intar_threshold=intar_threshold,
1469
+ )
1470
+
1471
+ good_particles = np.isin(auto_reject, [ord(c) for c in GOOD_REJECT_CODES])
1472
+ bad_particles = ~good_particles
1473
+ if sa_method == 0:
1474
+ good_particles = good_particles & (centerin == 1)
1475
+ bad_particles = bad_particles & (centerin == 1)
1476
+ elif sa_method == 1:
1477
+ good_particles = good_particles & (entirein == 0)
1478
+ bad_particles = bad_particles & (centerin == 0)
1479
+
1480
+ good_partpercent[i] = np.count_nonzero(good_particles) / len(good_particles)
1481
+ reject_by_criterion[i, 0] = np.count_nonzero(centerin == 1) / len(good_particles)
1482
+ for c, code in enumerate(REJECT_CRITERION_CODES[1:], start=1):
1483
+ reject_by_criterion[i, c] = (
1484
+ np.count_nonzero(auto_reject == ord(code)) / len(good_particles))
1485
+
1486
+ image_time = _hhmmss_to_insec(image_time_hhmmss)
1487
+
1488
+ in_sec = (image_time >= one_sec_times[i]) & (image_time < one_sec_times[i + 1])
1489
+ total_one_sec_locs[i] = np.count_nonzero(in_sec)
1490
+ time_interval2[i] = float(msum(int_arr[in_sec]))
1491
+ if total_one_sec_locs[i] == 0:
1492
+ time_interval2[i] = 1
1493
+ return (particle_diameter_minR, area, particle_mass, calcd_area, particle_massbl,
1494
+ area_ratio, particle_vt, particle_pr, good_particles, bad_particles, image_time)
1495
+
1496
+
1497
+ def _run(
1498
+ f, mainf, infile, tas, timehhmmss, probename, d_choice, sa_method, pres, temp,
1499
+ projectname, ddate, ia_thresh_type, spec, cfg, i_new_habit, attr_habit,
1500
+ i_create_bad, i_create_aspect_ratio, i_save_int_arr_sv, octave_mean_extra,
1501
+ octave_colon, software, creation_time, progress,
1502
+ mmethod=0, mmethod_pow=0.0, stamp_profile=None, tas_qc=None, area_ratio_z=None,
1503
+ default_int_arr_thresh=None, pecan=None, time_offset=None, zero_sv_nan=False,
1504
+ ):
1505
+ if time_offset is not None and time_offset.tas_clock == "probe":
1506
+ # Opt-in (TimeOffset): the per-second rows share the particles' off clock, so they move
1507
+ # with them, before the rollover below sees them as it would a real clock's.
1508
+ timehhmmss = shift_hhmmss(timehhmmss, time_offset.seconds)
1509
+ # -- flight-time rollover: UNCHANGED in v3.5, reused verbatim ----------
1510
+ _rollover_240000(timehhmmss)
1511
+
1512
+ tas_time = (np.floor(timehhmmss / 10000) * 3600
1513
+ + np.floor((timehhmmss % 10000) / 100) * 60
1514
+ + np.floor(timehhmmss % 100))
1515
+ # :164-172 / :195-203 -- PECAN's per-second threshold from the supplied parameters;
1516
+ # None on every other case, which reads the constant (apply_shattering).
1517
+ intar_threshold = (None if pecan is None else
1518
+ pecan_intar_threshold(tas_time, pecan, cfg.defaultIntArrThresh))
1519
+
1520
+ num_bins = cfg.num_bins
1521
+ kk = cfg.kk(octave_colon=octave_colon)
1522
+ diodesize = cfg.diodesize
1523
+ res = diodesize * 1000
1524
+ binwidth = np.diff(kk)
1525
+ tas_max = cfg.tasMax
1526
+ if tas_max is None:
1527
+ raise TasMaxUndefined(_TASMAX_UNDEFINED)
1528
+ apply_int_arr_thresh = cfg.applyIntArrThresh
1529
+ reaccpt_shatrs = cfg.reaccptShatrs
1530
+
1531
+ n_sec = len(tas)
1532
+
1533
+ def nanmat():
1534
+ return np.full((n_sec, num_bins), np.nan)
1535
+
1536
+ def nancube():
1537
+ return np.full((n_sec, num_bins, 10), np.nan)
1538
+
1539
+ good = dict(
1540
+ dist_minR=nanmat(), dist_AreaR=nanmat(), areaRatio1=nanmat(),
1541
+ area=nanmat(), meanp=nanmat(), iwc=nanmat(), iwcbl=nanmat(),
1542
+ vt=nanmat(), pr=nanmat(), partarea=nanmat(),
1543
+ habitsd=nancube(), habitmsd=nancube(), area_dist2=nancube(),
1544
+ re=np.full(n_sec, np.nan), one_sec_ar=np.full(n_sec, np.nan),
1545
+ aspectRatio=nanmat() if i_create_aspect_ratio else None,
1546
+ aspectRatio1=nanmat() if i_create_aspect_ratio else None,
1547
+ )
1548
+ bad = dict(
1549
+ dist_minR=nanmat(), dist_AreaR=nanmat(), areaRatio1=nanmat(),
1550
+ area=nanmat(), meanp=nanmat(), iwc=nanmat(), iwcbl=nanmat(),
1551
+ vt=nanmat(), pr=nanmat(), partarea=nanmat(),
1552
+ habitsd=nancube(), habitmsd=nancube(), area_dist2=nancube(),
1553
+ re=np.full(n_sec, np.nan),
1554
+ # `bad_one_sec_ar = zeros(length(tas),1)` (v3.5 :708) -- ZERO, not NaN,
1555
+ # unlike every sibling `bad_*` accumulator (all `zeros(...)*NaN`). The
1556
+ # past-end-of-data branch below never touches ANY `bad_*` variable
1557
+ # (measured: :1848-1875 names only good-side variables), so a second
1558
+ # that never gets a real particle block leaves this at its own
1559
+ # allocation -- 0, not NaN (the uncorrected no-crossover particle time).
1560
+ one_sec_ar=np.zeros(n_sec),
1561
+ aspectRatio=nanmat() if i_create_aspect_ratio else None,
1562
+ aspectRatio1=nanmat() if i_create_aspect_ratio else None,
1563
+ )
1564
+ good_partpercent = np.zeros(n_sec)
1565
+ reject_by_criterion = np.zeros((n_sec, 14))
1566
+ time_interval2 = np.zeros(n_sec)
1567
+ time_interval72 = np.zeros(n_sec)
1568
+ total_one_sec_locs = np.zeros(n_sec)
1569
+ total_pc1 = np.zeros(n_sec)
1570
+ total_pc2 = np.zeros(n_sec)
1571
+
1572
+ one_sec_times = np.concatenate([tas_time, [tas_time[-1] + 1]])
1573
+
1574
+ _, num_of_part = f.inq_dim(0)
1575
+
1576
+ # -- particle time: v3.5 `:758-781`, the three-arm probetype switch -----
1577
+ # `:758-759` probetype 1 -> `particle_time`
1578
+ # `:760-778` probetype 2 -> `Time`, via `image_time_hhmmssallbuffer`
1579
+ # `:779-780` else (probetypes 0 and 3) -> `Time`, directly
1580
+ # so 0, 2 and 3 all end up with `Time` and only probetype 1 differs --
1581
+ # measured by reading the three arms, not inferred from probetype 2's.
1582
+ if cfg.probetype == 1:
1583
+ image_time_hhmmssall = f.get_var(f.inq_var_id("particle_time")).reshape(-1)
1584
+ else:
1585
+ image_time_hhmmssall = f.get_var(f.inq_var_id("Time")).reshape(-1)
1586
+ if time_offset is not None:
1587
+ # Opt-in (TimeOffset): onto aircraft time where the particle times are read, before
1588
+ # every midnight correction below, so those see a corrected clock's data.
1589
+ image_time_hhmmssall = shift_hhmmss(image_time_hhmmssall, time_offset.seconds)
1590
+ # `Time_in_seconds`/`msec` are also read here in the source but feed only
1591
+ # the dead-store `alltimeinseconds` computation (v3.1.4 port's own
1592
+ # docstring, ":522-528... DEAD STORE... discarded at :534"); v3.5's diff
1593
+ # does not touch that block. Not transcribed -- see the design record.
1594
+
1595
+ # -- NEW in v3.5: the multi-day fix and the block-resolution logic -----
1596
+ image_time_hhmmssall, _ = fix_multiday_particle_times(image_time_hhmmssall)
1597
+ image_time_hhmmssall = apply_flight_day_carryover(image_time_hhmmssall, timehhmmss)
1598
+ starttime, start_all, count_all = resolve_particle_blocks(
1599
+ image_time_hhmmssall, int(num_of_part)
1600
+ )
1601
+ start_all_max = int(start_all.max())
1602
+
1603
+ jjj = 1
1604
+ eof_flag = False
1605
+ n_blocks = len(start_all)
1606
+
1607
+ vid_names = [
1608
+ "particle_millisec", "particle_microsec", "image_auto_reject",
1609
+ "image_width", "image_length", "image_area", "image_perimeter",
1610
+ "holroyd_habit", "image_center_in", "image_touching_edge",
1611
+ "image_diam_AreaR", "Time_in_seconds", "DMT_DOF_SPEC_OVERLOAD",
1612
+ "image_diam_minR",
1613
+ ]
1614
+ # `:945-947` reads `parent_rec_num` for probetypes 0 and 3 only; `:969-973` reads
1615
+ # `Particle_number_all` for every OTHER probetype (added with the CIP pipeline, 2026-09-23).
1616
+ old_style = cfg.probetype in (0, 3)
1617
+ vid_names += ["parent_rec_num"] if old_style else ["Particle_number_all"]
1618
+ if i_create_aspect_ratio:
1619
+ vid_names += ["image_RectangleW", "image_RectangleL",
1620
+ "image_EllipseW", "image_EllipseL"]
1621
+ if mmethod == 3:
1622
+ # `sizeDist_decibel3.m:1206` -- only Mmethod 3 reads this variable;
1623
+ # a stock v3.5 fixture with no `Holroyd_perimeter` variable is
1624
+ # untouched at mmethod=0, the only value any existing caller passes.
1625
+ vid_names += ["Holroyd_perimeter"]
1626
+ vid = {name: f.inq_var_id(name) for name in vid_names}
1627
+
1628
+ for i in range(n_sec):
1629
+ if progress is not None and (i + 1) % 1000 == 0:
1630
+ progress(i + 1, n_sec)
1631
+
1632
+ # v3.5 :913/:918 compare `int32(timehhmmss(i))` with `int32(starttime(jjj))`:
1633
+ # int32 ROUNDS (half away from zero), where Python's `int` truncates, so a
1634
+ # fractional TAS time such as 164128.6 is second 164129 to MATLAB. `int()`
1635
+ # here before V35; measured under Octave, case `fractime`.
1636
+ t_int32 = int(mint32(timehhmmss[i]))
1637
+ if not eof_flag and t_int32 >= int(mint32(starttime[jjj - 1])):
1638
+ # v3.5 :918 -- `while (int32(timehhmmss(i))>int32(starttime(jjj)))`,
1639
+ # with NO `jjj < length(start_all)` bound (the ORACLES fork's
1640
+ # ORACLES-variant sizeDist.m:627 has one; no stock release does).
1641
+ while t_int32 > int(mint32(starttime[jjj - 1])):
1642
+ jjj += 1
1643
+ if jjj == n_blocks:
1644
+ eof_flag = True
1645
+ if jjj > n_blocks:
1646
+ # The loop's next test reads `starttime(jjj)` one past the
1647
+ # end, so v3.5 MATLAB dies whenever a TAS second lands
1648
+ # beyond the last particle block before `jjj` has reached
1649
+ # it (a TAS gap over the final block). Measured under
1650
+ # Octave on the unmodified v3.5 source, V35, case
1651
+ # `tasgap`: "starttime(3): out of bound 2". Before V35
1652
+ # this loop carried the fork's bound and completed.
1653
+ raise MatlabIndexError(
1654
+ f"v3.5 sizeDist.m:918 reads starttime({jjj}) past the "
1655
+ f"last of {n_blocks} particle blocks at TAS second "
1656
+ f"{t_int32}: the while loop has no "
1657
+ "`jjj <= length(start_all)` bound, so MATLAB dies with "
1658
+ "an out-of-bound index here.")
1659
+ if jjj == n_blocks:
1660
+ eof_flag = True
1661
+
1662
+ start = int(start_all[jjj - 1])
1663
+ count = int(count_all[jjj - 1])
1664
+ jjj = min(jjj + 1, n_blocks)
1665
+
1666
+ def gv(name, s=start, c=count):
1667
+ return f.get_var(vid[name], s, c).reshape(-1)
1668
+
1669
+ (auto_reject, im_width, im_length, area, perimeter, habit1, centerin,
1670
+ entirein, aspect_ratio, aspect_ratio1, particle_diameter_AreaR,
1671
+ time_in_seconds, rec_nums, dof_overload) = _read_block(
1672
+ gv, i, old_style, i_create_aspect_ratio, cfg.probetype,
1673
+ total_pc1, total_pc2)
1674
+
1675
+ int_arr, int_arr2, int_arr3 = _interarrival(
1676
+ f, vid, start, count, start_all_max, time_in_seconds, cfg.probetype,
1677
+ res, tas_max, reaccpt_shatrs)
1678
+
1679
+ auto_reject[int_arr < 0] = ord("I")
1680
+ int_arr[int_arr < 0] = 0
1681
+
1682
+ (particle_diameter_minR, area, particle_mass, calcd_area, particle_massbl,
1683
+ area_ratio, particle_vt, particle_pr, good_particles, bad_particles,
1684
+ image_time) = _diameters_and_mass(
1685
+ gv=gv, i=i, start=start, count=count, cfg=cfg, d_choice=d_choice,
1686
+ diodesize=diodesize, old_style=old_style, im_length=im_length,
1687
+ im_width=im_width, area=area, perimeter=perimeter, habit1=habit1,
1688
+ centerin=centerin, entirein=entirein, rec_nums=rec_nums,
1689
+ dof_overload=dof_overload, auto_reject=auto_reject, int_arr=int_arr,
1690
+ int_arr2=int_arr2, int_arr3=int_arr3,
1691
+ image_time_hhmmssall=image_time_hhmmssall, tas=tas, tas_max=tas_max,
1692
+ pres=pres, temp=temp, mmethod=mmethod, mmethod_pow=mmethod_pow,
1693
+ i_new_habit=i_new_habit, ia_thresh_type=ia_thresh_type,
1694
+ apply_int_arr_thresh=apply_int_arr_thresh, spec=spec, sa_method=sa_method,
1695
+ one_sec_times=one_sec_times, time_interval72=time_interval72,
1696
+ time_interval2=time_interval2, good_partpercent=good_partpercent,
1697
+ reject_by_criterion=reject_by_criterion,
1698
+ total_one_sec_locs=total_one_sec_locs, area_ratio_z=area_ratio_z,
1699
+ intar_threshold=intar_threshold)
1700
+
1701
+ for which, mask, store in (("good", good_particles, good),
1702
+ ("bad", bad_particles, bad)):
1703
+ if which == "bad" and not i_create_bad:
1704
+ continue
1705
+ empty = _process_population(
1706
+ i, mask, entirein, image_time, one_sec_times, kk, num_bins,
1707
+ binwidth, particle_diameter_minR, particle_diameter_AreaR,
1708
+ habit1, area, perimeter, area_ratio, particle_mass,
1709
+ calcd_area, particle_massbl, particle_vt, particle_pr,
1710
+ store, octave_mean_extra, aspect_ratio, aspect_ratio1,
1711
+ )
1712
+ if empty and which == "good":
1713
+ time_interval2[i] = 1
1714
+ time_interval72[i] = 0
1715
+ total_pc1[i] = 1
1716
+ total_pc2[i] = 1
1717
+ else:
1718
+ # v3.5 :1848-1875 (unchanged from v3.1.4) names ONLY good-side
1719
+ # variables in this branch -- no `bad_*` array is touched at all.
1720
+ # A second that never gets a real particle block therefore leaves
1721
+ # every `bad_*` accumulator at its own pre-allocation (NaN, except
1722
+ # `bad_one_sec_ar`'s own zero -- see the `bad` dict above,
1723
+ # the uncorrected no-crossover particle time). Looping over `(good, bad)`
1724
+ # symmetrically here, as a naive port would, measurably disagrees with
1725
+ # real Octave on `REJ_ar` alone.
1726
+ for store in (good,):
1727
+ store["dist_minR"][i, :] = np.nan
1728
+ store["dist_AreaR"][i, :] = np.nan
1729
+ store["area_dist2"][i, :, :] = np.nan
1730
+ store["partarea"][i, :] = np.nan
1731
+ store["iwc"][i, :] = np.nan
1732
+ store["iwcbl"][i, :] = np.nan
1733
+ store["vt"][i, :] = np.nan
1734
+ store["pr"][i, :] = np.nan
1735
+ store["re"][i] = np.nan
1736
+ store["habitsd"][i, :, :] = np.nan
1737
+ store["habitmsd"][i, :, :] = np.nan
1738
+ store["one_sec_ar"][i] = np.nan
1739
+ good_partpercent[i] = 1
1740
+ reject_by_criterion[i, :] = np.nan
1741
+ time_interval2[i] = 1
1742
+ time_interval72[i] = 0
1743
+ total_pc1[i] = 1
1744
+ total_pc2[i] = 1
1745
+
1746
+ # -- sample volume and normalisation (unchanged by the diff) -----------
1747
+ cip2_binmin = kk[:-1]
1748
+ cip2_binmax = kk[1:]
1749
+ cip2_binmid = (cip2_binmin + cip2_binmax) / 2
1750
+ cip2_bindD = np.diff(kk)
1751
+
1752
+ sa2 = np.asarray(calc_sa_randombins(cip2_binmid, res, cfg.armdst,
1753
+ cfg.num_diodes, sa_method,
1754
+ cfg.probetype)).reshape(-1)
1755
+
1756
+ # `:1931-1948` -- how the per-second live-time fraction is derived differs
1757
+ # by probetype. Probetype 2 (and 0/3) use 1 - dead time; probetype 1 uses
1758
+ # the RATIO of images kept to particles the probe itself counted, which is
1759
+ # a different quantity entirely.
1760
+ if cfg.probetype == 1:
1761
+ # `:1934` -- TotalPC2 is a 16-bit probe counter read as signed, so a
1762
+ # wrapped count comes back negative; += 2^16 unwraps it.
1763
+ total_pc2 = total_pc2.copy()
1764
+ total_pc2[total_pc2 < 0] += 2 ** 16
1765
+ # `:1938` -- images we have / particles the probe counted.
1766
+ time_interval199 = total_pc1 / total_pc2
1767
+ # `:1950-1958` -- "Experimental - Use with care!". During PECAN the
1768
+ # image count ran up to TWICE the probe's own particle count, which
1769
+ # would inflate concentration; every ratio above 1 is pinned to 1.
1770
+ # The clamp is applied for EVERY campaign, not just PECAN, because
1771
+ # `:1950`'s gate is `probetype==1` alone. Preserved.
1772
+ time_interval200 = time_interval199.copy()
1773
+ n_exceeded = int(np.count_nonzero(time_interval199 > 1))
1774
+ time_interval200[time_interval199 > 1] = 1.0
1775
+ _logger.warning(
1776
+ "Total image count exceeded probe particle count %d times; "
1777
+ "time_interval200 was set to 1 in these cases.", n_exceeded,
1778
+ )
1779
+ else:
1780
+ time_interval200 = 1 - time_interval72 # `:1932` probetype 2 (and 0/3)
1781
+
1782
+ # v3.5 :1959-1971 (Finlon 02/26/18): a NaN TAS takes the last valid TAS
1783
+ # before it, or 100 m/s when there is none. Placed where v3.5 places it --
1784
+ # after the per-second loop, so it reaches only the sample volume below;
1785
+ # the loop's `tas(i) > tasMax` (:1144) saw the NaN. A copy, because the
1786
+ # caller's array is not MATLAB's pass-by-value `tas`. Absent from this port
1787
+ # before V35, which wrote a NaN sample volume there; measured under
1788
+ # Octave on the unmodified v3.5 source, case `nantas`. Applies to every
1789
+ # probetype: :1959 is outside the :1931-1958 probetype split.
1790
+ tas = tas.copy()
1791
+ for k in np.flatnonzero(np.isnan(tas)):
1792
+ prev = tas[:k]
1793
+ prev = prev[~np.isnan(prev)]
1794
+ tas[k] = prev[-1] if prev.size else 100.0
1795
+ # (:1972-1973's "Found %d instances..." fprintf is stdout only; not reproduced.)
1796
+
1797
+ svol2 =(sa2[:, None] * (1e-3) ** 2) * time_interval200[None, :]
1798
+ svol2 = svol2 * tas[None, :]
1799
+ svol2 = svol2 * 100 ** 3
1800
+ # Default-on correction: a 1 s overload gives time_interval200 = 0 (:1121-1123, :1932),
1801
+ # so every concentration below is count/0 = Inf. Opt-in here (the Octave goldens run stock);
1802
+ # the driver passes zero_sv_nan=True by default on this engine. NaN divisor -> NaN conc;
1803
+ # sample_vol itself is written unchanged.
1804
+ svol_div = svol2
1805
+ zero_sv_seconds = 0
1806
+ if zero_sv_nan:
1807
+ bad = ~(svol2 > 0)
1808
+ zero_sv_seconds = int(bad.any(axis=0).sum())
1809
+ svol_div = np.where(bad, np.nan, svol2)
1810
+ svol2_t = svol_div.T
1811
+ svol2a = np.repeat(svol2_t[:, :, None], 10, axis=2)
1812
+
1813
+ out = {}
1814
+ unwritten = {}
1815
+ for which, store in (("", good), ("REJ_", bad)):
1816
+ if which == "REJ_" and not i_create_bad:
1817
+ continue
1818
+ with np.errstate(divide="ignore", invalid="ignore"):
1819
+ conc_minR = store["dist_minR"] / svol2_t
1820
+ out[which + "conc_minR"] = conc_minR.T
1821
+ out[which + "conc_AreaR"] = (store["dist_AreaR"] / svol2_t).T
1822
+ out[which + "total_area"] = (store["area"] / svol2_t).T
1823
+ out[which + "Calcd_area"] = (store["partarea"] / svol2_t).T
1824
+ out[which + "mass"] = (store["iwc"] / svol2_t).T
1825
+ out[which + "massBL"] = (store["iwcbl"] / svol2_t).T
1826
+ out[which + "vt"] = (store["vt"] / svol2_t).T
1827
+ out[which + "Prec_rate"] = (store["pr"] / svol2_t).T
1828
+ out[which + "count"] = (store["dist_minR"] * binwidth[None, :] / 10).T
1829
+ out[which + "area"] = np.transpose(store["area_dist2"] / svol2a, (2, 1, 0))
1830
+ out[which + "habitsd"] = np.transpose(store["habitsd"] / svol2a, (2, 1, 0))
1831
+ out[which + "habitmsd"] = np.transpose(store["habitmsd"] / svol2a, (2, 1, 0))
1832
+ out[which + "n"] = nansum(conc_minR * binwidth[None, :], 2) / 10
1833
+ out[which + "re"] = store["re"]
1834
+ out[which + "ar"] = store["one_sec_ar"]
1835
+ out[which + "mean_perimeter"] = store["meanp"].T
1836
+ # v3.5 fix (the fixed area-ratio double scaling): these three (and their REJ_ twins) are now
1837
+ # written WITH the transpose every sibling variable already carries.
1838
+ # v3.1.4's own port names their absence a defect (its `NOT_TRANSPOSED`
1839
+ # set); v3.5 no longer has it, so this port must not "preserve" it.
1840
+ out[which + "mean_area_ratio"] = store["areaRatio1"].T
1841
+ if i_create_aspect_ratio:
1842
+ out[which + "mean_aspect_ratio_rectangle"] = store["aspectRatio"].T
1843
+ out[which + "mean_aspect_ratio_ellipse"] = store["aspectRatio1"].T
1844
+ unwritten[which + "lwc"] = _lwc.lwc_calc(conc_minR, cip2_binmid)
1845
+
1846
+ if i_create_bad:
1847
+ for name in ("mean_aspect_ratio_rectangle", "mean_aspect_ratio_ellipse"):
1848
+ out.setdefault("REJ_" + name, np.full((n_sec, num_bins), np.nan).T)
1849
+
1850
+ out["time"] = timehhmmss
1851
+ out["bin_min"] = cip2_binmin
1852
+ out["bin_max"] = cip2_binmax
1853
+ out["bin_mid"] = cip2_binmid
1854
+ out["bin_dD"] = cip2_bindD
1855
+ out["Reject_ratio"] = 1 - good_partpercent
1856
+ out["sum_IntArr"] = time_interval200
1857
+ out["sample_vol"] = svol2
1858
+
1859
+ iat_threshold = None
1860
+ if spec.iat_thresh is not None:
1861
+ iat_threshold = np.asarray(spec.iat_thresh, dtype=np.float64)
1862
+ out["iat_threshold"] = iat_threshold
1863
+
1864
+ _write_v35(
1865
+ mainf, out, num_bins, n_sec, infile, projectname, probename, sa_method,
1866
+ d_choice, apply_int_arr_thresh, reaccpt_shatrs, cfg, i_create_bad,
1867
+ i_create_aspect_ratio, i_save_int_arr_sv, attr_habit, iat_threshold,
1868
+ software, creation_time, stamp_profile, tas_qc, area_ratio_z=area_ratio_z,
1869
+ default_int_arr_thresh=default_int_arr_thresh, time_offset=time_offset,
1870
+ )
1871
+ out["_unwritten"] = unwritten
1872
+ out["_zero_sv_seconds"] = zero_sv_seconds
1873
+ out["_reject_by_criterion"] = reject_by_criterion
1874
+ out["_total_one_sec_locs"] = total_one_sec_locs
1875
+ out["_time_interval2"] = time_interval2
1876
+ out["_TotalPC1"] = total_pc1
1877
+ out["_TotalPC2"] = total_pc2
1878
+ return out
1879
+
1880
+
1881
+ def fix_time_grid(timehhmmss):
1882
+ """Default-on v3.5 correction for the duplicated-and-skipped seconds of the S4 time vector.
1883
+
1884
+ ``read_binary_SPEC.m:301-302`` writes each primary record's header time, and S4 floors it
1885
+ (``run_flight``'s ``np.floor(timehhmmss)``); clock jitter floors two records to the same
1886
+ second and skips the next, so second *t* appears twice and *t + 1* never.
1887
+ Minimal correction: a duplicate whose immediate successor gap is exactly two seconds moves
1888
+ up into the skipped second; failing that, its partner moves down when the gap before it is
1889
+ exactly two seconds. A duplicate with no single-second hole beside it is left as it is, so
1890
+ no row is invented and no particle is reassigned by more than one second. Midnight is
1891
+ unwrapped before the pass and rewrapped after. Returns ``(fixed HHMMSS float array,
1892
+ n_moved)``; the input is not modified.
1893
+ """
1894
+ t = np.asarray(timehhmmss, dtype=float)
1895
+ hh, rem = np.divmod(t, 10000)
1896
+ mm, ss = np.divmod(rem, 100)
1897
+ sec = hh * 3600 + mm * 60 + ss
1898
+ if sec.size > 1:
1899
+ sec = sec + 86400 * np.concatenate(([0], np.cumsum(np.diff(sec) < -43200)))
1900
+ sec = sec.copy()
1901
+ n = sec.size
1902
+ moved = 0
1903
+ for i in range(1, n):
1904
+ if sec[i] != sec[i - 1]:
1905
+ continue
1906
+ if (i + 1 >= n or sec[i + 1] - sec[i] == 2) and i + 1 < n:
1907
+ sec[i] += 1
1908
+ moved += 1
1909
+ elif i - 2 >= 0 and sec[i - 1] - sec[i - 2] == 2:
1910
+ sec[i - 1] -= 1
1911
+ moved += 1
1912
+ sec = np.mod(sec, 86400)
1913
+ h, r = np.divmod(sec, 3600)
1914
+ m, s_ = np.divmod(r, 60)
1915
+ return h * 10000 + m * 100 + s_, moved
1916
+
1917
+
1918
+ def count_duplicate_seconds(timehhmmss):
1919
+ """Rows of ``timehhmmss`` (floored to whole seconds) equal to their predecessor: the
1920
+ duplicates :func:`fix_time_grid` left unresolved because no single-second hole sat beside
1921
+ them (back-to-back repeats). Counted and stamped, never moved."""
1922
+ t = np.floor(np.asarray(timehhmmss, dtype=float).reshape(-1))
1923
+ return int(np.count_nonzero(t[1:] == t[:-1])) if t.size > 1 else 0