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,488 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """What the triage pages show beside a particle that its product does not state outright.
3
+
4
+ Four things, each read or recomputed from data the server already holds, never written into a
5
+ product (the triage server changes no computed number):
6
+
7
+ * :func:`reject_outcome` — what the size distribution does with a particle of each automatic
8
+ reject code: kept as is, kept with its size corrected, or rejected.
9
+ * :func:`shape_test_habit` — Holroyd's shape test re-run on the particle's own image. UIOOPS
10
+ v3.5's ``imgProc_sm.m:1218-1236`` (the ungated "[EXPERIMENTAL]" hollow block) writes habit
11
+ ``'s'`` for any particle under 0.3 mm whose enclosing-circle centre pixel is unshadowed,
12
+ without running the shape test, so the letter in a v3.5 file is no evidence of shape there:
13
+ on the 2018-02-15 ARM flight 99.2 % of its ``'s'`` particles came from that block (measured
14
+ 2026-10-01, every 50th particle). Where the block did not act, the re-run agrees with the
15
+ file letter for every particle measured (the 200-item all-codes queue of that flight).
16
+ * :func:`particle_parts` — the separate pieces of shadow in an image, numbered in order along
17
+ the flight, so a reviewer can say which piece of a two-particle image is real; fragments
18
+ within :data:`PIECE_GAP_DIODES` empty diodes of each other count as one piece.
19
+ * :class:`MetFolder` — the ambient air temperature at the particle's record time, from ARM's
20
+ merged aircraft files (``enaaafmergedF1.c1.<date>.<time>.nc``, ``ambient_temp`` in °C, one
21
+ row per second).
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import re
26
+ import threading
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ import numpy as np
31
+
32
+ from arrayprobe_uiops.sizedist_core import GOOD_REJECT_CODES
33
+
34
+ __all__ = [
35
+ "REJECT_OUTCOMES", "LATER_SCREENS_NOTE", "reject_outcome",
36
+ "shape_test_habit", "particle_parts", "piece_groups", "PIECE_GAP_DIODES", "MetFolder",
37
+ "PIECE_COUNT_CLASSES", "PIECE_COUNT_WORDS", "count_class", "piece_count_class",
38
+ ]
39
+
40
+ #: The codes the size distribution keeps, with what happens to each. The kept set is
41
+ #: ``sizeDist.m:1460`` in v3.5 and ``:1209`` in v3.1.4, the same five letters both times
42
+ #: (:data:`arrayprobe.sizedist.GOOD_REJECT_CODES`); every other code is rejected. ``'H'`` is
43
+ #: the only kept code whose size changes: ``imgProc_sm.m:1275-1276`` (v3.5) divides its
44
+ #: smallest-circle diameter by the Korolev hollow-particle size factor.
45
+ REJECT_OUTCOMES: dict[str, tuple[str, str]] = {
46
+ "0": ("kept", "kept as is"),
47
+ "h": ("kept", "kept as is: hollow, but no hole ratio to correct its size with"),
48
+ "u": ("kept", "kept as is: hollow, but its hole is too small to correct its size"),
49
+ "H": ("corrected", "kept with its size corrected: the smallest-circle diameter is divided "
50
+ "by the Korolev hollow-particle factor"),
51
+ "R": ("kept", "kept again: the shattering screen removed it and the re-acceptance put it "
52
+ "back"),
53
+ }
54
+
55
+ if set(REJECT_OUTCOMES) != set(GOOD_REJECT_CODES): # the page must never mislabel a code
56
+ raise ImportError(f"REJECT_OUTCOMES {sorted(REJECT_OUTCOMES)} disagrees with "
57
+ f"sizedist.GOOD_REJECT_CODES {GOOD_REJECT_CODES!r}")
58
+
59
+ #: What the particle file cannot say: the size distribution's own later screens.
60
+ LATER_SCREENS_NOTE = (
61
+ "A kept particle can still be dropped by the size distribution's later screens "
62
+ "(shattering, inter-arrival time, area ratio, a centre outside the sample area); "
63
+ "the particle file does not record those.")
64
+
65
+
66
+ def reject_outcome(code) -> tuple[str, str] | None:
67
+ """``(kind, words)`` for an automatic reject code; ``kind`` is ``"kept"``,
68
+ ``"corrected"`` or ``"rejected"``. ``None`` when there is no code to describe."""
69
+ if not isinstance(code, str) or not code:
70
+ return None
71
+ if code in REJECT_OUTCOMES:
72
+ return REJECT_OUTCOMES[code]
73
+ return ("rejected", "rejected: not counted in the size distribution")
74
+
75
+
76
+ def shape_test_habit(c, diode_mm: float) -> str:
77
+ """Holroyd's habit letter from the shape test alone, on the boolean silhouette ``c``
78
+ (``(n_slices, n_diodes)``, the whole record width as ``imgProc_sm`` passes it).
79
+
80
+ Uses the v3.5 port's ``holroyd`` (``holroyd.m:7-89`` of v3.5), whose decision tree has
81
+ no stub, so it answers the shape question for files of either engine.
82
+ """
83
+ from arrayprobe_uiops.habit import holroyd
84
+
85
+ letter, _ = holroyd(np.asarray(c, dtype=bool), diode_mm)
86
+ return letter
87
+
88
+
89
+ def piece_groups(c, gap: int = 0, scale: str = "constant") -> list[np.ndarray]:
90
+ """The 8-connected pieces of ``c`` grouped single-linkage when the gap between their
91
+ nearest pixels is at most ``gap`` diodes; one boolean mask per group.
92
+
93
+ The gap is the Chebyshev distance between the nearest pixels less one, i.e. the number of
94
+ empty pixels between them, so ``gap=0`` is plain 8-connectivity. Exact: dilating every
95
+ pixel by a ``(gap+1)``-square makes two pixels 8-adjacent iff their Chebyshev distance
96
+ is at most ``gap + 1``, so the dilation's components are the single-linkage groups.
97
+
98
+ ``scale="larger"`` (opt-in) makes the allowed gap size-scaled: two 8-connected
99
+ components join when their gap is at most ``min(gap, extent of the larger of the two)``,
100
+ extent being ``max(bbox height, bbox width)`` in pixels, single linkage; ``gap`` is then
101
+ the cap. Measured on 441 hand labels of 2018-02-15 with cap 12 it agrees with 393
102
+ against 388 for the best constant gap. The default, ``"constant"``, is unchanged.
103
+ """
104
+ from scipy import ndimage
105
+
106
+ if scale not in ("constant", "larger"):
107
+ raise ValueError(f"scale must be 'constant' or 'larger', got {scale!r}")
108
+ c = np.asarray(c, dtype=bool)
109
+ if c.size == 0 or not c.any():
110
+ return []
111
+ if scale == "larger":
112
+ return _piece_groups_larger(c, gap)
113
+ eight = np.ones((3, 3), dtype=int)
114
+ if gap <= 0:
115
+ labels, count = ndimage.label(c, structure=eight)
116
+ else:
117
+ pad = gap + 1
118
+ big = np.pad(c, pad)
119
+ grown = ndimage.binary_dilation(big, structure=np.ones((gap + 1, gap + 1), dtype=bool))
120
+ labels, count = ndimage.label(grown, structure=eight)
121
+ labels = labels[pad:-pad, pad:-pad] * c
122
+ return [labels == lab for lab in range(1, count + 1) if (labels == lab).any()]
123
+
124
+
125
+
126
+ def _piece_groups_larger(c: np.ndarray, cap: int) -> list[np.ndarray]:
127
+ """:func:`piece_groups` with ``scale="larger"``: pairwise gaps, size-scaled threshold."""
128
+ from scipy import ndimage
129
+
130
+ labels, count = ndimage.label(c, structure=np.ones((3, 3), dtype=int))
131
+ masks = [labels == lab for lab in range(1, count + 1)]
132
+ extents = []
133
+ for m in masks:
134
+ rr, cc = np.nonzero(m)
135
+ extents.append(max(int(rr.max() - rr.min()) + 1, int(cc.max() - cc.min()) + 1))
136
+ parent = list(range(count))
137
+
138
+ def find(i: int) -> int:
139
+ while parent[i] != i:
140
+ parent[i] = parent[parent[i]]
141
+ i = parent[i]
142
+ return i
143
+
144
+ for i in range(count):
145
+ # Chebyshev distance from every pixel to component i's nearest pixel.
146
+ dist = ndimage.distance_transform_cdt(~masks[i], metric="chessboard")
147
+ for j in range(i + 1, count):
148
+ pair_gap = int(dist[masks[j]].min()) - 1
149
+ if pair_gap <= min(cap, max(extents[i], extents[j])):
150
+ ri, rj = find(i), find(j)
151
+ if ri != rj:
152
+ parent[rj] = ri
153
+ groups: dict[int, np.ndarray] = {}
154
+ for i in range(count):
155
+ r = find(i)
156
+ groups[r] = groups[r] | masks[i] if r in groups else masks[i].copy()
157
+ return [groups[r] for r in sorted(groups)]
158
+
159
+ #: Pieces whose nearest pixels are at most this many empty diodes apart are drawn and numbered
160
+ #: as one particle. Set to 8. Measured against 441 hand labels
161
+ #: of 2018-02-15, G = 7 and G = 8 both agree with 388, the maximum; G = 8
162
+ #: joins one more real crystal (6 split, against 7) and merges two of the 27 two-particle
163
+ #: labels.
164
+ PIECE_GAP_DIODES = 8
165
+
166
+
167
+ def particle_parts(c, gap: int = PIECE_GAP_DIODES, scale: str = "constant") -> list[dict]:
168
+ """The separate pieces of shadow in ``c``, numbered 1, 2, … in order along the flight.
169
+
170
+ A piece is a group of 8-connected components whose nearest pixels are at most ``gap``
171
+ empty diodes apart (:func:`piece_groups`; ``gap=0`` is plain 8-connectivity), so one
172
+ fragmented crystal is one piece. Order is by first slice, then first diode, so piece 1 is
173
+ the one the probe met first. Each entry: ``n``, ``pixels``, ``row``/``col`` (centroid, in
174
+ pixels), ``rows``/``cols`` (inclusive first and last). Display only. ``scale`` is passed
175
+ to :func:`piece_groups` (``"larger"``: size-scaled gap, ``gap`` the cap).
176
+ """
177
+ parts: list[dict[str, Any]] = []
178
+ for mask in piece_groups(c, gap, scale):
179
+ rr, cc = np.nonzero(mask)
180
+ parts.append({"pixels": int(rr.size), "row": float(rr.mean()), "col": float(cc.mean()),
181
+ "rows": (int(rr.min()), int(rr.max())),
182
+ "cols": (int(cc.min()), int(cc.max()))})
183
+ parts.sort(key=lambda p: (p["rows"][0], p["cols"][0]))
184
+ for n, p in enumerate(parts, start=1):
185
+ p["n"] = n
186
+ return parts
187
+
188
+
189
+ #: The particle-count schema: an image holds
190
+ #: one piece, two, or three or more, counted with the size-scaled gap capped at
191
+ #: :data:`PIECE_GAP_DIODES`. Display and labelling only; no computed number reads it.
192
+ PIECE_COUNT_CLASSES = ("one", "two", "three_or_more")
193
+ PIECE_COUNT_WORDS = {"one": "one particle", "two": "two particles",
194
+ "three_or_more": "three or more particles"}
195
+
196
+
197
+ def count_class(n: int) -> str | None:
198
+ """A piece count as its :data:`PIECE_COUNT_CLASSES` entry; ``None`` for no pieces."""
199
+ if n <= 0:
200
+ return None
201
+ return PIECE_COUNT_CLASSES[min(n, 3) - 1]
202
+
203
+
204
+ def piece_count_class(c, gap: int = PIECE_GAP_DIODES, scale: str = "larger") -> str | None:
205
+ """How many particles ``c`` shows under the particle-count schema: ``"one"``, ``"two"`` or
206
+ ``"three_or_more"`` (``None`` for an empty image).
207
+
208
+ Pieces are :func:`piece_groups` with the size-scaled gap by default (``scale="larger"``:
209
+ two components join when the empty diodes between them are at most
210
+ ``min(gap, extent of the larger)``), so specks much smaller than ``gap`` stay separate.
211
+ The gap is counted in diodes, so the rule reads the same at every probe resolution; its
212
+ physical width is ``gap`` times the diode size. Display only.
213
+ """
214
+ return count_class(len(piece_groups(c, gap, scale)))
215
+
216
+ _MERGED_NAME = re.compile(r"^enaaafmergedF1\.c1\.(\d{8})\.(\d{6})\.nc$")
217
+ #: ORACLES P-3 merge files (``mrg1_P3_<date>_R<rev>.nc``): ``Static_Air_Temp`` in degC on
218
+ #: ``Start_UTC``, seconds after midnight UTC of the file's date.
219
+ _ORACLES_MERGE_NAME = re.compile(r"^mrg1_P3_(\d{8})_R\d+\.nc$")
220
+ _TIME_UNITS = re.compile(r"^seconds since (\d{4})-(\d{2})-(\d{2})[ T]00:00:00")
221
+
222
+
223
+ class MetFolder:
224
+ """ARM AAF merged files in one folder, read once each, for the temperature at a second.
225
+
226
+ ``temperature_at(yyyymmdd, hhmmss)`` returns ``(degC, file name)`` for the row at that
227
+ second, or ``None`` when no file of that date holds a valid value there. A value is
228
+ invalid when masked, not finite, or at or below -9990 (the files' missing-value
229
+ convention). The time axis is checked,
230
+ not assumed: ``time``'s units must be "seconds since <the file's date> 00:00:00".
231
+ """
232
+
233
+ VARIABLE = "ambient_temp"
234
+
235
+ def __init__(self, folder: Path):
236
+ self.folder = Path(folder)
237
+ self._by_date: dict[str, list[Path]] = {}
238
+ for p in sorted(self.folder.glob("enaaafmergedF1.c1.*.nc")):
239
+ m = _MERGED_NAME.match(p.name)
240
+ if m:
241
+ self._by_date.setdefault(m.group(1), []).append(p)
242
+ for p in sorted(self.folder.glob("mrg1_P3_*.nc")):
243
+ m = _ORACLES_MERGE_NAME.match(p.name)
244
+ if m:
245
+ self._by_date.setdefault(m.group(1), []).append(p)
246
+ self._cache: dict[Path, tuple[np.ndarray, np.ndarray] | None] = {}
247
+ self._lock = threading.Lock()
248
+
249
+ def __len__(self) -> int:
250
+ return sum(len(v) for v in self._by_date.values())
251
+
252
+ def _load(self, path: Path):
253
+ import netCDF4
254
+
255
+ with self._lock:
256
+ if path in self._cache:
257
+ return self._cache[path]
258
+ loaded = None
259
+ if _ORACLES_MERGE_NAME.match(path.name):
260
+ loaded = self._load_oracles(path)
261
+ self._cache[path] = loaded
262
+ return loaded
263
+ with netCDF4.Dataset(path) as ds:
264
+ tv = ds.variables.get("time")
265
+ m = _TIME_UNITS.match(getattr(tv, "units", "") or "") if tv is not None else None
266
+ name = _MERGED_NAME.match(path.name)
267
+ assert name is not None # only names matching _MERGED_NAME are indexed
268
+ date = name.group(1)
269
+ if (tv is not None and m and "".join(m.groups()) == date
270
+ and self.VARIABLE in ds.variables):
271
+ t = np.ma.filled(np.ma.asarray(tv[:]).astype(float), np.nan)
272
+ v = np.ma.filled(np.ma.asarray(ds.variables[self.VARIABLE][:]).astype(float),
273
+ np.nan)
274
+ v[v <= -9990] = np.nan
275
+ loaded = (t, v)
276
+ self._cache[path] = loaded
277
+ return loaded
278
+
279
+ @staticmethod
280
+ def _load_oracles(path: Path):
281
+ """``(seconds of day, degC)`` from an ORACLES merge file, or ``None``.
282
+
283
+ ``Start_UTC`` must be in "seconds", and the epoch ``time`` axis minus ``Start_UTC``
284
+ must land on midnight UTC of the date in the file name, so a mislabelled file reads
285
+ as no temperature rather than a wrong one."""
286
+ import datetime as _dt
287
+
288
+ import netCDF4
289
+
290
+ m = _ORACLES_MERGE_NAME.match(path.name)
291
+ if m is None: # callers pass only names the pattern matched (:214, :230)
292
+ return None
293
+ date = m.group(1)
294
+ with netCDF4.Dataset(path) as ds:
295
+ su, tv, temp = (ds.variables.get(k) for k in ("Start_UTC", "time", "Static_Air_Temp"))
296
+ if su is None or temp is None or (getattr(su, "units", "") or "").strip() != "seconds":
297
+ return None
298
+ t = np.ma.filled(np.ma.asarray(su[:]).astype(float), np.nan)
299
+ if tv is not None and t.size:
300
+ um = re.match(r"^seconds since 1970-01-01[ T]00:00:00",
301
+ getattr(tv, "units", "") or "")
302
+ epoch = np.ma.filled(np.ma.asarray(tv[:1]).astype(float), np.nan)
303
+ midnight = _dt.datetime.strptime(date, "%Y%m%d").replace(
304
+ tzinfo=_dt.UTC).timestamp()
305
+ if not um or not np.isfinite(epoch[0]) or abs(epoch[0] - t[0] - midnight) > 1.0:
306
+ return None
307
+ v = np.ma.filled(np.ma.asarray(temp[:]).astype(float), np.nan)
308
+ v[v <= -9990] = np.nan
309
+ return t, v
310
+
311
+ def temperature_at(self, yyyymmdd, hhmmss) -> tuple[float, str] | None:
312
+ """``(degC, file name)`` for the row at the record second ``hhmmss`` (UTC) of date
313
+ ``yyyymmdd``, from the first file of that date holding a valid value; ``None`` otherwise."""
314
+ try:
315
+ date = f"{int(yyyymmdd):08d}"
316
+ hms = int(hhmmss)
317
+ except (TypeError, ValueError):
318
+ return None
319
+ sec = (hms // 10000) * 3600 + (hms // 100 % 100) * 60 + hms % 100
320
+ for path in self._by_date.get(date, []):
321
+ loaded = self._load(path)
322
+ if loaded is None:
323
+ continue
324
+ t, v = loaded
325
+ hit = np.flatnonzero(t == sec)
326
+ if hit.size and np.isfinite(v[hit[0]]):
327
+ return float(v[hit[0]]), path.name
328
+ return None
329
+
330
+
331
+ class StateFileError(ValueError):
332
+ """A state-variable file that cannot give the air temperature unambiguously."""
333
+
334
+
335
+ _CF_TIME_UNITS = re.compile(
336
+ r"^\s*(seconds?|minutes?|hours?|days?)\s+since\s+(\d{4})-(\d{1,2})-(\d{1,2})"
337
+ r"(?:[ T](\d{1,2}):(\d{2})(?::(\d{2}(?:\.\d*)?))?)?\s*(?:Z|UTC|\+0+(?::?0+)?)?\s*$",
338
+ re.IGNORECASE)
339
+ _UNIT_SECONDS = {"second": 1.0, "minute": 60.0, "hour": 3600.0, "day": 86400.0}
340
+ _CELSIUS_UNITS = {"degc", "deg_c", "deg c", "°c", "c", "celsius", "degree_celsius",
341
+ "degrees_celsius", "degrees c", "degree c"}
342
+ _KELVIN_UNITS = {"k", "kelvin", "degk", "deg_k", "degrees_kelvin"}
343
+ #: Words that mark a temperature as something other than the static air temperature.
344
+ _NOT_AIR = ("dew", "frost", "potential", "virtual", "total", "skin", "surface", "brightness",
345
+ "equivalent", "wet_bulb", "wet bulb", "wetbulb", "cabin", "housing", "inlet",
346
+ "sensor", "instrument", "probe", "flag", "uncertainty", "std", "qc")
347
+
348
+
349
+ def _attr(var, name: str) -> str:
350
+ return str(getattr(var, name, "") or "").strip()
351
+
352
+
353
+ def _temperature_scale(var) -> str | None:
354
+ """``"C"`` or ``"K"`` from a variable's units, else ``None``."""
355
+ u = _attr(var, "units").lower()
356
+ if u in _CELSIUS_UNITS:
357
+ return "C"
358
+ if u in _KELVIN_UNITS:
359
+ return "K"
360
+ return None
361
+
362
+
363
+ def _cf_time_origin(var) -> tuple[float, float] | None:
364
+ """``(epoch seconds of the origin, seconds per unit)`` for a CF time axis, else ``None``."""
365
+ import datetime as _dt
366
+
367
+ m = _CF_TIME_UNITS.match(_attr(var, "units"))
368
+ if not m:
369
+ return None
370
+ unit = m.group(1).lower().rstrip("s")
371
+ y, mo, d = (int(g) for g in m.group(2, 3, 4))
372
+ hh, mm = int(m.group(5) or 0), int(m.group(6) or 0)
373
+ ss = float(m.group(7) or 0.0)
374
+ origin = _dt.datetime(y, mo, d, hh, mm, tzinfo=_dt.UTC).timestamp() + ss
375
+ return origin, _UNIT_SECONDS[unit]
376
+
377
+
378
+ def detect_state_variables(ds, var: str | None = None) -> tuple[str, str]:
379
+ """``(temperature variable, time variable)`` in an open netCDF ``ds``, chosen by content.
380
+
381
+ The temperature is a 1-D variable whose units are a temperature (degC/C/K and their
382
+ spellings). With ``var`` given, that variable is used and only checked. Otherwise the
383
+ candidates are ranked: ``standard_name = air_temperature`` first, then a name or
384
+ long_name saying static or ambient air temperature, then any other temperature whose
385
+ name, long_name and standard_name carry none of :data:`_NOT_AIR` (dew point, total,
386
+ potential, ...). More than one candidate in the best rank is refused, listing them, so
387
+ a file never silently gives the wrong temperature. The time variable is the 1-D CF time
388
+ axis ("<unit> since <date>") on the temperature's dimension; more than one is refused.
389
+ """
390
+ vars_ = ds.variables
391
+ if var is not None:
392
+ if var not in vars_:
393
+ found = sorted(n for n in vars_ if _temperature_scale(vars_[n]))
394
+ raise StateFileError(f"no variable {var!r} in the file; temperature-like "
395
+ f"variables: {found}")
396
+ if _temperature_scale(vars_[var]) is None or vars_[var].ndim != 1:
397
+ raise StateFileError(f"{var!r} is not a 1-D temperature (units "
398
+ f"{_attr(vars_[var], 'units')!r}; need degC, C or K)")
399
+ temp = var
400
+ else:
401
+ ranks: dict[int, list[str]] = {}
402
+ for name, v in vars_.items():
403
+ if v.ndim != 1 or _temperature_scale(v) is None:
404
+ continue
405
+ text = " ".join((name, _attr(v, "long_name"), _attr(v, "standard_name"))).lower()
406
+ if _attr(v, "standard_name").lower() == "air_temperature":
407
+ rank = 0
408
+ elif any(w in text for w in _NOT_AIR):
409
+ continue
410
+ elif "static" in text or "ambient" in text:
411
+ rank = 1
412
+ elif "temp" in text:
413
+ rank = 2
414
+ else:
415
+ continue
416
+ ranks.setdefault(rank, []).append(name)
417
+ if not ranks:
418
+ raise StateFileError("no air-temperature variable found (looked for a 1-D variable "
419
+ "with units degC, C or K); name one with --state-var")
420
+ best = ranks[min(ranks)]
421
+ if len(best) > 1:
422
+ raise StateFileError(f"ambiguous air temperature: candidates {', '.join(best)}; "
423
+ "name one with --state-var")
424
+ temp = best[0]
425
+ dim = vars_[temp].dimensions[0]
426
+ times = [n for n, v in vars_.items()
427
+ if v.ndim == 1 and v.dimensions[0] == dim and _cf_time_origin(v) is not None]
428
+ if len(times) > 1 and dim in times:
429
+ times = [dim]
430
+ if not times:
431
+ raise StateFileError(f"no CF time axis ('<unit> since <date>') on {temp!r}'s dimension "
432
+ f"{dim!r} to align on")
433
+ if len(times) > 1:
434
+ raise StateFileError(f"ambiguous time axis for {temp!r}: candidates {', '.join(times)}")
435
+ return temp, times[0]
436
+
437
+
438
+ class StateFile:
439
+ """One state-variable file named by the user, for the temperature at a second.
440
+
441
+ The same interface as :class:`MetFolder` (``temperature_at``, ``folder``, ``VARIABLE``,
442
+ ``len``) so the particle page reads either. The variables are chosen by
443
+ :func:`detect_state_variables` at construction, so a file that cannot give an
444
+ unambiguous temperature is refused when it is named, not on the first particle.
445
+ """
446
+
447
+ def __init__(self, path: Path, var: str | None = None):
448
+ import netCDF4
449
+
450
+ self.path = Path(path)
451
+ self.folder = self.path
452
+ if not self.path.is_file():
453
+ raise StateFileError(f"no such file: {self.path}")
454
+ try:
455
+ ds = netCDF4.Dataset(self.path)
456
+ except OSError as e:
457
+ raise StateFileError(f"not a readable netCDF file: {self.path} ({e})") from e
458
+ with ds:
459
+ temp, time = detect_state_variables(ds, var)
460
+ origin, scale = _cf_time_origin(ds.variables[time]) # type: ignore[misc]
461
+ t = np.ma.filled(np.ma.asarray(ds.variables[time][:]).astype(float), np.nan)
462
+ v = np.ma.filled(np.ma.asarray(ds.variables[temp][:]).astype(float), np.nan)
463
+ kelvin = _temperature_scale(ds.variables[temp]) == "K"
464
+ v[v <= -9990] = np.nan
465
+ if kelvin:
466
+ v = v - 273.15
467
+ self.VARIABLE = temp
468
+ self.time_variable = time
469
+ self._epoch = np.round(origin + t * scale)
470
+ self._v = v
471
+
472
+ def __len__(self) -> int:
473
+ return 1
474
+
475
+ def temperature_at(self, yyyymmdd, hhmmss) -> tuple[float, str] | None:
476
+ """``(degC, file name)`` at the record second, or ``None`` when no valid value."""
477
+ import datetime as _dt
478
+
479
+ try:
480
+ day = _dt.datetime.strptime(f"{int(yyyymmdd):08d}", "%Y%m%d").replace(tzinfo=_dt.UTC)
481
+ hms = int(hhmmss)
482
+ except (TypeError, ValueError):
483
+ return None
484
+ sec = day.timestamp() + (hms // 10000) * 3600 + (hms // 100 % 100) * 60 + hms % 100
485
+ hit = np.flatnonzero(self._epoch == sec)
486
+ if hit.size and np.isfinite(self._v[hit[0]]):
487
+ return float(self._v[hit[0]]), self.path.name
488
+ return None