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,228 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Reader for 2D-S records in NCAR's RAF OAP file format, written from process2d's rule.
3
+
4
+ This reader exists so that an OAP export of this repository's decoded 2D-S images
5
+ can be round-tripped against a decoder that does not share the writer's code.
6
+ :func:`arrayprobe.readers.pms.read_binary_PMS` cannot serve: it knows the tags
7
+ ``C1``, ``C6``, ``C4`` and ``P*`` only, and skips a 2D-S record (tag ``SH`` or
8
+ ``SV``) without a word. Computes no number used by any product.
9
+
10
+ How this repository stores a decoded 2D-S image (read from source, layout pinned in tests)
11
+ ------------------------------------------------------------------------
12
+ The S2 file (``<stem>.H.cdf`` / ``.V.cdf``), written by
13
+ ``arrayprobe_uiops.spec._ImageFileV35`` with helpers shared from
14
+ ``arrayprobe.readers.spec``:
15
+
16
+ * ``data`` is ``int``, MATLAB shape ``(ImgRowlen=8, ImgBlocklen=1700, time)``;
17
+ one ``time`` step per raw 4096-byte record decoded (``spec.py:147-148``).
18
+ Per-record ``year, month, day, hour, minute, second, millisec, wkday`` (from
19
+ the raw record header), ``tas`` and ``tasRatio`` ride beside it.
20
+ * Each column is one slice of 128 diodes, packed into eight 16-bit words,
21
+ **MSB-first**: diode row 1 is bit 15 of word 1, row 128 bit 0 of word 8
22
+ (``sixteen2int``, ``readers/spec.py:599-608``).
23
+ * Polarity: **1 = shaded**. The decoder sets rows ``bb+1 .. bb+aa`` to 1, where
24
+ ``aa`` is the shaded-run field and ``bb`` the clear-run field of each
25
+ run-length word (``readers/spec.py:161-162``, ``:262-290``). The OAP format is
26
+ the opposite (1 = clear), so an exporter inverts.
27
+ * Particles are laid end to end from column 1: ``n_s`` image slices, then one
28
+ **boundary slice** (alternating 1010..., every word 43690), then one **header
29
+ slice** (``_write_header_slice``, ``readers/spec.py:393-414``). The header
30
+ slice holds the particle timing counter MSB-first in rows 1-128 and again in
31
+ rows 97-128, overwritten in rows 49-64 by the packet's count word, 65-80 by
32
+ the particle count and 81-96 by ``n_s``. So the timing counter is
33
+ recoverable exactly from words 7-8 of the header slice: it is the **32-bit**
34
+ value of the particle's last two raw words (``arrayprobe_uiops/spec.py``,
35
+ ``get_img_v35``), not a 48-bit word.
36
+ * No boundary precedes the first particle. Particles whose packet sets the
37
+ timing flag are skipped, not stored. A record whose particles run past
38
+ column 1700 loses them (the canvas cut, inherited from the upstream reader).
39
+ An image slice that happens to be all-alternating would read as a boundary;
40
+ the header slice that must follow it is what disambiguates.
41
+ * Per-record time is the raw record's, not the particle's: a particle's own time
42
+ is only its 32-bit counter.
43
+
44
+ The OAP side (process2d, NCAR/aircraft_oap ``process2d/process2d.cpp`` at
45
+ commit b46dd43)
46
+ -----------------------------------------------------------------------------
47
+ * A file is an XML preamble ending ``</OAP>`` and a newline, then 4116-byte
48
+ records: a 2-byte probe id, nine big-endian uint16 (hour, minute, second,
49
+ year, month, day, TAS, msec, overload), 4096 data bytes.
50
+ * Slice width is ``nDiodes / 8`` = 16 bytes for 2D-S (``:680-681``), 256 slices
51
+ per record.
52
+ * A slice is a **sync slice** when its last three bytes are ``AA AA AA``
53
+ (``:815-822``, "Stored little-endian, check far side of 16 bytes"); its
54
+ timing value is the slice's first eight bytes read little-endian, masked
55
+ with the probe's timing mask (``:818``, ``:821``).
56
+ * Any other slice is image: diode 0 is byte 15 bit 7, counting down through
57
+ bit 0 and then to byte 14, ..., diode 127 is byte 0 bit 0 (``:997-1002``).
58
+ translate2ds packs diode 0 into byte 0 bit 0 (LSB-first), so process2d sees
59
+ translate2ds's image mirrored across the array -- recorded, not resolved here.
60
+ * At a sync slice process2d closes the slices accumulated since the previous
61
+ sync as one particle, with the sync's timing value (``:852-993``). translate2ds
62
+ writes each sync carrying the *next* particle's time, so attribution differs
63
+ by one particle; this reader reports what the file says and leaves that to
64
+ the writer's tests.
65
+ """
66
+
67
+ from __future__ import annotations
68
+
69
+ import dataclasses
70
+ import re
71
+ import struct
72
+ from pathlib import Path
73
+
74
+ import numpy as np
75
+
76
+ __all__ = [
77
+ "OAP_RECORD_BYTES",
78
+ "OapParticle",
79
+ "OapRecordHeader",
80
+ "SLICE_BYTES_2DS",
81
+ "UnsupportedProbeVersion",
82
+ "read_oap_2ds",
83
+ "refuse_unsupported_raf_probe",
84
+ "split_oap_xml",
85
+ ]
86
+
87
+ OAP_RECORD_BYTES = 4116
88
+ DATA_BYTES = 4096
89
+ SLICE_BYTES_2DS = 16 # 128 diodes / 8, process2d.cpp:680
90
+ SYNC_TAIL = b"\xaa\xaa\xaa" # process2d.cpp:44, :820
91
+ TIMING_MASK_48 = 0x0000FFFFFFFFFFFF # the six low bytes translate2ds writes
92
+ _HEADER = struct.Struct(">2s9H")
93
+ _TAGS_2DS = (b"SH", b"SV")
94
+
95
+
96
+ @dataclasses.dataclass(frozen=True)
97
+ class OapRecordHeader:
98
+ """The 20-byte record header, as stored."""
99
+
100
+ probe_id: bytes
101
+ hour: int
102
+ minute: int
103
+ second: int
104
+ year: int
105
+ month: int
106
+ day: int
107
+ tas: int
108
+ msec: int
109
+ overload: int
110
+
111
+
112
+ @dataclasses.dataclass(frozen=True)
113
+ class OapParticle:
114
+ """One particle: the image slices before a sync slice, and that sync's timing.
115
+
116
+ ``bits`` is ``(n_slices, 128)`` uint8 in process2d's diode order, values as
117
+ stored (1 = clear, the OAP convention); ``shaded`` inverts it.
118
+ ``record`` is the 0-based index of the record holding the sync slice.
119
+ """
120
+
121
+ probe_id: bytes
122
+ timing: int
123
+ bits: np.ndarray
124
+ record: int
125
+
126
+ @property
127
+ def shaded(self) -> np.ndarray:
128
+ return (1 - self.bits).astype(np.uint8)
129
+
130
+
131
+ def split_oap_xml(raw: bytes) -> tuple[str, int]:
132
+ """Return the XML preamble and the byte offset of the first record.
133
+
134
+ The preamble ends at ``</OAP>`` plus the newline after it. A file without a
135
+ preamble starts its records at offset 0.
136
+ """
137
+ end = raw.find(b"</OAP>")
138
+ if end < 0:
139
+ return "", 0
140
+ stop = end + len(b"</OAP>")
141
+ if raw[stop : stop + 1] == b"\n":
142
+ stop += 1
143
+ return raw[:stop].decode("latin-1"), stop
144
+
145
+
146
+ class UnsupportedProbeVersion(ValueError):
147
+ """A RAF OAP raw file names a probe version the v3.5 engine cannot frame."""
148
+
149
+
150
+ #: Bytes read from the head of a raw file to find the XML preamble; a preamble
151
+ #: is a few hundred bytes, so this is generous.
152
+ _PREAMBLE_SCAN_BYTES = 65536
153
+ _PROBE_TYPE = re.compile(r"<probe\b[^>]*\btype\s*=\s*\"([^\"]*)\"")
154
+ _UNSUPPORTED_RAF_TYPES = {
155
+ "Fast2DC_v2": (
156
+ "the v3.5 engine frames only Fast-2DC v1 (a three-byte AA AA AA particle "
157
+ "boundary and a 12 MHz clock); a Fast-2DC v2 file marks each particle with a "
158
+ "two-byte AA AA word and a 33.333 MHz 44-bit clock, so the engine would find "
159
+ "no particle and write an empty product. Process this file with --engine soda2."
160
+ ),
161
+ }
162
+
163
+
164
+ def refuse_unsupported_raf_probe(path: str | Path) -> None:
165
+ """Raise :class:`UnsupportedProbeVersion` if ``path``'s preamble names a probe
166
+ type the v3.5 engine cannot frame (today: ``Fast2DC_v2``).
167
+
168
+ Reads only the head of the file. A file with no XML preamble, or whose probe
169
+ types are all framable, passes and returns ``None``.
170
+ """
171
+ with open(path, "rb") as fh:
172
+ head = fh.read(_PREAMBLE_SCAN_BYTES)
173
+ xml, _ = split_oap_xml(head)
174
+ for probe_type in _PROBE_TYPE.findall(xml):
175
+ reason = _UNSUPPORTED_RAF_TYPES.get(probe_type)
176
+ if reason is not None:
177
+ raise UnsupportedProbeVersion(
178
+ f"{Path(path).name}: probe type {probe_type!r}: {reason}")
179
+
180
+
181
+ def _slice_bits(slice_bytes: bytes) -> np.ndarray:
182
+ """process2d.cpp:997-1002: diode 0 is byte 15 bit 7, diode 127 byte 0 bit 0."""
183
+ arr = np.frombuffer(slice_bytes[::-1], dtype=np.uint8)
184
+ return np.unpackbits(arr, bitorder="big")
185
+
186
+
187
+ def read_oap_2ds(path: str | Path, probe_id: bytes = b"SH",
188
+ ) -> tuple[str, list[OapRecordHeader], list[OapParticle]]:
189
+ """Read every record tagged ``probe_id`` and split its slice stream at syncs.
190
+
191
+ Slices run continuously across records of the same probe, as translate2ds
192
+ writes them. Slices after the last sync (zero padding of the final record
193
+ included) belong to no particle and are not returned. Records of other
194
+ probes are skipped. Raises ``ValueError`` if the record area is not a whole
195
+ number of records.
196
+ """
197
+ if probe_id not in _TAGS_2DS:
198
+ raise ValueError(f"not a 2D-S probe id: {probe_id!r}")
199
+ raw = Path(path).read_bytes()
200
+ xml, offset = split_oap_xml(raw)
201
+ body = raw[offset:]
202
+ if len(body) % OAP_RECORD_BYTES:
203
+ raise ValueError(
204
+ f"{len(body)} bytes after the XML is not a whole number of "
205
+ f"{OAP_RECORD_BYTES}-byte records"
206
+ )
207
+ headers: list[OapRecordHeader] = []
208
+ particles: list[OapParticle] = []
209
+ pending: list[np.ndarray] = []
210
+ n_records = len(body) // OAP_RECORD_BYTES
211
+ for rec in range(n_records):
212
+ start = rec * OAP_RECORD_BYTES
213
+ fields = _HEADER.unpack_from(body, start)
214
+ if fields[0] != probe_id:
215
+ continue
216
+ headers.append(OapRecordHeader(*fields))
217
+ data = body[start + _HEADER.size : start + OAP_RECORD_BYTES]
218
+ for s in range(DATA_BYTES // SLICE_BYTES_2DS):
219
+ sl = data[s * SLICE_BYTES_2DS : (s + 1) * SLICE_BYTES_2DS]
220
+ if sl[-3:] == SYNC_TAIL:
221
+ timing = int.from_bytes(sl[:8], "little") & TIMING_MASK_48
222
+ bits = (np.vstack(pending) if pending
223
+ else np.zeros((0, 8 * SLICE_BYTES_2DS), dtype=np.uint8))
224
+ particles.append(OapParticle(probe_id, timing, bits, len(headers) - 1))
225
+ pending = []
226
+ else:
227
+ pending.append(_slice_bits(sl))
228
+ return xml, headers, particles
@@ -0,0 +1,51 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """The particle-image coercion shared by both UIOOPS ports.
3
+
4
+ Moved verbatim from ``arrayprobe/particle.py``, which re-exports these names, so
5
+ ``arrayprobe.particle.shadow_mask is arrayprobe_uiops.particle.shadow_mask``. The
6
+ module imports only NumPy, so the v3.1.4 package can load it without loading the
7
+ v3.5 engine. The encoding and its rationale are documented in
8
+ ``arrayprobe/particle.py``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import numpy as np
14
+
15
+ __all__ = ["SHADOWED", "LIT", "shadow_mask"]
16
+
17
+ #: The character MATLAB uses for a shadowed diode -- particle present.
18
+ SHADOWED = "0"
19
+
20
+ #: The character MATLAB uses for a lit diode -- no particle.
21
+ LIT = "1"
22
+
23
+ _SHADOWED_ORD = ord(SHADOWED)
24
+
25
+
26
+ def shadow_mask(c) -> np.ndarray: # type: ignore[no-untyped-def]
27
+ """Coerce a particle image to the canonical boolean array (``True`` = shadowed).
28
+
29
+ Four input forms are recognised, covering everything the pipeline produces:
30
+
31
+ * a boolean array -- returned as-is (already canonical);
32
+ * a string/bytes array -- compared against ``'0'``, the MATLAB char matrix;
33
+ * an integer array containing values above 1 -- treated as raw ASCII codes,
34
+ the char matrix as it arrives from a netCDF ``short``/``byte`` variable;
35
+ * any other integer array -- treated as 0/1 truth values.
36
+
37
+ The "above 1" test is what separates the last two cases, and it is decidable
38
+ because the two encodings share no values: an ASCII image contains only 48
39
+ and 49, a truth image only 0 and 1. An all-shadowed ASCII image is all 48s,
40
+ so its maximum is 48; an all-lit truth image is all 0s. The one genuinely
41
+ ambiguous input is an *empty* array, which both readings send to the same
42
+ empty result.
43
+ """
44
+ a = np.asarray(c)
45
+ if a.dtype.kind == "b":
46
+ return a
47
+ if a.dtype.kind in "SU":
48
+ return a == SHADOWED
49
+ if a.dtype.kind in "iu" and a.size and a.max() > 1:
50
+ return a == _SHADOWED_ORD
51
+ return a.astype(bool)
@@ -0,0 +1,94 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Single-particle image perimeter (boundary pixel count).
3
+
4
+ Ported from: ParticlePerimeter.m (UIOOPS v3.1.4)
5
+ """
6
+
7
+ #: Declared so the public surface is explicit rather than whatever happens not to
8
+ #: start with an underscore. The Phase-1 shims at ``<name>.py`` in the original flat layout import
9
+ #: these names directly, CONSTANTS INCLUDED -- omitting a constant here would not
10
+ #: break them, but omitting one from a shim does, which is why they are listed.
11
+ __all__ = [
12
+ "SHADOWED",
13
+ "BACKGROUND",
14
+ "particle_perimeter",
15
+ "particle_perimeter_setbased",
16
+ "particle_perimeter_from_mask",
17
+ ]
18
+
19
+ SHADOWED = 48 # ASCII '0': an illuminated-diode / shadowed pixel
20
+ BACKGROUND = 49 # ASCII '1': background, also used for the padded border
21
+
22
+
23
+ def particle_perimeter(image_buffer):
24
+ """Faithful port of ParticlePerimeter.m.
25
+
26
+ image_buffer: 2D sequence of ASCII codes (int), where SHADOWED (48)
27
+ marks a shadowed pixel and any other value is background.
28
+
29
+ Perimeter = count of shadowed pixels with at least one 4-connected
30
+ non-shadowed neighbor (the image is implicitly padded with
31
+ BACKGROUND on all sides, matching the original's `c1` padding).
32
+
33
+ "Any other value is background" is the original's behaviour, not an
34
+ interpretation of it: ParticlePerimeter.m tests `48==c1(i,j)` and
35
+ nothing else. Checked against MATLAB's own output for a code of 50 in
36
+ `tests/test_particle_perimeter_oracle.py`, along with the three
37
+ degenerate shapes (0x0, 3x0, 0x5) where a transcription of the
38
+ `2:m+1` loops can diverge silently.
39
+ """
40
+ m = len(image_buffer)
41
+ n = len(image_buffer[0]) if m else 0
42
+
43
+ padded = [[BACKGROUND] * (n + 2) for _ in range(m + 2)]
44
+ for i in range(m):
45
+ for j in range(n):
46
+ padded[i + 1][j + 1] = image_buffer[i][j]
47
+
48
+ perimeter = 0
49
+ for i in range(1, m + 1):
50
+ for j in range(1, n + 1):
51
+ if padded[i][j] == SHADOWED and (
52
+ padded[i + 1][j] != SHADOWED
53
+ or padded[i - 1][j] != SHADOWED
54
+ or padded[i][j + 1] != SHADOWED
55
+ or padded[i][j - 1] != SHADOWED
56
+ ):
57
+ perimeter += 1
58
+ return perimeter
59
+
60
+
61
+ def particle_perimeter_setbased(image_buffer):
62
+ """Independent re-derivation of the same quantity, for cross-validation.
63
+
64
+ Treats shadowed pixels as a coordinate set and counts those with at
65
+ least one of their 4 neighbors missing from the set -- neighbors
66
+ that fall outside the image bounds count as "missing" too, which
67
+ reproduces the original's background-padding behavior without
68
+ building an explicit padded array. Written independently from
69
+ particle_perimeter() above so that the two implementations agree
70
+ only if the underlying logic (not just the code) is correct.
71
+ """
72
+ m = len(image_buffer)
73
+ n = len(image_buffer[0]) if m else 0
74
+ shadowed = {
75
+ (i, j)
76
+ for i in range(m)
77
+ for j in range(n)
78
+ if image_buffer[i][j] == SHADOWED
79
+ }
80
+
81
+ perimeter = 0
82
+ for (i, j) in shadowed:
83
+ neighbors = ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1))
84
+ if any(nb not in shadowed for nb in neighbors):
85
+ perimeter += 1
86
+ return perimeter
87
+
88
+
89
+ def particle_perimeter_from_mask(mask):
90
+ """Convenience wrapper: mask is a 2D sequence of bool, True = shadowed.
91
+
92
+ Source: wraps the port of ``ParticlePerimeter.m:9-22`` (UIOOPS v3.1.4)."""
93
+ img = [[SHADOWED if v else BACKGROUND for v in row] for row in mask]
94
+ return particle_perimeter(img)
@@ -0,0 +1,199 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Single-particle area, mass, and terminal-velocity relations (UIOOPS v3.5).
3
+
4
+ Ported from: single_area.m, single_mass.m (UIOOPS v3.5, both CHANGED from
5
+ v3.1.4) and single_vt.m. ``single_vt.m`` is byte-identical between the two
6
+ versions, so ``single_vt`` below is the one translation both engines use:
7
+ ``arrayprobe.particle_physics`` re-exports this object lazily
8
+ rather than carrying a second translation -- see ``arrayprobe_uiops.__init__`` and
9
+ ``tests/test_v35_reuse_byte_identity.py``.
10
+
11
+ **What changed.** v3.5 added a required third argument, ``iNewHabit``, to
12
+ both ``single_area`` and ``single_mass``. It selects between two habit-code
13
+ groupings for the SAME set of area-diameter / mass-diameter power laws --
14
+ no coefficient changed, only which habit codes route to which law:
15
+
16
+ - ``i_new_habit=False`` (``iNewHabit=0``, "original Holroyd classifications"):
17
+ byte-identical grouping to v3.1.4's single_area.m/single_mass.m.
18
+ - ``i_new_habit=True`` (``iNewHabit=1``, "modified Holroyd classifications"):
19
+ habit ``'o'`` (Oriented) moves out of the linear/'l' bucket and into the
20
+ irregular bucket in BOTH functions. This also makes single_area's and
21
+ single_mass's irregular buckets agree on which codes they contain where
22
+ they did not before -- v3.1.4's asymmetry (single_area's irregular bucket
23
+ is ``{'i','a','s','t'}``, single_mass's is only ``{'i','a'}``) is preserved
24
+ in both branches here exactly as measured; ``i_new_habit`` does not touch
25
+ that asymmetry, it only touches where ``'o'`` and ``'l'`` route.
26
+
27
+ No default is given for ``i_new_habit`` -- it changes computed output, so
28
+ silently picking a side is refused, matching the project's
29
+ "no default silently picks a side" rule (see ``FidelityProfile``).
30
+
31
+ Confirmed against UIOOPS v3.5 run directly under Octave 11.3.0
32
+ (``UIOPS-v3.5/joefinlon-UIOPS-039be82/single_area.m``, ``single_mass.m``), 80 diameter/habit/
33
+ i_new_habit combinations, golden fixture
34
+ ``tests/data/v35_particle_physics_octave_golden.csv``
35
+ (``tests/test_v35_particle_physics.py``).
36
+ """
37
+
38
+ __all__ = [
39
+ "single_area",
40
+ "single_mass",
41
+ "single_vt",
42
+ ]
43
+
44
+ import math
45
+ from typing import Any
46
+
47
+
48
+ def single_area(diameter: Any, habit: Any, i_new_habit: Any) -> Any:
49
+ """Particle cross-sectional area (mm^2) from diameter (cgs, cm), habit code,
50
+ and the v3.5 habit-scheme selector.
51
+
52
+ Direct port of v3.5's single_area.m. Unrecognized habit codes return 0.0,
53
+ matching the original's uninitialized-`area`-stays-0 behavior.
54
+ """
55
+ # MATLAB's `switch char(habit)` is case-sensitive: an uppercase code matches no case and
56
+ # returns 0. Holroyd emits lowercase except 'M' and 'C', which match nothing either way.
57
+ habit = str(habit)
58
+ area = 0.0
59
+
60
+ if not i_new_habit: # original Holroyd classifications
61
+ if habit in ('l', 'o'): # Linear and Oriented
62
+ if diameter < 0.03:
63
+ a, b = 0.0696, 1.5
64
+ else:
65
+ a, b = 0.0512, 1.414
66
+ area = a * diameter ** b
67
+ elif habit == 'h': # Plate
68
+ a, b = 0.65, 2.0
69
+ area = a * diameter ** b
70
+ elif habit in ('i', 'a', 's', 't'): # Irregular
71
+ a, b = 0.2285, 1.88
72
+ area = a * diameter ** b
73
+ elif habit == 'g': # Graupel
74
+ a, b = 0.5, 2.0
75
+ area = a * diameter ** b
76
+ elif habit == 'd': # Dendrite
77
+ a, b = 0.21, 1.76
78
+ area = a * diameter ** b
79
+ else: # modified Holroyd classifications
80
+ if habit == 'l': # Linear
81
+ if diameter < 0.03:
82
+ a, b = 0.0696, 1.5
83
+ else:
84
+ a, b = 0.0512, 1.414
85
+ area = a * diameter ** b
86
+ elif habit == 'h': # Plate
87
+ a, b = 0.65, 2.0
88
+ area = a * diameter ** b
89
+ elif habit in ('i', 'a', 's', 't', 'o'): # Irregular, aggregate, sphere, tiny, bad
90
+ a, b = 0.2285, 1.88
91
+ area = a * diameter ** b
92
+ elif habit == 'g': # Graupel
93
+ a, b = 0.5, 2.0
94
+ area = a * diameter ** b
95
+ elif habit == 'd': # Dendrite
96
+ a, b = 0.21, 1.76
97
+ area = a * diameter ** b
98
+
99
+ return area * 100 # cgs -> mm^2, per original comment
100
+
101
+
102
+ def single_mass(diameter: Any, habit: Any, i_new_habit: Any) -> Any:
103
+ """Particle ice water content / mass (cgs) from diameter, habit code, and
104
+ the v3.5 habit-scheme selector.
105
+
106
+ Direct port of v3.5's single_mass.m. Unrecognized habit codes return 0.0.
107
+ """
108
+ # MATLAB's `switch char(habit)` is case-sensitive: an uppercase code matches no case and
109
+ # returns 0. Holroyd emits lowercase except 'M' and 'C', which match nothing either way.
110
+ habit = str(habit)
111
+ iwc = 0.0
112
+
113
+ if not i_new_habit: # original Holroyd classifications
114
+ if habit in ('s', 't'): # Sphere and Tiny
115
+ a, b = 0.00294, 1.9
116
+ iwc = a * diameter ** b
117
+ elif habit in ('l', 'o'): # Linear and Oriented
118
+ if diameter < 0.03:
119
+ a, b = 0.001666, 1.91
120
+ else:
121
+ a, b = 0.000907, 1.74
122
+ iwc = a * diameter ** b
123
+ elif habit == 'h': # Plate
124
+ a, b = 0.00739, 2.45
125
+ iwc = a * diameter ** b
126
+ elif habit in ('i', 'a'): # Irregular
127
+ a, b = 0.00294, 1.9
128
+ iwc = a * diameter ** b
129
+ elif habit == 'g': # Graupel
130
+ a, b = 0.049, 2.8
131
+ iwc = a * diameter ** b
132
+ elif habit == 'd': # Dendrite
133
+ a, b = 0.000516, 1.8
134
+ iwc = a * diameter ** b
135
+ else: # modified Holroyd classifications
136
+ if habit in ('s', 't'): # Sphere and Tiny
137
+ a, b = 0.00294, 1.9
138
+ iwc = a * diameter ** b
139
+ elif habit == 'l': # Linear (columnar)
140
+ if diameter < 0.03:
141
+ a, b = 0.001666, 1.91
142
+ else:
143
+ a, b = 0.000907, 1.74
144
+ iwc = a * diameter ** b
145
+ elif habit == 'h': # Plate
146
+ a, b = 0.00739, 2.45
147
+ iwc = a * diameter ** b
148
+ elif habit in ('i', 'a', 'o'): # Irregular, aggregate, bad/undetermined
149
+ a, b = 0.00294, 1.9
150
+ iwc = a * diameter ** b
151
+ elif habit == 'g': # Graupel
152
+ a, b = 0.049, 2.8
153
+ iwc = a * diameter ** b
154
+ elif habit == 'd': # Dendrite
155
+ a, b = 0.000516, 1.8
156
+ iwc = a * diameter ** b
157
+
158
+ return iwc
159
+
160
+
161
+ def single_vt(diameter: Any, area_ratio: Any, mass: Any, pressure_hpa: Any, temp_c: Any,
162
+ use_mitchell: Any = False) -> Any:
163
+ """Terminal fall velocity for a single particle.
164
+
165
+ Direct port of single_vt.m. Default method is Heymsfield & Westbrook
166
+ (2010); pass use_mitchell=True for the Mitchell (1996) method (a
167
+ special case of Heymsfield & Westbrook with k=0, drag C=0.6,
168
+ epsilon=5.83).
169
+
170
+ Units, matching the original: diameter/mass in metric (m, kg),
171
+ pressure in hPa, temperature in Celsius.
172
+
173
+ Note: the original hardcodes `pi=3.1415926` as a local variable
174
+ (shadowing MATLAB's built-in, full-precision `pi`), rather than
175
+ using the built-in constant. That literal is preserved here
176
+ deliberately -- swapping in math.pi would be a (tiny) numerical
177
+ behavior change from the original, not a pure translation.
178
+ """
179
+ g = 9.8
180
+ pi = 3.1415926 # deliberately not math.pi -- see docstring note
181
+
182
+ t_k = temp_c + 273.15
183
+ p_pa = pressure_hpa * 100
184
+ rho_a = p_pa / (287.15 * t_k)
185
+ # Sutherland's formula for dynamic viscosity
186
+ eta = 18.27 * (291.15 + 120) / (t_k + 120) * (t_k / 291.15) ** 1.5 / 1e6
187
+ nu = eta / rho_a # kinematic viscosity
188
+
189
+ if not use_mitchell:
190
+ # Modified Best Number, Heymsfield & Westbrook (2010), drag C=0.35, epsilon=8.0
191
+ x = rho_a / (eta ** 2) * 8 * mass * g / (pi * area_ratio ** 0.5)
192
+ reynolds = 16 * (math.sqrt(1 + 4 * math.sqrt(x) / 64 / math.sqrt(0.35)) - 1) ** 2
193
+ else:
194
+ # Modified Best Number, Mitchell (1996), drag C=0.6, epsilon=5.83
195
+ x = rho_a / (eta ** 2) * 8 * mass * g / (pi * area_ratio)
196
+ reynolds = 5.83 ** 2 / 4 * (
197
+ math.sqrt(1 + 4 * math.sqrt(x) / (5.83 ** 2) / math.sqrt(0.6)) - 1) ** 2
198
+
199
+ return nu / diameter * reynolds