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.
- arrayprobe/__init__.py +219 -0
- arrayprobe/__main__.py +19 -0
- arrayprobe/_v314_lazy.py +48 -0
- arrayprobe/ai_ready.py +212 -0
- arrayprobe/attributed_export.py +1333 -0
- arrayprobe/authordefaults.py +267 -0
- arrayprobe/cli.py +3510 -0
- arrayprobe/combine.py +12 -0
- arrayprobe/compare.py +950 -0
- arrayprobe/config.py +1239 -0
- arrayprobe/constants.py +12 -0
- arrayprobe/count_closure.py +204 -0
- arrayprobe/diagnostic_views.py +769 -0
- arrayprobe/diode_report.py +265 -0
- arrayprobe/driver/__init__.py +5 -0
- arrayprobe/driver/_load_record.py +331 -0
- arrayprobe/driver/preflight_inputs.py +250 -0
- arrayprobe/driver/reprocess.py +553 -0
- arrayprobe/driver/run_flight.py +8166 -0
- arrayprobe/driver/tas_from_probe_housekeeping.py +124 -0
- arrayprobe/dropsize.py +519 -0
- arrayprobe/friendly.py +206 -0
- arrayprobe/geometry/__init__.py +77 -0
- arrayprobe/geometry/min_rectangle.py +92 -0
- arrayprobe/intarr.py +12 -0
- arrayprobe/intarr_analysis.py +16 -0
- arrayprobe/intarr_plots.py +12 -0
- arrayprobe/inventory.py +129 -0
- arrayprobe/jit_kernels.py +344 -0
- arrayprobe/lwc.py +44 -0
- arrayprobe/masks.py +349 -0
- arrayprobe/matio.py +410 -0
- arrayprobe/matlab_compat.py +13 -0
- arrayprobe/ncio.py +26 -0
- arrayprobe/particle.py +55 -0
- arrayprobe/particle_perimeter.py +12 -0
- arrayprobe/products.py +78 -0
- arrayprobe/profiles.py +179 -0
- arrayprobe/provenance.py +21 -0
- arrayprobe/py.typed +11 -0
- arrayprobe/readers/__init__.py +9 -0
- arrayprobe/readers/dmt.py +603 -0
- arrayprobe/readers/mask_csv.py +12 -0
- arrayprobe/readers/pms.py +12 -0
- arrayprobe/readers/sea.py +433 -0
- arrayprobe/readers/tasinfo.py +12 -0
- arrayprobe/regimes.py +507 -0
- arrayprobe/render.py +728 -0
- arrayprobe/reproduce_report.py +149 -0
- arrayprobe/review_agreement.py +135 -0
- arrayprobe/review_sampling.py +327 -0
- arrayprobe/run_page.py +624 -0
- arrayprobe/sample_area.py +12 -0
- arrayprobe/selector.py +206 -0
- arrayprobe/sizing.py +151 -0
- arrayprobe/time_convert.py +12 -0
- arrayprobe/timing_closure.py +141 -0
- arrayprobe/tools/__init__.py +27 -0
- arrayprobe/tools/make_demo_flight.py +1089 -0
- arrayprobe/tools/make_tas_file.py +760 -0
- arrayprobe/tools/probe_comparison.py +569 -0
- arrayprobe/tools/synthetic_truth.py +698 -0
- arrayprobe/tools/tas_sources.py +705 -0
- arrayprobe/triage_context.py +488 -0
- arrayprobe/triage_server.py +5215 -0
- arrayprobe/tune/__init__.py +15 -0
- arrayprobe/tune/diodes.py +400 -0
- arrayprobe/tune/distributions.py +300 -0
- arrayprobe/tune/sample.py +243 -0
- arrayprobe/tune/score.py +230 -0
- arrayprobe/tune/settings.py +354 -0
- arrayprobe/validate_by_condition.py +208 -0
- arrayprobe/validation_report.py +166 -0
- arrayprobe-0.1.0.dist-info/METADATA +260 -0
- arrayprobe-0.1.0.dist-info/RECORD +189 -0
- arrayprobe-0.1.0.dist-info/WHEEL +5 -0
- arrayprobe-0.1.0.dist-info/entry_points.txt +2 -0
- arrayprobe-0.1.0.dist-info/licenses/LICENSE +31 -0
- arrayprobe-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
- arrayprobe-0.1.0.dist-info/licenses/NOTICE.md +369 -0
- arrayprobe-0.1.0.dist-info/top_level.txt +4 -0
- arrayprobe_soda2/__init__.py +131 -0
- arrayprobe_soda2/angles.py +143 -0
- arrayprobe_soda2/aspect_ratio.py +541 -0
- arrayprobe_soda2/backfill.py +100 -0
- arrayprobe_soda2/binary_dof.py +181 -0
- arrayprobe_soda2/buildindex.py +113 -0
- arrayprobe_soda2/decompress_dmt.py +285 -0
- arrayprobe_soda2/enhancement_hooks.py +275 -0
- arrayprobe_soda2/export_ascii.py +732 -0
- arrayprobe_soda2/export_ncdf.py +683 -0
- arrayprobe_soda2/export_ncdf_raf.py +396 -0
- arrayprobe_soda2/fillholes.py +161 -0
- arrayprobe_soda2/find_radius.py +105 -0
- arrayprobe_soda2/findsize.py +407 -0
- arrayprobe_soda2/fit_poisson.py +170 -0
- arrayprobe_soda2/fix2dimage.py +63 -0
- arrayprobe_soda2/fixraking.py +162 -0
- arrayprobe_soda2/fixstuckbits.py +146 -0
- arrayprobe_soda2/hvps4_read_frame.py +121 -0
- arrayprobe_soda2/jit_kernels.py +152 -0
- arrayprobe_soda2/label_blobs.py +177 -0
- arrayprobe_soda2/min_circle_fast.py +320 -0
- arrayprobe_soda2/particlesort.py +703 -0
- arrayprobe_soda2/pbp_writer.py +558 -0
- arrayprobe_soda2/poisson_spot_correct.py +183 -0
- arrayprobe_soda2/princomp.py +107 -0
- arrayprobe_soda2/probespecs.py +361 -0
- arrayprobe_soda2/process_2d.py +1364 -0
- arrayprobe_soda2/process_2d_parallel.py +626 -0
- arrayprobe_soda2/process_hk.py +512 -0
- arrayprobe_soda2/processbuffer_2dc.py +155 -0
- arrayprobe_soda2/processbuffer_cip.py +213 -0
- arrayprobe_soda2/processbuffer_f2dc.py +139 -0
- arrayprobe_soda2/processbuffer_spec.py +441 -0
- arrayprobe_soda2/processbuffer_tail.py +350 -0
- arrayprobe_soda2/pth_readers.py +245 -0
- arrayprobe_soda2/py.typed +11 -0
- arrayprobe_soda2/read2dbuffer.py +371 -0
- arrayprobe_soda2/reject.py +246 -0
- arrayprobe_soda2/reprocess_pbp.py +156 -0
- arrayprobe_soda2/sample_area.py +264 -0
- arrayprobe_soda2/save_writer.py +480 -0
- arrayprobe_soda2/sea.py +324 -0
- arrayprobe_soda2/spec_absolutepointers.py +109 -0
- arrayprobe_soda2/spec_decompress.py +203 -0
- arrayprobe_soda2/spec_index.py +476 -0
- arrayprobe_soda2/spec_read_frame.py +286 -0
- arrayprobe_soda2/spec_read_hk.py +301 -0
- arrayprobe_soda2/spec_readint.py +127 -0
- arrayprobe_soda2/timeconv.py +77 -0
- arrayprobe_soda2/update_op.py +101 -0
- arrayprobe_uiops/__init__.py +45 -0
- arrayprobe_uiops/combine.py +192 -0
- arrayprobe_uiops/combine_fork.py +359 -0
- arrayprobe_uiops/constants.py +830 -0
- arrayprobe_uiops/decode_naming.py +113 -0
- arrayprobe_uiops/diode_mask.py +250 -0
- arrayprobe_uiops/engine_absence.py +41 -0
- arrayprobe_uiops/export_oap.py +325 -0
- arrayprobe_uiops/geometry_core.py +366 -0
- arrayprobe_uiops/habit.py +749 -0
- arrayprobe_uiops/habit_core.py +248 -0
- arrayprobe_uiops/hollow_size_rule.py +376 -0
- arrayprobe_uiops/imgproc.py +2081 -0
- arrayprobe_uiops/imgproc_core.py +275 -0
- arrayprobe_uiops/intarr.py +167 -0
- arrayprobe_uiops/intarr_analysis.py +569 -0
- arrayprobe_uiops/intarr_plots.py +119 -0
- arrayprobe_uiops/jit_kernels.py +430 -0
- arrayprobe_uiops/lwc.py +70 -0
- arrayprobe_uiops/matlab_compat.py +860 -0
- arrayprobe_uiops/measure.py +346 -0
- arrayprobe_uiops/min_circle.py +204 -0
- arrayprobe_uiops/min_ellipse.py +161 -0
- arrayprobe_uiops/min_rectangle.py +200 -0
- arrayprobe_uiops/ncar_2dc_timing.py +100 -0
- arrayprobe_uiops/ncio.py +810 -0
- arrayprobe_uiops/oap_read.py +228 -0
- arrayprobe_uiops/particle.py +51 -0
- arrayprobe_uiops/particle_perimeter.py +94 -0
- arrayprobe_uiops/particle_physics.py +199 -0
- arrayprobe_uiops/pecan_params.py +134 -0
- arrayprobe_uiops/probe_cases.py +298 -0
- arrayprobe_uiops/product_sanity.py +337 -0
- arrayprobe_uiops/profile.py +71 -0
- arrayprobe_uiops/profiles.py +756 -0
- arrayprobe_uiops/provenance.py +804 -0
- arrayprobe_uiops/py.typed +11 -0
- arrayprobe_uiops/qc.py +169 -0
- arrayprobe_uiops/readers/__init__.py +8 -0
- arrayprobe_uiops/readers/mask_csv.py +74 -0
- arrayprobe_uiops/readers/pms.py +239 -0
- arrayprobe_uiops/readers/tasinfo.py +57 -0
- arrayprobe_uiops/rect_ellipse.py +129 -0
- arrayprobe_uiops/register_image_assisted.py +25 -0
- arrayprobe_uiops/reject.py +501 -0
- arrayprobe_uiops/reject_core.py +220 -0
- arrayprobe_uiops/sample_area.py +93 -0
- arrayprobe_uiops/sizedist.py +1923 -0
- arrayprobe_uiops/sizedist_core.py +814 -0
- arrayprobe_uiops/sizedist_tables.py +642 -0
- arrayprobe_uiops/spec.py +1094 -0
- arrayprobe_uiops/spec_core.py +703 -0
- arrayprobe_uiops/stray_pixel.py +103 -0
- arrayprobe_uiops/tas.py +191 -0
- arrayprobe_uiops/time_convert.py +41 -0
- uiops/__init__.py +402 -0
- uiops/py.typed +11 -0
|
@@ -0,0 +1,705 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
"""Where a run's true airspeed comes from: an ordered, recorded chain.
|
|
3
|
+
|
|
4
|
+
The author's ruling, verbatim:
|
|
5
|
+
|
|
6
|
+
* *"yes for oracles, for other probes/campaigns - use probe airspeed"* -- use the ORACLES merge
|
|
7
|
+
file's airspeed instead of the 2D-S probe's;
|
|
8
|
+
* *"never drop, use a cutoff and a default to fall to, provide user an option to select both in
|
|
9
|
+
config so nothing is hard coded"*;
|
|
10
|
+
* *"07-06: ... - ARM's own"*;
|
|
11
|
+
* *"for oracles - yes, use the merged-file airspeed. for non-oracles, a merged file may not be
|
|
12
|
+
available, so we look elsewhere for a reliable source, and if not, then the probe file itself
|
|
13
|
+
with the decisions made earlier today. document this chain in the TAS page too and the
|
|
14
|
+
metadata provides exactly what was followed. during processing, user can be given an
|
|
15
|
+
opt-in/option in the config file."*
|
|
16
|
+
|
|
17
|
+
So the source is a **chain of tiers, tried in order** (:data:`TIERS`):
|
|
18
|
+
|
|
19
|
+
1. ``merge`` -- a campaign merge file (ORACLES ``mrg1_P3_<yyyymmdd>_R*.nc``, ``True_Air_Speed``);
|
|
20
|
+
2. ``aircraft`` -- another reliable aircraft source (ARM AAF ``enaaafmergedF1.c1.<date>.*.nc``,
|
|
21
|
+
``true_airspeed``);
|
|
22
|
+
3. ``probe`` -- the probe's own ``<stem>.tas.csv``, reduced under the duplicate-second rules
|
|
23
|
+
(:func:`arrayprobe.tools.make_tas_file.reduce_probe_csv`).
|
|
24
|
+
|
|
25
|
+
``mode="auto"`` walks the tiers and uses the first that is available and passes its checks;
|
|
26
|
+
``"merge"``/``"aircraft"``/``"probe"`` pin one tier and **refuse** rather than fall through when
|
|
27
|
+
it is absent. Every tier tried is recorded -- used, skipped (not available) or failed (a check,
|
|
28
|
+
named) -- in the aircraft file's global attributes and in the run log.
|
|
29
|
+
|
|
30
|
+
**Only sources read off a real file are registered** (:data:`SOURCES`), each with the file it was
|
|
31
|
+
read from. A file matching no entry raises naming what it carries; nothing is guessed.
|
|
32
|
+
|
|
33
|
+
**Units are read, not assumed**: a registered source whose entry says ``units="attribute"``
|
|
34
|
+
must carry a ``units`` attribute naming one of :data:`UNIT_FACTORS`, or it is refused. The UIOOPS
|
|
35
|
+
``TAS``/``Time`` convention carries none and is m/s by definition (``imgproc.py:531-532`` reads
|
|
36
|
+
two bare arrays).
|
|
37
|
+
|
|
38
|
+
**The fidelity boundary.** Nothing here touches either engine. ``imgProc_sm.m:365``/``:763``'s
|
|
39
|
+
own 170 m/s fallback (``imgproc.py:118``) stays as it is; what this module configures is the
|
|
40
|
+
aircraft file the engine is *handed* and, when a run selects it, the TAS series ``sizeDist`` is
|
|
41
|
+
handed in place of the probe's.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
from __future__ import annotations
|
|
45
|
+
|
|
46
|
+
import glob as _glob
|
|
47
|
+
import json as _json
|
|
48
|
+
import os as _os
|
|
49
|
+
from dataclasses import dataclass, field
|
|
50
|
+
from pathlib import Path
|
|
51
|
+
|
|
52
|
+
import numpy as np
|
|
53
|
+
|
|
54
|
+
from arrayprobe.tools import make_tas_file as _mtf
|
|
55
|
+
from arrayprobe.tools.make_tas_file import TasPolicy, second_ranges
|
|
56
|
+
|
|
57
|
+
__all__ = ["AircraftSource", "SOURCES", "TIERS", "MODES", "UNIT_FACTORS", "AircraftSeries",
|
|
58
|
+
"read_aircraft", "substitute", "ChainResult", "resolve_chain", "write_chain_file",
|
|
59
|
+
"series_for_sizedist", "regular_grid_hhmmss", "regular_series_for_sizedist",
|
|
60
|
+
"write_soda2_pth_csv"]
|
|
61
|
+
|
|
62
|
+
#: The tiers in the order ``auto`` tries them.
|
|
63
|
+
TIERS = ("merge", "aircraft", "probe")
|
|
64
|
+
#: ``[tas].source`` / ``--tas-source`` values: walk the chain, or pin one tier.
|
|
65
|
+
MODES = ("auto", *TIERS)
|
|
66
|
+
|
|
67
|
+
#: Factor to m/s per units string, for the units strings met on registered files. A units
|
|
68
|
+
#: string not here is refused, never guessed. 1 kt = 1852 m / 3600 s exactly (international
|
|
69
|
+
#: nautical mile).
|
|
70
|
+
UNIT_FACTORS = {"kts": 1852.0 / 3600.0, "m/s": 1.0}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass(frozen=True)
|
|
74
|
+
class AircraftSource:
|
|
75
|
+
"""One registered aircraft TAS source, read off a real file before being added."""
|
|
76
|
+
|
|
77
|
+
name: str
|
|
78
|
+
tier: str
|
|
79
|
+
tas_var: str
|
|
80
|
+
time_var: str
|
|
81
|
+
time_axis: str # "hhmmss" | "seconds-of-day" | "seconds-since-base_time"
|
|
82
|
+
units: str # "attribute" (read and checked) | "m/s" (the UIOOPS convention)
|
|
83
|
+
pattern: str | None # file name glob with {yyyymmdd}; None = only when named explicitly
|
|
84
|
+
evidence: str
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
#: Order matters for identification only (the first whose two variables a file carries);
|
|
88
|
+
#: the chain's order is :data:`TIERS`.
|
|
89
|
+
SOURCES = (
|
|
90
|
+
AircraftSource(
|
|
91
|
+
"uiops-flightdata", "aircraft", "TAS", "Time", "hhmmss", "m/s", None,
|
|
92
|
+
"UIOPS flightData_*.cdf -- the convention imgProc_sm.m expects; imgproc.py:531-532 "
|
|
93
|
+
"reads these names; tests/data/demo_flight_v35_aircraft.cdf"),
|
|
94
|
+
AircraftSource(
|
|
95
|
+
"oracles-p3-merge", "merge", "True_Air_Speed", "Start_UTC", "seconds-of-day",
|
|
96
|
+
"attribute", "mrg1_P3_{yyyymmdd}_R*.nc",
|
|
97
|
+
"read 2026-09-23 off mrg1_P3_20160906_R36.nc, mrg1_P3_20170812_R28.nc and "
|
|
98
|
+
"mrg1_P3_20181002_R25.nc ($ARRAYPROBE_ORACLES_DATA): Start_UTC f8 units 'seconds' "
|
|
99
|
+
"(of day), whole, 1 Hz; True_Air_Speed f8 units 'kts', missing_value -9999/-7777/-8888, "
|
|
100
|
+
"fill 9.969e36 (46-74 samples per file); source Hskping_P3_<date>_R*.ict"),
|
|
101
|
+
AircraftSource(
|
|
102
|
+
"arm-aaf-merged", "aircraft", "true_airspeed", "time", "seconds-since-base_time",
|
|
103
|
+
"attribute", "enaaafmergedF1.c1.{yyyymmdd}.*.nc",
|
|
104
|
+
"ARM AAF merged, read 2026-09-23 off enaaafmergedF1.c1.20170706.082313.nc: "
|
|
105
|
+
"true_airspeed f4 units 'm/s' (source enaaafnaviwgF1.c1:true_airspeed), "
|
|
106
|
+
"missing_value -9999; time f8 'seconds since 2017-07-06 00:00:00', base_time "
|
|
107
|
+
"1499299200 (that midnight), whole, 1 Hz"),
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass
|
|
112
|
+
class AircraftSeries:
|
|
113
|
+
"""An aircraft file read and converted: HHMMSS whole seconds, TAS in m/s (not yet
|
|
114
|
+
policy-checked)."""
|
|
115
|
+
|
|
116
|
+
time_hhmmss: np.ndarray
|
|
117
|
+
tas_mps: np.ndarray
|
|
118
|
+
source: AircraftSource
|
|
119
|
+
path: str
|
|
120
|
+
units: str
|
|
121
|
+
factor: float
|
|
122
|
+
notes: list = field(default_factory=list)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _variables(path) -> set:
|
|
126
|
+
import netCDF4
|
|
127
|
+
with netCDF4.Dataset(str(path)) as ds:
|
|
128
|
+
return set(ds.variables)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _units(path, var) -> str | None:
|
|
132
|
+
import netCDF4
|
|
133
|
+
with netCDF4.Dataset(str(path)) as ds:
|
|
134
|
+
v = ds.variables[var]
|
|
135
|
+
return str(v.getncattr("units")) if "units" in v.ncattrs() else None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _sod_to_hhmmss(sod) -> np.ndarray:
|
|
139
|
+
return _mtf._sod_to_hhmmss(sod)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def identify(path) -> AircraftSource:
|
|
143
|
+
"""The registered source whose two variables ``path`` carries. Raises ``KeyError`` naming
|
|
144
|
+
what it tried and what the file carries -- never a guess."""
|
|
145
|
+
present = _variables(path)
|
|
146
|
+
for src in SOURCES:
|
|
147
|
+
if src.tas_var in present and src.time_var in present:
|
|
148
|
+
return src
|
|
149
|
+
tried = ", ".join(f"{s.tas_var}/{s.time_var}" for s in SOURCES)
|
|
150
|
+
raise KeyError(
|
|
151
|
+
f"{path}: no true-airspeed variable found. Tried {tried}. It carries: "
|
|
152
|
+
f"{sorted(present)}. Add the source to arrayprobe.tools.tas_sources.SOURCES once you "
|
|
153
|
+
"have read it out of a real file -- do not guess a name.")
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def read_aircraft(path, source: AircraftSource | None = None) -> AircraftSeries:
|
|
157
|
+
"""Read ``path`` as ``source`` (identified by its variables when not given), convert its
|
|
158
|
+
time axis to UTC HHMMSS and its TAS to m/s by the units attribute. Read through
|
|
159
|
+
``ncio.ncread`` -- the call the engine makes -- so masking and scaling apply the same way."""
|
|
160
|
+
from arrayprobe import ncio
|
|
161
|
+
|
|
162
|
+
src = source or identify(path)
|
|
163
|
+
tas = np.asarray(ncio.ncread(str(path), src.tas_var), dtype=np.float64).ravel()
|
|
164
|
+
# A masked (fill-value) time is NaN here, not its stored fill: np.asarray on ncread's masked
|
|
165
|
+
# array would hand back the fill itself (ARM's -9999), which the conversions below turn into
|
|
166
|
+
# a real-looking clock second (-9999 s of day is 21:13:21).
|
|
167
|
+
t = np.ma.filled(np.ma.asarray(ncio.ncread(str(path), src.time_var), dtype=np.float64),
|
|
168
|
+
np.nan).ravel()
|
|
169
|
+
bad_time = int(np.sum(~np.isfinite(t)))
|
|
170
|
+
if bad_time:
|
|
171
|
+
raise ValueError(f"{path}: '{src.time_var}' has {bad_time} masked or non-finite "
|
|
172
|
+
"value(s); a time that is not a number cannot key a second")
|
|
173
|
+
notes: list[str] = []
|
|
174
|
+
if src.units == "attribute":
|
|
175
|
+
units = _units(path, src.tas_var)
|
|
176
|
+
if units is None:
|
|
177
|
+
raise ValueError(f"{path}: {src.tas_var} carries no units attribute; source "
|
|
178
|
+
f"{src.name} is registered as reading its units from the file, so "
|
|
179
|
+
"a speed of unknown units is refused rather than assumed")
|
|
180
|
+
if units not in UNIT_FACTORS:
|
|
181
|
+
raise ValueError(f"{path}: {src.tas_var} units {units!r} are not one of "
|
|
182
|
+
f"{sorted(UNIT_FACTORS)}; refused rather than guessed")
|
|
183
|
+
else:
|
|
184
|
+
units = src.units
|
|
185
|
+
factor = UNIT_FACTORS[units]
|
|
186
|
+
if factor != 1.0:
|
|
187
|
+
tas = tas * factor
|
|
188
|
+
notes.append(f"{src.tas_var} converted from {units!r} to m/s (x {factor!r})")
|
|
189
|
+
if src.time_axis == "seconds-of-day":
|
|
190
|
+
if np.any(t != np.floor(t)):
|
|
191
|
+
raise ValueError(f"{path}: {src.time_var} is not whole seconds; the exact-match "
|
|
192
|
+
"lookup at imgProc_sm.m:727 needs whole seconds")
|
|
193
|
+
# Unwrapped, matching UIOOPS's own midnight convention (2026-09-28): a value at or
|
|
194
|
+
# past 86400 s is the next day's clock continuing as 24xxxx HHMMSS, not folded back to
|
|
195
|
+
# 000000 -- the same convention sizeDist.m's +240000 rollover keeps for particle times.
|
|
196
|
+
t = _sod_to_hhmmss(t.astype(np.int64))
|
|
197
|
+
notes.append(f"{src.time_var} converted from seconds of day to UTC HHMMSS (unwrapped "
|
|
198
|
+
"past midnight)")
|
|
199
|
+
elif src.time_axis == "seconds-since-base_time":
|
|
200
|
+
if "base_time" not in _variables(path):
|
|
201
|
+
raise ValueError(
|
|
202
|
+
f"{path}: '{src.time_var}' is seconds since base_time (ARM convention) but the "
|
|
203
|
+
"file has no base_time variable, so the time of day cannot be established; "
|
|
204
|
+
"refused rather than read as HHMMSS (it would match no record at "
|
|
205
|
+
"imgProc_sm.m:727)")
|
|
206
|
+
base = float(np.asarray(ncio.ncread(str(path), "base_time"), dtype=float).ravel()[0])
|
|
207
|
+
# Unwrapped past midnight, same convention as the seconds-of-day branch above (B5):
|
|
208
|
+
# seconds since base_time's own reference day, not folded back to 000000 at 86400 s.
|
|
209
|
+
day0 = np.floor(base / 86400.0) * 86400.0
|
|
210
|
+
sod = np.round(base + t - day0).astype(np.int64)
|
|
211
|
+
t = _sod_to_hhmmss(sod)
|
|
212
|
+
notes.append(f"'{src.time_var}' converted from seconds since base_time to UTC HHMMSS "
|
|
213
|
+
"(unwrapped past midnight)")
|
|
214
|
+
return AircraftSeries(t, tas, src, str(path), units, factor, notes)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def substitute(time_hhmmss, tas, policy: TasPolicy):
|
|
218
|
+
"""Every out-of-range TAS -> ``policy.default_mps``. Returns ``(tas, subs)``, ``subs`` one
|
|
219
|
+
``(HHMMSS, original, reason)`` per substituted sample. Nothing is dropped."""
|
|
220
|
+
t = np.asarray(time_hhmmss, dtype=np.float64).ravel()
|
|
221
|
+
out = np.asarray(tas, dtype=np.float64).ravel().copy()
|
|
222
|
+
subs = []
|
|
223
|
+
for i, x in enumerate(out.tolist()):
|
|
224
|
+
why = policy.reason(x)
|
|
225
|
+
if why is not None:
|
|
226
|
+
subs.append((int(t[i]) if np.isfinite(t[i]) else -1, x, why))
|
|
227
|
+
out[i] = policy.default_mps
|
|
228
|
+
return out, subs
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclass
|
|
232
|
+
class ChainResult:
|
|
233
|
+
"""What the chain decided for one flight file. ``tier``/``source`` name what was used;
|
|
234
|
+
``steps`` is every tier tried, in order, as ``(tier, source, outcome, detail)`` with outcome
|
|
235
|
+
``used`` / ``skipped`` / ``failed``."""
|
|
236
|
+
|
|
237
|
+
mode: str
|
|
238
|
+
tier: str
|
|
239
|
+
source: str
|
|
240
|
+
path: str
|
|
241
|
+
time: np.ndarray
|
|
242
|
+
tas: np.ndarray
|
|
243
|
+
policy: TasPolicy
|
|
244
|
+
steps: list
|
|
245
|
+
substituted: list # (HHMMSS, reason) per second that took the default
|
|
246
|
+
lines: list
|
|
247
|
+
provenance: dict
|
|
248
|
+
|
|
249
|
+
def stamp(self) -> str:
|
|
250
|
+
"""The ``.call`` fragment (only ever added when a run opts into the chain)."""
|
|
251
|
+
return f"tas_chain={self.tier}:{self.source} tas_policy=({self.policy.token()})"
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _steps_text(steps) -> str:
|
|
255
|
+
return "; ".join(f"{tier}/{name}: {outcome}" + (f" ({detail})" if detail else "")
|
|
256
|
+
for tier, name, outcome, detail in steps)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _probe_seconds(probe_csv) -> np.ndarray | None:
|
|
260
|
+
if probe_csv is None or not Path(probe_csv).is_file():
|
|
261
|
+
return None
|
|
262
|
+
t, _ = _mtf.tas_from_csv(probe_csv)
|
|
263
|
+
sod = _mtf._hhmmss_to_sod(np.asarray(t, dtype=float))
|
|
264
|
+
return np.unique(_sod_to_hhmmss(np.floor(sod + 0.5).astype(np.int64)))
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _from_aircraft(series: AircraftSeries, policy: TasPolicy, probe_secs):
|
|
268
|
+
"""Check, substitute, and extend over the probe's seconds. Returns
|
|
269
|
+
``(time, tas, substituted, lines, extra_provenance)``; raises ValueError on a failed check."""
|
|
270
|
+
t, v = series.time_hhmmss, series.tas_mps
|
|
271
|
+
v, subs = substitute(t, v, policy)
|
|
272
|
+
# The same fail-closed check the builder applies: whole, unique, clock-valid HHMMSS.
|
|
273
|
+
t, v = _mtf.check_tas_series(t, v)
|
|
274
|
+
lines = [f"TAS substituted: {s:06d} {x!r} -> {policy.default_mps:g} m/s ({why})"
|
|
275
|
+
for s, x, why in subs]
|
|
276
|
+
substituted = [(s, why) for s, x, why in subs]
|
|
277
|
+
extra: dict = {}
|
|
278
|
+
if probe_secs is not None:
|
|
279
|
+
have = set(t.astype(np.int64).tolist())
|
|
280
|
+
overlap = [s for s in probe_secs.astype(np.int64).tolist() if s in have]
|
|
281
|
+
if not overlap:
|
|
282
|
+
raise ValueError(
|
|
283
|
+
f"shares no second with the probe's own clock ({probe_secs.size} probe seconds, "
|
|
284
|
+
f"{int(probe_secs[0]):06d}..{int(probe_secs[-1]):06d}; source "
|
|
285
|
+
f"{int(t[0]):06d}..{int(t[-1]):06d}) -- it cannot be this flight's airspeed")
|
|
286
|
+
gaps = [s for s in probe_secs.astype(np.int64).tolist() if s not in have]
|
|
287
|
+
extra["tas_probe_seconds_covered"] = np.int32(len(overlap))
|
|
288
|
+
extra["tas_probe_seconds_total"] = np.int32(probe_secs.size)
|
|
289
|
+
if gaps:
|
|
290
|
+
# Never dropped: a probe second the aircraft source does not cover takes the
|
|
291
|
+
# default, in the file, so the configured default -- not only the engine's own
|
|
292
|
+
# fallback -- is what applies there. Logged as ranges; every second is recoverable.
|
|
293
|
+
t = np.concatenate([t, np.asarray(gaps, dtype=np.float64)])
|
|
294
|
+
v = np.concatenate([v, np.full(len(gaps), policy.default_mps)])
|
|
295
|
+
order = np.argsort(_mtf._hhmmss_to_sod(t), kind="stable")
|
|
296
|
+
t, v = t[order], v[order]
|
|
297
|
+
substituted += [(s, "no-aircraft-sample") for s in gaps]
|
|
298
|
+
lines.append(f"TAS substituted: {len(gaps)} probe second(s) with no aircraft "
|
|
299
|
+
f"sample -> {policy.default_mps:g} m/s: {second_ranges(gaps)}")
|
|
300
|
+
return t, v, sorted(substituted), lines, extra
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _candidates(src: AircraftSource, yyyymmdd: str, search_dirs) -> list[Path]:
|
|
304
|
+
assert src.pattern is not None, "callers skip a source registered with no file pattern"
|
|
305
|
+
found: list[Path] = []
|
|
306
|
+
for d in search_dirs:
|
|
307
|
+
pattern = str(Path(d).expanduser() / src.pattern.format(yyyymmdd=yyyymmdd))
|
|
308
|
+
found += [Path(p) for p in sorted(_glob.glob(pattern))]
|
|
309
|
+
return found
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def resolve_chain(mode: str, *, yyyymmdd: str | None, search_dirs=(), probe_csv=None,
|
|
313
|
+
policy: TasPolicy | None = None,
|
|
314
|
+
second_rule: str = _mtf.AUTHOR_SECOND_RULE,
|
|
315
|
+
neighbour: str = _mtf.AUTHOR_NEIGHBOUR_RULE,
|
|
316
|
+
explicit: dict | None = None) -> ChainResult:
|
|
317
|
+
"""Walk the chain (``mode="auto"``) or pin one tier, and return what was used and why.
|
|
318
|
+
|
|
319
|
+
``yyyymmdd`` names the flight's date (a raw stem ``base170812080701`` is ``20170812``) and
|
|
320
|
+
fills each registered source's file-name pattern in ``search_dirs``; ``explicit`` maps a tier
|
|
321
|
+
to a file named outright (``make-tas-file --from-merge``/``--from-aircraft``), which is then
|
|
322
|
+
that tier's only candidate. ``probe_csv`` is the decode's ``<stem>.tas.csv``: the ``probe``
|
|
323
|
+
tier's input, and for the other tiers the clock they must share at least one second with.
|
|
324
|
+
|
|
325
|
+
Raises ``ValueError`` -- listing every step -- when no tier is usable, or when a pinned tier
|
|
326
|
+
is absent or fails: a pinned source never falls through silently.
|
|
327
|
+
"""
|
|
328
|
+
if mode not in MODES:
|
|
329
|
+
raise ValueError(f"TAS source must be one of {MODES}, got {mode!r}")
|
|
330
|
+
policy = policy or TasPolicy()
|
|
331
|
+
explicit = explicit or {}
|
|
332
|
+
tiers = TIERS if mode == "auto" else (mode,)
|
|
333
|
+
probe_secs = _probe_seconds(probe_csv)
|
|
334
|
+
steps: list[tuple[str, str, str, str]] = []
|
|
335
|
+
for tier in tiers:
|
|
336
|
+
if tier == "probe":
|
|
337
|
+
if probe_csv is None or not Path(probe_csv).is_file():
|
|
338
|
+
steps.append(("probe", "probe-tas-csv", "skipped",
|
|
339
|
+
f"not available: {probe_csv or 'no <stem>.tas.csv'}"))
|
|
340
|
+
continue
|
|
341
|
+
red = _mtf.reduce_probe_csv(probe_csv, policy=policy, second_rule=second_rule,
|
|
342
|
+
neighbour=neighbour, unsettled="default")
|
|
343
|
+
try:
|
|
344
|
+
t, v = _mtf.check_tas_series(red.time, red.tas)
|
|
345
|
+
except ValueError as exc:
|
|
346
|
+
steps.append(("probe", "probe-tas-csv", "failed", str(exc)))
|
|
347
|
+
continue
|
|
348
|
+
steps.append(("probe", "probe-tas-csv", "used", str(probe_csv)))
|
|
349
|
+
return _result(mode, "probe", "probe-tas-csv", str(probe_csv), t, v, policy, steps,
|
|
350
|
+
list(red.substituted), red.lines, red.provenance)
|
|
351
|
+
sources = [s for s in SOURCES if s.tier == tier]
|
|
352
|
+
for src in sources:
|
|
353
|
+
if tier in explicit:
|
|
354
|
+
cands = [Path(explicit[tier])]
|
|
355
|
+
elif src.pattern is None:
|
|
356
|
+
continue # only reachable when named outright
|
|
357
|
+
elif yyyymmdd is None:
|
|
358
|
+
steps.append((tier, src.name, "skipped", "not available: no flight date"))
|
|
359
|
+
continue
|
|
360
|
+
elif not search_dirs:
|
|
361
|
+
steps.append((tier, src.name, "skipped",
|
|
362
|
+
"not available: no search directory configured ([tas].search / "
|
|
363
|
+
"--tas-search)"))
|
|
364
|
+
continue
|
|
365
|
+
else:
|
|
366
|
+
cands = _candidates(src, yyyymmdd, search_dirs)
|
|
367
|
+
if not cands:
|
|
368
|
+
# An explicit file is always one candidate, so an empty list came from
|
|
369
|
+
# _candidates, which only runs for a source with a file pattern.
|
|
370
|
+
assert src.pattern is not None
|
|
371
|
+
steps.append((tier, src.name, "skipped",
|
|
372
|
+
f"not available: no {src.pattern.format(yyyymmdd=yyyymmdd)} in "
|
|
373
|
+
f"{[str(d) for d in search_dirs]}"))
|
|
374
|
+
continue
|
|
375
|
+
if len(cands) > 1:
|
|
376
|
+
steps.append((tier, src.name, "failed",
|
|
377
|
+
f"{len(cands)} candidate files ({', '.join(c.name for c in cands)}); "
|
|
378
|
+
"name one outright rather than have one picked"))
|
|
379
|
+
continue
|
|
380
|
+
path = cands[0]
|
|
381
|
+
try:
|
|
382
|
+
found = identify(path)
|
|
383
|
+
if tier in explicit and found.tier != tier:
|
|
384
|
+
raise ValueError(f"{path.name} reads as {found.name}, a {found.tier} source, "
|
|
385
|
+
f"not a {tier} one")
|
|
386
|
+
series = read_aircraft(path, found)
|
|
387
|
+
t, v, subs, lines, extra = _from_aircraft(series, policy, probe_secs)
|
|
388
|
+
except (KeyError, ValueError, OSError) as exc:
|
|
389
|
+
steps.append((tier, src.name if tier not in explicit else path.name, "failed",
|
|
390
|
+
str(exc)))
|
|
391
|
+
if tier in explicit:
|
|
392
|
+
break
|
|
393
|
+
continue
|
|
394
|
+
steps.append((tier, found.name, "used", str(path)))
|
|
395
|
+
prov = {
|
|
396
|
+
"tas_source": f"{path} ({found.name}, measured)",
|
|
397
|
+
"tas_source_evidence": found.evidence,
|
|
398
|
+
"tas_units_read": series.units,
|
|
399
|
+
"tas_unit_factor_to_mps": float(series.factor),
|
|
400
|
+
"tas_conversions": "; ".join(series.notes) or "none",
|
|
401
|
+
**policy.attributes(),
|
|
402
|
+
"tas_substituted_count": np.int32(len(subs)),
|
|
403
|
+
# reason=HHMMSS ranges, one group per reason: every second is recoverable.
|
|
404
|
+
"tas_substituted_seconds": "; ".join(
|
|
405
|
+
f"{why}={second_ranges([s for s, w in subs if w == why])}"
|
|
406
|
+
for why in dict.fromkeys(w for _, w in subs)),
|
|
407
|
+
**extra,
|
|
408
|
+
}
|
|
409
|
+
return _result(mode, tier, found.name, str(path), t, v, policy, steps, subs,
|
|
410
|
+
list(series.notes) + lines, prov)
|
|
411
|
+
if tier in explicit:
|
|
412
|
+
break
|
|
413
|
+
raise ValueError(f"TAS source chain ({mode}) found nothing usable: {_steps_text(steps)}")
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _result(mode, tier, source, path, t, v, policy, steps, subs, lines, prov) -> ChainResult:
|
|
417
|
+
prov = dict(prov)
|
|
418
|
+
prov["tas_chain_mode"] = mode
|
|
419
|
+
prov["tas_chain_used"] = f"{tier}:{source}"
|
|
420
|
+
prov["tas_chain_steps"] = _steps_text(steps)
|
|
421
|
+
prov["tas_chain_note"] = (
|
|
422
|
+
"Rule: tiers tried in order merge -> aircraft -> probe; "
|
|
423
|
+
"the first available source that passes its checks is used; a pinned tier never falls "
|
|
424
|
+
"through. See docs/developer/TAS.md, 'The TAS source chain'")
|
|
425
|
+
head = [f"TAS chain ({mode}): {tier}/{source} used -- {path}"]
|
|
426
|
+
head += [f"TAS chain step: {t_}/{n}: {o}" + (f" ({d})" if d else "")
|
|
427
|
+
for t_, n, o, d in steps]
|
|
428
|
+
return ChainResult(mode, tier, source, path, t, v, policy, steps, subs, head + lines, prov)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def write_chain_file(path, result: ChainResult) -> Path:
|
|
432
|
+
"""The aircraft file for the framing stage, in UIOOPS's ``TAS``/``Time`` convention, carrying
|
|
433
|
+
the whole decision record in its global attributes."""
|
|
434
|
+
return _mtf.write_tas_file(path, result.time, result.tas, provenance=result.provenance)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def series_for_sizedist(probe_time_hhmmss, aircraft_time, aircraft_tas, policy: TasPolicy):
|
|
438
|
+
"""The TAS array the size-distribution stage (``sizeDist``) gets when a run picks aircraft TAS.
|
|
439
|
+
|
|
440
|
+
**The time axis stays the probe's own** (the ``<stem>.tas.csv`` times, floored exactly as
|
|
441
|
+
the probe path floors them), because ``sizeDist``'s output time base *is* its TAS series'
|
|
442
|
+
time axis (the earlier translation's ``sizeDist`` port, at its output time base): swapping the
|
|
443
|
+
axis too would move or remove seconds of the
|
|
444
|
+
product. Only the values are replaced -- by the aircraft TAS at the same whole second, and
|
|
445
|
+
by ``policy.default_mps`` where the aircraft series has none (never dropped).
|
|
446
|
+
Returns ``(time, tas, missing_seconds)``.
|
|
447
|
+
"""
|
|
448
|
+
t = np.floor(np.asarray(probe_time_hhmmss, dtype=np.float64).ravel())
|
|
449
|
+
lookup = dict(zip(np.asarray(aircraft_time, dtype=np.int64).tolist(),
|
|
450
|
+
np.asarray(aircraft_tas, dtype=np.float64).tolist(), strict=True))
|
|
451
|
+
tas = np.empty_like(t)
|
|
452
|
+
missing: list[int] = []
|
|
453
|
+
for i, s in enumerate(t.astype(np.int64).tolist()):
|
|
454
|
+
val = lookup.get(s)
|
|
455
|
+
if val is None or policy.reason(val) is not None:
|
|
456
|
+
tas[i] = policy.default_mps
|
|
457
|
+
missing.append(s)
|
|
458
|
+
else:
|
|
459
|
+
tas[i] = val
|
|
460
|
+
return t, tas, missing
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def regular_grid_hhmmss(probe_time_hhmmss) -> np.ndarray:
|
|
464
|
+
"""A one-second HHMMSS grid from the probe axis's first second to its last, every second once.
|
|
465
|
+
|
|
466
|
+
The probe's own ``<stem>.tas.csv`` axis repeats a second when two housekeeping packets
|
|
467
|
+
fall in it and skips one when none does. ``sizeDist``'s block walk
|
|
468
|
+
(v3.5 ``sizeDist.m:913-927``; v3.1.4 ``:745-754``) files no particle of a skipped second
|
|
469
|
+
and none of a repeated one -- measured
|
|
470
|
+
under Octave on the unmodified v3.5 source.
|
|
471
|
+
This grid has
|
|
472
|
+
neither. Midnight is unwrapped before the span is taken and wrapped back after, so a
|
|
473
|
+
grid crossing it reads ``235959, 0, 1`` as the probe's own does. Returned as float64,
|
|
474
|
+
the dtype the probe axis has.
|
|
475
|
+
"""
|
|
476
|
+
t = np.floor(np.asarray(probe_time_hhmmss, dtype=np.float64).ravel()).astype(np.int64)
|
|
477
|
+
if t.size == 0:
|
|
478
|
+
return np.zeros(0, dtype=np.float64)
|
|
479
|
+
sec = t // 10000 * 3600 + t // 100 % 100 * 60 + t % 100
|
|
480
|
+
# A step back of more than half a day is a midnight crossing, not jitter.
|
|
481
|
+
sec = sec + 86400 * np.concatenate([[0], np.cumsum(np.diff(sec) < -43200)])
|
|
482
|
+
grid = np.arange(sec.min(), sec.max() + 1, dtype=np.int64) % 86400
|
|
483
|
+
return (grid // 3600 * 10000 + grid // 60 % 60 * 100 + grid % 60).astype(np.float64)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def regular_series_for_sizedist(probe_time_hhmmss, aircraft_time, aircraft_tas,
|
|
487
|
+
policy: TasPolicy):
|
|
488
|
+
""":func:`series_for_sizedist` on :func:`regular_grid_hhmmss`'s grid instead of the probe's
|
|
489
|
+
own axis: the same aircraft-value lookup and the same policy default for a second the
|
|
490
|
+
aircraft series lacks, over a time vector with every second of the probe's span once.
|
|
491
|
+
|
|
492
|
+
The opt-in behind ``run_flight.py --tas-grid regular``. It is how UIOOPS's own worked example
|
|
493
|
+
calls ``sizeDist`` with aircraft airspeed
|
|
494
|
+
(``UIOPS-v3.5/joefinlon-UIOPS-039be82/minimal_working_example/run_sizeDist_Munich.m:25-26``
|
|
495
|
+
and ``:40`` hand it the flight file's ``Time`` and ``TAS`` together), with the span kept to the
|
|
496
|
+
probe's so the product covers the seconds it covered before. Returns
|
|
497
|
+
``(time, tas, missing_seconds)``.
|
|
498
|
+
"""
|
|
499
|
+
return series_for_sizedist(regular_grid_hhmmss(probe_time_hhmmss), aircraft_time,
|
|
500
|
+
aircraft_tas, policy)
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
#: The sidecar format's name, so a reader can refuse a record it does not understand.
|
|
504
|
+
QC_CONVENTION = "arrayprobe-tasqc-1"
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _reasons_text(reasons) -> str:
|
|
508
|
+
"""``"above-cutoff:n;...;unsettled-duplicate:k"`` -- every reason the chain substitutes
|
|
509
|
+
for, always all five, so a zero is stated rather than implied and the reasons sum to
|
|
510
|
+
``tas_substituted_count``. A slash-joined probe-tier reason (``"above-cutoff/non-finite"``)
|
|
511
|
+
counts under its first component."""
|
|
512
|
+
reasons = [r.split("/", 1)[0] for r in reasons]
|
|
513
|
+
return ";".join(f"{r}:{reasons.count(r)}" for r in _REASONS)
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _uncertainty_text(n_default: int, total: int, policy: TasPolicy) -> str:
|
|
517
|
+
"""``tas_uncertainty``: one sentence a reader of the attributes needs, for a single product
|
|
518
|
+
(:func:`qc_record`) and for a combine of several (:func:`merge_qc_records`) alike."""
|
|
519
|
+
if n_default == 0:
|
|
520
|
+
return f"none: every second has a measured TAS that passed policy {policy.token()}"
|
|
521
|
+
frac = n_default / total if total else 0.0
|
|
522
|
+
return (f"{n_default} of {total} seconds ({100.0 * frac:.2f} %) sized with default TAS "
|
|
523
|
+
f"{policy.default_mps:g} m/s, not a measured value; sample volume scales with "
|
|
524
|
+
f"TAS, so concentration in those seconds is in error by the unknown factor "
|
|
525
|
+
f"TAS_true/{policy.default_mps:g}. Ranges: arrayprobe_tas_*_ranges.")
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def qc_record(chain: ChainResult | None, policy: TasPolicy, probe_time_hhmmss, missing,
|
|
529
|
+
legacy_subs=None) -> dict:
|
|
530
|
+
"""The TAS data-quality facts for one product: which seconds of the probe's axis
|
|
531
|
+
were sized with a default TAS rather than a measured one, and why.
|
|
532
|
+
|
|
533
|
+
``probe_time_hhmmss`` is the probe's own time axis **before** flooring (``<stem>.tas.csv``);
|
|
534
|
+
``missing`` is :func:`series_for_sizedist`'s third return (``[]`` on a path that never
|
|
535
|
+
called it); ``legacy_subs`` is :func:`substitute`'s ``subs`` for an aircraft file handed
|
|
536
|
+
directly (``--tas-file``, no chain; ``None`` when there is no aircraft file). Keys become
|
|
537
|
+
attribute names under ``arrayprobe_``.
|
|
538
|
+
|
|
539
|
+
``tas_floor_round_residual_*`` counts the absent seconds whose sample ``round``s onto a
|
|
540
|
+
second the chain does have -- seconds lost only because this axis is floored
|
|
541
|
+
(13 on 0812). Reported, not fixed: fixing it changes sd values.
|
|
542
|
+
"""
|
|
543
|
+
t_raw = np.asarray(probe_time_hhmmss, dtype=np.float64).ravel()
|
|
544
|
+
axis = np.floor(t_raw).astype(np.int64).tolist()
|
|
545
|
+
in_axis = set(axis)
|
|
546
|
+
chain_secs = (set(np.asarray(chain.time, dtype=np.int64).tolist())
|
|
547
|
+
if chain is not None else set())
|
|
548
|
+
subs = [(int(s), why) for s, why in (chain.substituted if chain is not None else ())]
|
|
549
|
+
subs += [(int(s), why) for s, _orig, why in (legacy_subs or ())]
|
|
550
|
+
subs = [(s, why) for s, why in subs if s in in_axis]
|
|
551
|
+
sub_secs = {s for s, _ in subs}
|
|
552
|
+
missing = [int(s) for s in missing]
|
|
553
|
+
missing_set = set(missing)
|
|
554
|
+
absent = sorted(s for s in missing_set if s not in chain_secs)
|
|
555
|
+
absent_set = set(absent)
|
|
556
|
+
residual = sorted({s for s, x in zip(axis, t_raw.tolist(), strict=True)
|
|
557
|
+
if s in absent_set and int(np.round(x)) in chain_secs})
|
|
558
|
+
total = len(axis)
|
|
559
|
+
n_sub = sum(1 for s in axis if s in sub_secs and s not in missing_set)
|
|
560
|
+
n_default = n_sub + len(missing)
|
|
561
|
+
frac = n_default / total if total else 0.0
|
|
562
|
+
if chain is not None:
|
|
563
|
+
used = f"{chain.tier}:{chain.source}"
|
|
564
|
+
else:
|
|
565
|
+
used = "tas-file" if legacy_subs is not None else "none"
|
|
566
|
+
text = _uncertainty_text(n_default, total, policy)
|
|
567
|
+
return {
|
|
568
|
+
"tas_qc_convention": QC_CONVENTION,
|
|
569
|
+
"tas_chain_used": used,
|
|
570
|
+
"tas_policy": policy.token(),
|
|
571
|
+
"tas_seconds_total": total,
|
|
572
|
+
"tas_substituted_count": len(sub_secs),
|
|
573
|
+
"tas_substituted_ranges": second_ranges(sub_secs),
|
|
574
|
+
"tas_substituted_reasons": _reasons_text(why for _, why in subs),
|
|
575
|
+
"tas_missing_count": len(missing),
|
|
576
|
+
"tas_missing_ranges": second_ranges(missing),
|
|
577
|
+
"tas_missing_absent_count": len(absent),
|
|
578
|
+
"tas_missing_absent_ranges": second_ranges(absent),
|
|
579
|
+
"tas_floor_round_residual_count": len(residual),
|
|
580
|
+
"tas_floor_round_residual_ranges": second_ranges(residual),
|
|
581
|
+
"tas_defaulted_fraction": float(frac),
|
|
582
|
+
"tas_uncertainty": text,
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
_REASONS = ("above-cutoff", "non-finite", "non-positive", "no-aircraft-sample",
|
|
587
|
+
"unsettled-duplicate")
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def merge_qc_records(parts) -> dict:
|
|
591
|
+
"""One record for a combined product from its constituents' records.
|
|
592
|
+
|
|
593
|
+
``parts`` is ``[(sd_filename, record), ...]`` in stitch order. Counts are summed, ranges
|
|
594
|
+
concatenated in that order, reasons summed per reason, and the fraction and uncertainty
|
|
595
|
+
text recomputed over the summed axis; ``tas_qc_parts`` names every part. The parts must
|
|
596
|
+
share one policy -- :func:`check_combine_provenance` has already refused inputs whose
|
|
597
|
+
stamps disagree, so a mismatch here is a bug, raised rather than averaged over.
|
|
598
|
+
"""
|
|
599
|
+
parts = list(parts)
|
|
600
|
+
if not parts:
|
|
601
|
+
raise ValueError("merge_qc_records: no parts")
|
|
602
|
+
recs = [rec for _, rec in parts]
|
|
603
|
+
policies = {rec["tas_policy"] for rec in recs}
|
|
604
|
+
if len(policies) != 1:
|
|
605
|
+
raise ValueError(f"merge_qc_records: parts disagree on tas_policy: {sorted(policies)}")
|
|
606
|
+
policy = TasPolicy.parse(policies.pop())
|
|
607
|
+
total = sum(int(rec["tas_seconds_total"]) for rec in recs)
|
|
608
|
+
n_default = sum(int(round(float(rec["tas_defaulted_fraction"])
|
|
609
|
+
* int(rec["tas_seconds_total"]))) for rec in recs)
|
|
610
|
+
out = {
|
|
611
|
+
"tas_qc_convention": QC_CONVENTION,
|
|
612
|
+
"tas_chain_used": ",".join(dict.fromkeys(rec["tas_chain_used"] for rec in recs)),
|
|
613
|
+
"tas_policy": policy.token(),
|
|
614
|
+
"tas_seconds_total": total,
|
|
615
|
+
"tas_defaulted_fraction": float(n_default / total if total else 0.0),
|
|
616
|
+
"tas_uncertainty": _uncertainty_text(n_default, total, policy),
|
|
617
|
+
"tas_qc_parts": ",".join(name for name, _ in parts),
|
|
618
|
+
}
|
|
619
|
+
for stem in ("tas_substituted", "tas_missing", "tas_missing_absent",
|
|
620
|
+
"tas_floor_round_residual"):
|
|
621
|
+
out[f"{stem}_count"] = sum(int(rec[f"{stem}_count"]) for rec in recs)
|
|
622
|
+
out[f"{stem}_ranges"] = ",".join(r for r in (rec[f"{stem}_ranges"] for rec in recs) if r)
|
|
623
|
+
counts = dict.fromkeys(_REASONS, 0)
|
|
624
|
+
for rec in recs:
|
|
625
|
+
for item in rec["tas_substituted_reasons"].split(";"):
|
|
626
|
+
reason, n = item.rsplit(":", 1)
|
|
627
|
+
counts[reason] += int(n)
|
|
628
|
+
out["tas_substituted_reasons"] = ";".join(f"{r}:{counts[r]}" for r in _REASONS)
|
|
629
|
+
return out
|
|
630
|
+
|
|
631
|
+
def qc_sidecar_path(product) -> Path:
|
|
632
|
+
"""``<product>.tasqc.json``, beside the product; staleness checks never read it."""
|
|
633
|
+
product = Path(product)
|
|
634
|
+
return product.with_name(product.name + ".tasqc.json")
|
|
635
|
+
|
|
636
|
+
|
|
637
|
+
def write_qc_sidecar(product, rec: dict) -> Path:
|
|
638
|
+
"""Write ``rec`` as sorted-key JSON beside ``product``, partial-then-rename like the
|
|
639
|
+
``.decode`` and ``.call`` sidecars, so a kill never leaves a half-written record."""
|
|
640
|
+
target = qc_sidecar_path(product)
|
|
641
|
+
partial = target.with_name(target.name + ".partial")
|
|
642
|
+
partial.write_text(_json.dumps(rec, sort_keys=True, indent=1) + "\n",
|
|
643
|
+
encoding="utf-8")
|
|
644
|
+
_os.replace(partial, target)
|
|
645
|
+
return target
|
|
646
|
+
|
|
647
|
+
|
|
648
|
+
#: Per-second TAS quality flag values, for the CF and ARM exports.
|
|
649
|
+
QC_FLAG_MEASURED, QC_FLAG_SUBSTITUTED, QC_FLAG_DEFAULTED = 0, 1, 2
|
|
650
|
+
|
|
651
|
+
|
|
652
|
+
def expand_ranges(ranges: str) -> set[int]:
|
|
653
|
+
"""The inverse of :func:`second_ranges`: ``"124838-124840,130000"`` -> the HHMMSS seconds,
|
|
654
|
+
stepping in seconds of day so a range across a minute or hour boundary is exact."""
|
|
655
|
+
out: set[int] = set()
|
|
656
|
+
for part in filter(None, (p.strip() for p in (ranges or "").split(","))):
|
|
657
|
+
lo, _, hi = part.partition("-")
|
|
658
|
+
a = int(_mtf._hhmmss_to_sod([int(lo)])[0])
|
|
659
|
+
b = int(_mtf._hhmmss_to_sod([int(hi or lo)])[0])
|
|
660
|
+
for sod in range(a, b + 1):
|
|
661
|
+
out.add((sod // 3600) * 10000 + (sod % 3600 // 60) * 100 + sod % 60)
|
|
662
|
+
return out
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def qc_flags(rec: dict, time_hhmmss) -> np.ndarray:
|
|
666
|
+
"""One flag per ``time_hhmmss`` second: 2 where the record says the second took the default
|
|
667
|
+
(absent from every tier, or lost to the floor/round residual), else 1 where a tier's value
|
|
668
|
+
was substituted by policy, else 0. Seconds are matched as whole HHMMSS."""
|
|
669
|
+
t = np.rint(np.asarray(time_hhmmss, dtype=np.float64).ravel()).astype(np.int64)
|
|
670
|
+
subst = expand_ranges(rec.get("tas_substituted_ranges", ""))
|
|
671
|
+
dflt = (expand_ranges(rec.get("tas_missing_ranges", ""))
|
|
672
|
+
| expand_ranges(rec.get("tas_floor_round_residual_ranges", "")))
|
|
673
|
+
flags = np.full(t.shape, QC_FLAG_MEASURED, dtype=np.int8)
|
|
674
|
+
flags[np.isin(t, sorted(subst))] = QC_FLAG_SUBSTITUTED
|
|
675
|
+
flags[np.isin(t, sorted(dflt))] = QC_FLAG_DEFAULTED
|
|
676
|
+
return flags
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def read_qc_sidecar(product) -> dict | None:
|
|
680
|
+
"""The record :func:`write_qc_sidecar` wrote beside ``product``, or ``None`` when there is
|
|
681
|
+
none. A record of another convention raises rather than being read as this one."""
|
|
682
|
+
target = qc_sidecar_path(product)
|
|
683
|
+
if not target.is_file():
|
|
684
|
+
return None
|
|
685
|
+
rec = _json.loads(target.read_text(encoding="utf-8"))
|
|
686
|
+
if rec.get("tas_qc_convention") != QC_CONVENTION:
|
|
687
|
+
raise ValueError(f"{target.name}: convention {rec.get('tas_qc_convention')!r}, "
|
|
688
|
+
f"expected {QC_CONVENTION!r}")
|
|
689
|
+
return rec
|
|
690
|
+
|
|
691
|
+
def write_soda2_pth_csv(path, time_hhmmss, tas_mps) -> Path:
|
|
692
|
+
"""The same series as a SODA-2 ``op.pth`` ASCII file (``soda2_process_2d.pro:147-162``,
|
|
693
|
+
ported as ``arrayprobe_soda2.pth_readers.read_pth_ascii``): one ``<seconds of day>,<tas>``
|
|
694
|
+
line per sample, since SODA-2's ``op.starttime`` is seconds from midnight. SODA-2 fills each
|
|
695
|
+
accepted row forward and accepts ``0 < tas < 500`` (``:156``), so a series that has been
|
|
696
|
+
through :class:`TasPolicy` passes whole when the cutoff is below 500 m/s."""
|
|
697
|
+
t = np.asarray(time_hhmmss, dtype=np.float64).ravel()
|
|
698
|
+
v = np.asarray(tas_mps, dtype=np.float64).ravel()
|
|
699
|
+
sod = _mtf._hhmmss_to_sod(t)
|
|
700
|
+
order = np.argsort(sod, kind="stable")
|
|
701
|
+
path = Path(path)
|
|
702
|
+
with open(path, "w", encoding="ascii", newline="\n") as fh:
|
|
703
|
+
for s, x in zip(sod[order].tolist(), v[order].tolist(), strict=True):
|
|
704
|
+
fh.write(f"{int(round(s))},{x!r}\n")
|
|
705
|
+
return path
|