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,760 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Write the aircraft TAS file stock ``imgProc_sm.m`` reads as ``varargin{1}``.
3
+
4
+ Built 2026-09-16 on the cold-start usability audit's finding 1.2. The v3.5 engine
5
+ -- the package default, the one the Configuration page's decision tree sends a new user to
6
+ -- refuses to run without this file, citing ``imgProc_sm.m:183-185``. The refusal is good.
7
+ The problem the audit measured is that **no page stated the file's contents**: `<aircraft
8
+ TAS file>` appeared as a placeholder in the decision tree and as a path in an example, and
9
+ the only way to learn the schema was to open a tracked fixture with ``netCDF4``. So a
10
+ scientist with their own 2D-S data and no ORACLES involvement could not run the default
11
+ engine at all.
12
+
13
+ **The schema, read off what the port actually does** (``imgproc.py:531-532``)::
14
+
15
+ tas = ncio.ncread(tas_file, "TAS") # m/s
16
+ tas_time = ncio.ncread(tas_file, "Time") # HHMMSS
17
+
18
+ Two 1-D variables of equal length, read by those exact names through ``ncread`` (so any
19
+ ``scale_factor``/``add_offset``/``_FillValue`` a file carries is applied). ``Time`` is
20
+ HHMMSS-as-a-number -- 06:06:38 is ``60638.0``, not seconds since an epoch -- because
21
+ ``imgProc_sm`` compares it against the probe's own housekeeping clock, which is HHMMSS.
22
+ Nothing else in the file is read: no units attribute, no global attribute, no dimension
23
+ name is required. This tool writes ``f8`` for both and names the dimension ``time``,
24
+ matching ``scripts/make_demo_reference.write_aircraft_v35`` and the tracked fixture
25
+ ``tests/data/demo_flight_v35_aircraft.cdf``.
26
+
27
+ **Where the numbers come from.** Two sources, and the tool refuses to invent a third:
28
+
29
+ * ``--from-tas-csv <stem>.tas.csv`` -- the sidecar S2 already writes beside every decode
30
+ (``read_binary_SPEC.m``'s own ``.tas.csv``), whose first two columns are exactly
31
+ ``timehhmmss, tas``. This is the audit's own suggestion, and it is the path to use when
32
+ the probe recorded the aircraft speed. Parsed by
33
+ :func:`arrayprobe.readers.tasinfo.load_tas_info`, so the two columns are read by the
34
+ same code ``loadTASinfo_2DS.m`` is ported into rather than by a second parser that could
35
+ disagree with it.
36
+ * ``--constant-tas`` with ``--start-hhmmss`` and ``--seconds`` -- a flat series, for a
37
+ campaign whose TAS is held outside the probe file. **Named a constant explicitly**, so
38
+ it cannot be mistaken for a measurement: the tool will not derive a "typical" speed from
39
+ anything.
40
+
41
+ **The S2 ``.tas.csv`` is sub-second and jittered** (``110126.232``, ``124834.999``,
42
+ ``124838.000``, ...), and ``imgProc_sm.m:727`` (``imgproc.py:1027``) looks each image record's
43
+ integer HHMMSS up by **exact equality**. A fractional ``Time`` therefore matches almost never
44
+ and every record silently falls back to 170 m/s (``imgproc.py:118``) -- measured 2026-09-23 on
45
+ every finished ORACLES 2017 v3.5 product --
46
+ and a repeated integer ``Time`` makes MATLAB die at ``:738`` (the
47
+ port raises). So the CSV path reduces to whole seconds, and :func:`write_tas_file` refuses a
48
+ ``Time`` that is non-finite, non-integer or repeated. The port's refusal is faithful and stays;
49
+ the remedy lives here, in the sidecar builder, never in the engine.
50
+
51
+ **The reduction takes two design decisions; both are the defaults and both stay
52
+ options:**
53
+
54
+ * ``--second-rule {round,floor}``, default **round** -- how a fractional HHMMSS becomes a
55
+ second. They collide different pairs (``124835.999`` is 124836 under round, 124835 under
56
+ floor).
57
+ * ``--neighbour {adjacent,nearest-present}``, default **adjacent** -- what "the previous or the
58
+ next time step" means: the second just before / just after (s-1, s+1; absent if missing), or
59
+ the nearest second that is present. At 124838 of ``base170821110122`` the first resolves and
60
+ the second does not.
61
+
62
+ **Out-of-range TAS and unsettled duplicates fall to a default -- nothing is dropped (author;
63
+ this replaces an earlier ruling to drop such rows):** *"never drop, use a cutoff and a default
64
+ to fall to, provide user an option to select both in config so nothing is hard coded."* A row
65
+ whose TAS is above the cutoff, at or below 0 m/s (the decode's -999 marker) or non-finite is set
66
+ aside before the duplicate comparison; a second left with no in-range row, and a duplicated
67
+ second the duplicate rule cannot settle, both **take the default value**. The cutoff and the default
68
+ are a :class:`TasPolicy` -- ``--cutoff-mps`` / ``--default-mps`` here, ``[tas].cutoff_mps`` /
69
+ ``[tas].default_mps`` in a run configuration -- whose documented defaults are
70
+ :data:`DEFAULT_CUTOFF_MPS` = 300 m/s (the largest ``tas_max`` in UIOOPS's probe table,
71
+ ``constants.py:492``, ``:559``) and :data:`DEFAULT_FALLBACK_MPS` = 170 m/s
72
+ (the value ``imgProc_sm.m:365``/``:763`` falls back to; the engine's own ``TAS_FALLBACK`` is not
73
+ touched or read by this module). Every substituted second is printed, one line each, and listed
74
+ in the file's global attributes (``tas_substituted_seconds``, with its reason).
75
+
76
+ **When two samples land on one second: the author's rule, verbatim:**
77
+ *"For the Oracle's flight that fails, you look at the true airspeed from either of the previous
78
+ or the next time steps, and whatever looks the same as the double time step, you take that."*
79
+ + *"and you document that decision and put it up whenever it comes up in the processing
80
+ chain."* Implemented as: all candidates identical -> keep one; exactly one distinct candidate
81
+ value equals the previous or next second's TAS (exact equality) -> keep it; otherwise
82
+ (several match, none matches, or no neighbour) -> **the rule picks nothing, and the second takes
83
+ the default**, printed as ``TAS substituted: <HHMMSS> ... unsettled-duplicate``.
84
+ ``--on-unsettled refuse`` keeps the stop-and-list behaviour available (write no file, list the
85
+ seconds). A neighbour second that itself holds several distinct values, or was itself
86
+ substituted, counts as having no known TAS. Every resolved second is printed, one line each, and
87
+ recorded in the file's global attributes (``tas_duplicate_rule``, ``tas_duplicates_resolved``,
88
+ ``tas_duplicates_resolved_seconds``, ...).
89
+
90
+ **Aircraft sources** (``--from-merge``, ``--from-aircraft``, ``--chain``) are
91
+ :mod:`arrayprobe.tools.tas_sources`: the ORACLES P-3 merge file and ARM's AAF merged file, read
92
+ off real files and listed in a registry there, converted by the units attribute each carries,
93
+ under the same :class:`TasPolicy`.
94
+
95
+ The ``--constant-tas`` path copies nothing measured and writes ``Time`` exactly as given
96
+ (whole seconds by construction).
97
+ """
98
+
99
+ from __future__ import annotations
100
+
101
+ import argparse
102
+ import sys
103
+ from collections.abc import Sequence
104
+ from dataclasses import dataclass
105
+ from pathlib import Path
106
+
107
+ import numpy as np
108
+
109
+ __all__ = ["write_tas_file", "check_tas_series", "tas_from_csv", "constant_tas",
110
+ "whole_second_series", "reduce_probe_csv", "TasPolicy", "DEFAULT_CUTOFF_MPS",
111
+ "DEFAULT_FALLBACK_MPS", "SECOND_RULES", "NEIGHBOUR_RULES", "UNSETTLED_RULES",
112
+ "TAS_DUPLICATE_RULE", "build_parser", "main"]
113
+
114
+ #: The two variable names ``imgproc.py:531-532`` reads. Named here so a rename there is a
115
+ #: test failure rather than a file this tool writes that the engine cannot read.
116
+ TAS_VARIABLE = "TAS"
117
+ TIME_VARIABLE = "Time"
118
+
119
+ #: The two reductions to whole seconds. The choice is the author's (no default anywhere).
120
+ SECOND_RULES = ("round", "floor")
121
+ #: The two readings of "the previous or the next time step". The author's choice.
122
+ NEIGHBOUR_RULES = ("adjacent", "nearest-present")
123
+ #: Written into the file so the decision travels with every product built from it.
124
+ TAS_DUPLICATE_RULE = ("Rule: keep the duplicate whose TAS equals the previous "
125
+ "or next second's; when it picks no candidate the second takes the default "
126
+ "value")
127
+ #: The author's choices (2026-09-23): round to the second, and "neighbour" is
128
+ #: the second just before / just after. Defaults because the author set them; still options.
129
+ AUTHOR_SECOND_RULE = "round"
130
+ AUTHOR_NEIGHBOUR_RULE = "adjacent"
131
+ #: Documented DEFAULTS for the two options, never read by the logic directly: every
132
+ #: function takes a :class:`TasPolicy`, and these are only what one is built with when the
133
+ #: caller names nothing. 300 m/s is the largest ``tas_max`` in UIOOPS's probe table
134
+ #: (constants.py:492, :559); 170 m/s is the value
135
+ #: ``imgProc_sm.m:365``/``:763`` falls back to (``tests/test_tas_sources.py`` asserts it equals
136
+ #: ``arrayprobe.imgproc.TAS_FALLBACK`` -- read from the engine, compared, never imported here).
137
+ DEFAULT_CUTOFF_MPS = 300.0
138
+ DEFAULT_FALLBACK_MPS = 170.0
139
+ #: A TAS at or below this is not a speed (author: "default yes") -- it catches the
140
+ #: decode's -999 "no TAS" marker, which MATLAB would otherwise use as a speed
141
+ #: (``imgProc_sm.m:730`` substitutes the fallback only for an empty or NaN match). This one is a
142
+ #: definition rather than an option: a non-positive airspeed is not an airspeed.
143
+ TAS_NONPOSITIVE_MPS = 0.0
144
+ #: What happens to a duplicated second the neighbour rule cannot settle. The author's ruling
145
+ #: is that it takes the default value. ``"refuse"`` keeps the stop-and-list behaviour.
146
+ UNSETTLED_RULES = ("default", "refuse")
147
+ AUTHOR_UNSETTLED_RULE = "default"
148
+
149
+
150
+ def write_tas_csv(path: str | Path, time_hhmmss: Sequence[float] | np.ndarray,
151
+ tas_mps: Sequence[float] | np.ndarray,
152
+ seconds_of_day: Sequence[float] | np.ndarray | None = None) -> int:
153
+ """Write the nine-column ``.tas.csv`` and return the row count.
154
+
155
+ Columns 1-2 are ``timehhmmss, tas``, the only two
156
+ :func:`arrayprobe.readers.tasinfo.load_tas_info` and ``loadTASinfo_2DS.m``'s
157
+ ``'%f%f%*s%*s%*s%*s%*s%*s%*s'`` read. Column 3 carries the seconds of day the HHMMSS was
158
+ packed from, and 4-9 are ``0`` -- the same nine-field shape
159
+ the CIP-housekeeping TAS producer writes, so the two SEA-chain TAS producers hand the
160
+ pipeline the same thing.
161
+ """
162
+ t = np.asarray(time_hhmmss, dtype=np.float64).ravel()
163
+ v = np.asarray(tas_mps, dtype=np.float64).ravel()
164
+ if t.size != v.size:
165
+ raise ValueError(f"time has {t.size} samples and tas has {v.size}")
166
+ if t.size == 0:
167
+ raise ValueError("refusing to write an empty .tas.csv")
168
+ s = (np.asarray(seconds_of_day, dtype=np.float64).ravel()
169
+ if seconds_of_day is not None else np.zeros_like(t))
170
+ lines = [f"{float(a):f}, {float(b):f}, {float(c):f}, 0, 0, 0, 0, 0, 0\n"
171
+ for a, b, c in zip(t, v, s, strict=True)]
172
+ Path(path).write_text("".join(lines))
173
+ return len(lines)
174
+
175
+
176
+ @dataclass(frozen=True)
177
+ class TasPolicy:
178
+ """The TAS policy pair: a cutoff above which a TAS is not believed, and the value a second
179
+ falls to when its TAS is out of range or unsettled. Both configurable (``[tas]`` in a run
180
+ configuration, ``--cutoff-mps``/``--default-mps`` on the command line)."""
181
+
182
+ cutoff_mps: float = DEFAULT_CUTOFF_MPS
183
+ default_mps: float = DEFAULT_FALLBACK_MPS
184
+
185
+ def __post_init__(self):
186
+ c, d = float(self.cutoff_mps), float(self.default_mps)
187
+ if not (np.isfinite(c) and np.isfinite(d)):
188
+ raise ValueError(f"TAS policy values must be finite, got cutoff={c!r}, default={d!r}")
189
+ if c <= TAS_NONPOSITIVE_MPS:
190
+ raise ValueError(f"TAS cutoff must be above {TAS_NONPOSITIVE_MPS:g} m/s, got {c!r}")
191
+ if not TAS_NONPOSITIVE_MPS < d <= c:
192
+ raise ValueError(f"TAS default must lie in ({TAS_NONPOSITIVE_MPS:g}, cutoff={c:g}] "
193
+ f"m/s so a substituted second passes the same check, got {d!r}")
194
+
195
+ def reason(self, value: float) -> str | None:
196
+ """Why ``value`` is out of range (``None`` when it is in range)."""
197
+ if not np.isfinite(value):
198
+ return "non-finite"
199
+ if value > self.cutoff_mps:
200
+ return "above-cutoff"
201
+ if value <= TAS_NONPOSITIVE_MPS:
202
+ return "non-positive"
203
+ return None
204
+
205
+ def token(self) -> str:
206
+ """One-line, round-trippable form, for ``.call`` stamps, attributes and worker argv."""
207
+ return f"cutoff={float(self.cutoff_mps)!r},default={float(self.default_mps)!r}"
208
+
209
+ @classmethod
210
+ def parse(cls, token: str) -> TasPolicy:
211
+ """The inverse of :meth:`token`: ``"cutoff=300.0,default=170.0"`` -> a policy."""
212
+ fields = dict(part.split("=", 1) for part in token.split(","))
213
+ return cls(float(fields["cutoff"]), float(fields["default"]))
214
+
215
+ def attributes(self) -> dict:
216
+ """The policy as file attributes: the token, both speeds and a note on the rule."""
217
+ return {
218
+ "tas_policy": self.token(),
219
+ "tas_cutoff_mps": float(self.cutoff_mps),
220
+ "tas_default_mps": float(self.default_mps),
221
+ "tas_policy_note": (
222
+ "Rule: never drop; a TAS above tas_cutoff_mps, at or below "
223
+ "0 m/s (incl. the -999 no-TAS marker) or non-finite, and a duplicated second the "
224
+ "duplicate rule cannot settle, take tas_default_mps. Documented defaults 300 m/s "
225
+ "(largest UIOPS tas_max) and 170 m/s (imgProc_sm.m:365/"
226
+ ":763's fallback); both configurable ([tas] in a run config, "
227
+ "--cutoff-mps/--default-mps)"),
228
+ }
229
+
230
+
231
+ def second_ranges(seconds) -> str:
232
+ """``[124838, 124839, 124840, 130000]`` -> ``"124838-124840,130000"`` (HHMMSS, contiguous
233
+ in seconds of day), so an attribute can list every substituted second compactly."""
234
+ secs = sorted({int(s) for s in seconds})
235
+ if not secs:
236
+ return ""
237
+ sod = [int(_hhmmss_to_sod([s])[0]) for s in secs]
238
+ out, i = [], 0
239
+ while i < len(secs):
240
+ j = i
241
+ while j + 1 < len(secs) and sod[j + 1] == sod[j] + 1:
242
+ j += 1
243
+ out.append(f"{secs[i]:06d}" if i == j else f"{secs[i]:06d}-{secs[j]:06d}")
244
+ i = j + 1
245
+ return ",".join(out)
246
+
247
+
248
+ def check_tas_series(time_hhmmss, tas_mps) -> tuple[np.ndarray, np.ndarray]:
249
+ """Refuse a ``(Time, TAS)`` series that ``imgProc_sm.m:727``'s exact-match lookup cannot use.
250
+
251
+ The one check every aircraft series passes before the engine sees it -- the file this
252
+ tool writes, and an aircraft file ``run_flight.py`` is handed
253
+ directly, such as ARM's merged file. Returns the two arrays as 1-D float64.
254
+ """
255
+ time_hhmmss = np.asarray(time_hhmmss, dtype=np.float64).ravel()
256
+ tas_mps = np.asarray(tas_mps, dtype=np.float64).ravel()
257
+ if time_hhmmss.size != tas_mps.size:
258
+ raise ValueError(
259
+ f"Time has {time_hhmmss.size} samples and TAS has {tas_mps.size}; "
260
+ "imgProc_sm.m:183-185 indexes them together, so they must be the same length")
261
+ if time_hhmmss.size == 0:
262
+ raise ValueError("no samples: a TAS file with an empty time axis sets no "
263
+ "particle time at all")
264
+ bad = ~np.isfinite(time_hhmmss)
265
+ if bad.any():
266
+ raise ValueError(f"{int(bad.sum())} non-finite Time value(s): imgProc_sm.m:727 "
267
+ "matches Time by exact equality, so such a row can never match")
268
+ frac = time_hhmmss != np.floor(time_hhmmss)
269
+ if frac.any():
270
+ raise ValueError(
271
+ f"{int(frac.sum())} of {time_hhmmss.size} Time values are not whole seconds "
272
+ f"(first: {time_hhmmss[frac][0]!r}): imgProc_sm.m:727 looks the record's integer "
273
+ "HHMMSS up by exact equality, so a fractional Time never matches and every record "
274
+ "silently takes the 170 m/s fallback (imgproc.py:118). Reduce to whole seconds "
275
+ "first (make-tas-file --from-tas-csv ... --second-rule {round,floor})")
276
+ uniq, counts = np.unique(time_hhmmss, return_counts=True)
277
+ if (counts > 1).any():
278
+ rep = uniq[counts > 1]
279
+ raise ValueError(
280
+ f"{rep.size} repeated Time value(s) (first: {rep[0]:.0f}): a second with more "
281
+ "than one TAS makes imgProc_sm.m:738 fail (the port raises too). Resolve the "
282
+ "duplicates first (make-tas-file --from-tas-csv, the duplicate rule)")
283
+ t = time_hhmmss.astype(np.int64)
284
+ # UIOOPS's midnight convention is unwrapped: a flight crossing midnight keeps counting
285
+ # 240000, 240001, ... rather than wrapping to 000000 (sizeDist.m:98-99/:657-658's
286
+ # +240000 rollover, ported as arrayprobe.sizedist._rollover_240000).
287
+ # So an hour of 24-47 (one further midnight crossing) is a
288
+ # valid clock hour here, not "probably seconds since some epoch" -- only the minute and
289
+ # second fields, and an hour past what one rollover can reach, distinguish a real epoch
290
+ # value from an unwrapped clock time.
291
+ bad_clock = (t < 0) | (t // 10000 > 47) | (t % 100 >= 60) | ((t // 100) % 100 >= 60)
292
+ if bad_clock.any():
293
+ raise ValueError(
294
+ f"{int(bad_clock.sum())} of {t.size} Time values are not a clock time HHMMSS "
295
+ f"(first: {t[bad_clock][0]}): the axis is probably seconds since some epoch, which "
296
+ "never equals the record's HHMMSS at imgProc_sm.m:727, so every particle would "
297
+ "silently take the 170 m/s fallback (imgproc.py:118)")
298
+ return time_hhmmss, tas_mps
299
+
300
+
301
+ def write_tas_file(path, time_hhmmss, tas_mps, *, provenance: dict | None = None) -> Path:
302
+ """Write ``path`` as NETCDF3_CLASSIC with ``Time`` (HHMMSS) and ``TAS`` (m/s), f8.
303
+
304
+ NETCDF3_CLASSIC for the same reason every other file this package writes is
305
+ (MATLAB's bare ``'clobber'`` default). Both arrays must be 1-D and the
306
+ same length -- ``imgProc_sm`` indexes them together, so a mismatch here would be a
307
+ silently misaligned time base rather than an error at read time.
308
+ """
309
+ import netCDF4
310
+
311
+ time_hhmmss, tas_mps = check_tas_series(time_hhmmss, tas_mps)
312
+ path = Path(path)
313
+ with netCDF4.Dataset(str(path), "w", format="NETCDF3_CLASSIC") as ds:
314
+ ds.createDimension("time", time_hhmmss.size)
315
+ # units/long_name are written for the human who opens the file. The engine reads
316
+ # neither (imgproc.py:531-532 is two bare ncread calls), so adding them changes no
317
+ # computed number -- the audit's own complaint about the combined product, answered
318
+ # here rather than repeated.
319
+ v_time = ds.createVariable(TIME_VARIABLE, "f8", ("time",))
320
+ v_time.units = "HHMMSS"
321
+ v_time.long_name = "time of day as HHMMSS, the probe housekeeping clock's own base"
322
+ v_time[:] = time_hhmmss
323
+ v_tas = ds.createVariable(TAS_VARIABLE, "f8", ("time",))
324
+ v_tas.units = "m s-1"
325
+ v_tas.long_name = "aircraft true air speed"
326
+ v_tas[:] = tas_mps
327
+ # Global attributes only: the engine reads Time and TAS and nothing else
328
+ # (imgproc.py:531-532), so provenance here changes no computed number.
329
+ for key, value in (provenance or {}).items():
330
+ ds.setncattr(key, value)
331
+ return path
332
+
333
+
334
+ def tas_from_csv(csv_path) -> tuple[np.ndarray, np.ndarray]:
335
+ """``(Time, TAS)`` from a ``<stem>.tas.csv`` the decode wrote.
336
+
337
+ Delegates to :func:`arrayprobe.readers.tasinfo.load_tas_info` -- the port of
338
+ ``loadTASinfo_2DS.m`` -- rather than parsing the CSV again here, so the two columns
339
+ this tool copies are the two columns the MATLAB lineage reads.
340
+ """
341
+ from arrayprobe.readers.tasinfo import load_tas_info
342
+
343
+ return load_tas_info(csv_path)
344
+
345
+
346
+ def _hhmmss_to_sod(hhmmss) -> np.ndarray:
347
+ """HHMMSS (possibly fractional) to fractional seconds of day: the formula of
348
+ ``scripts/tas_from_probe_housekeeping.hhmmss_to_seconds`` (``:57-63``) without
349
+ its ``floor`` on the seconds, because the reduction is chosen separately (``second_rule``).
350
+ Copied, not imported: ``scripts/`` is not importable from ``src/``."""
351
+ h = np.asarray(hhmmss, dtype=np.float64)
352
+ hh = np.floor(h / 10000.0)
353
+ mm = np.floor((h - hh * 10000.0) / 100.0)
354
+ ss = h - hh * 10000.0 - mm * 100.0
355
+ return hh * 3600.0 + mm * 60.0 + ss
356
+
357
+
358
+ def _sod_to_hhmmss(sod) -> np.ndarray:
359
+ """Whole seconds of day back to HHMMSS: ``tas_from_probe_housekeeping._hhmmss``
360
+ (``:119-121``), copied. HHMMSS does not carry by adding 1, so the carry is done here."""
361
+ s = np.asarray(sod, dtype=np.int64)
362
+ return ((s // 3600) * 10000 + ((s % 3600) // 60) * 100 + (s % 60)).astype(np.float64)
363
+
364
+
365
+ def whole_second_series(time_hhmmss, tas, *, second_rule: str = AUTHOR_SECOND_RULE,
366
+ neighbour: str = AUTHOR_NEIGHBOUR_RULE,
367
+ policy: TasPolicy | None = None,
368
+ unsettled: str = AUTHOR_UNSETTLED_RULE):
369
+ """Reduce a sub-second ``(Time, TAS)`` series to one sample per whole second.
370
+
371
+ ``second_rule`` (``"round"`` = ``floor(sod + 0.5)``, ``"floor"`` = ``floor(sod)``) and
372
+ ``neighbour`` (``"adjacent"`` = s-1 / s+1 only, ``"nearest-present"`` = the nearest
373
+ second present on each side) default to round and adjacent.
374
+
375
+ Rows out of range under ``policy`` (above its cutoff, at/below 0 m/s, non-finite) are set
376
+ aside before grouping, one ``class="out-of-range"`` record per second: ``remaining`` says
377
+ whether in-range rows keep that second; if not, the second **takes ``policy.default_mps``**
378
+ (``fallback``). A duplicated second the rule cannot settle (``class="ambiguous"``) takes the
379
+ default too under ``unsettled="default"``; under ``"refuse"`` it is left out of the series and
380
+ the caller must refuse to write. Nothing is dropped under the default.
381
+
382
+ Returns ``(time, tas, report)``. One record (a dict) per second with more than one sample or
383
+ an out-of-range row: ``second`` (HHMMSS int), ``class`` (``identical`` / ``unambiguous`` /
384
+ ``ambiguous`` / ``out-of-range``), ``candidates`` (every TAS, row order), ``prev`` / ``next``
385
+ (the neighbour's TAS; ``None`` when absent, substituted, or itself holding several distinct
386
+ values), ``prev_missing`` / ``next_missing``, ``kept`` (``None`` when ambiguous),
387
+ ``fallback`` (the default value the second took, else ``None``), ``reasons``.
388
+ """
389
+ if second_rule not in SECOND_RULES:
390
+ raise ValueError(f"second_rule must be one of {SECOND_RULES}, got {second_rule!r}")
391
+ if neighbour not in NEIGHBOUR_RULES:
392
+ raise ValueError(f"neighbour must be one of {NEIGHBOUR_RULES}, got {neighbour!r}")
393
+ if unsettled not in UNSETTLED_RULES:
394
+ raise ValueError(f"unsettled must be one of {UNSETTLED_RULES}, got {unsettled!r}")
395
+ policy = policy or TasPolicy()
396
+ t = np.asarray(time_hhmmss, dtype=np.float64).ravel()
397
+ v = np.asarray(tas, dtype=np.float64).ravel()
398
+ if t.size != v.size:
399
+ raise ValueError(f"Time has {t.size} samples and TAS has {v.size}")
400
+ sod = _hhmmss_to_sod(t)
401
+ key = (np.floor(sod + 0.5) if second_rule == "round" else np.floor(sod)).astype(np.int64)
402
+
403
+ groups: dict[int, list[float]] = {}
404
+ aside: dict[int, list[float]] = {}
405
+ reasons: dict[int, list[str]] = {}
406
+ for k, x in zip(key.tolist(), v.tolist(), strict=True):
407
+ why = policy.reason(x)
408
+ if why is None:
409
+ groups.setdefault(k, []).append(x)
410
+ else:
411
+ aside.setdefault(k, []).append(x)
412
+ reasons.setdefault(k, []).append(why)
413
+ report: list[dict] = [{
414
+ "second": int(_sod_to_hhmmss([k])[0]), "class": "out-of-range",
415
+ "candidates": vals, "prev": None, "next": None, "prev_missing": False,
416
+ "next_missing": False, "kept": None, "remaining": k in groups,
417
+ "fallback": None if k in groups else float(policy.default_mps),
418
+ "reasons": list(dict.fromkeys(reasons[k])),
419
+ } for k, vals in sorted(aside.items())]
420
+
421
+ def known(k):
422
+ vals = groups.get(k)
423
+ if vals is None or len(set(vals)) != 1:
424
+ return None
425
+ return vals[0]
426
+
427
+ out: dict[int, float] = {k: float(policy.default_mps) for k in aside if k not in groups}
428
+ seconds = sorted(groups)
429
+ for i, k in enumerate(seconds):
430
+ cands = groups[k]
431
+ if len(cands) == 1:
432
+ out[k] = cands[0]
433
+ continue
434
+ if neighbour == "adjacent":
435
+ prev, nxt = known(k - 1), known(k + 1)
436
+ else:
437
+ prev = known(seconds[i - 1]) if i > 0 else None
438
+ nxt = known(seconds[i + 1]) if i + 1 < len(seconds) else None
439
+ distinct = list(dict.fromkeys(cands))
440
+ kept: float | None
441
+ if len(distinct) == 1:
442
+ cls, kept = "identical", distinct[0]
443
+ else:
444
+ matching = [c for c in distinct if c == prev or c == nxt]
445
+ if len(matching) == 1:
446
+ cls, kept = "unambiguous", matching[0]
447
+ else:
448
+ cls, kept = "ambiguous", None
449
+ fallback = (float(policy.default_mps)
450
+ if kept is None and unsettled == "default" else None)
451
+ report.append({
452
+ "second": int(_sod_to_hhmmss([k])[0]),
453
+ "class": cls, "candidates": cands, "prev": prev, "next": nxt,
454
+ "prev_missing": (k - 1) not in groups, "next_missing": (k + 1) not in groups,
455
+ "kept": kept, "fallback": fallback,
456
+ "reasons": ["unsettled-duplicate"] if kept is None else [],
457
+ })
458
+ if kept is not None:
459
+ out[k] = kept
460
+ elif fallback is not None:
461
+ out[k] = fallback
462
+ ks = sorted(out)
463
+ return (_sod_to_hhmmss(np.array(ks, dtype=np.int64)),
464
+ np.array([out[k] for k in ks], dtype=np.float64), report)
465
+
466
+
467
+ @dataclass
468
+ class ProbeReduction:
469
+ """What :func:`reduce_probe_csv` produced: the series, the log lines it printed, the
470
+ provenance attributes for the file, and -- under ``unsettled="refuse"`` -- the seconds that
471
+ stopped it (non-empty means: write nothing)."""
472
+
473
+ time: np.ndarray
474
+ tas: np.ndarray
475
+ lines: list
476
+ provenance: dict
477
+ refused: list
478
+ substituted: list # (HHMMSS, reason) per second that took the default
479
+
480
+
481
+ def reduce_probe_csv(csv_path, *, policy: TasPolicy | None = None,
482
+ second_rule: str = AUTHOR_SECOND_RULE,
483
+ neighbour: str = AUTHOR_NEIGHBOUR_RULE,
484
+ unsettled: str = AUTHOR_UNSETTLED_RULE) -> ProbeReduction:
485
+ """The probe path end to end: ``<stem>.tas.csv`` -> whole seconds under the TAS rules,
486
+ one log line per decision. Shared by ``make-tas-file --from-tas-csv`` and the run driver's
487
+ TAS source chain (:mod:`arrayprobe.tools.tas_sources`), so the two cannot disagree."""
488
+ policy = policy or TasPolicy()
489
+ raw_t, raw_v = tas_from_csv(csv_path)
490
+ time_hhmmss, tas, report = whole_second_series(
491
+ raw_t, raw_v, second_rule=second_rule, neighbour=neighbour, policy=policy,
492
+ unsettled=unsettled)
493
+ lines = [f"TAS reduction: --second-rule {second_rule} --neighbour "
494
+ f"{neighbour} --on-unsettled {unsettled}; rows above {policy.cutoff_mps:g} m/s, "
495
+ f"at/below {TAS_NONPOSITIVE_MPS:g} m/s or non-finite are set aside, and a second "
496
+ f"left without a usable row takes {policy.default_mps:g} m/s (never dropped)"]
497
+ substituted: list[tuple[int, str]] = []
498
+ oor = [r for r in report if r["class"] == "out-of-range"]
499
+ for r in oor:
500
+ if r["remaining"]:
501
+ lines.append(f"TAS out-of-range row(s) set aside: {r['second']:06d} "
502
+ f"{len(r['candidates'])} row(s) {'/'.join(r['reasons'])} (e.g. "
503
+ f"{r['candidates'][0]}); other rows keep this second")
504
+ else:
505
+ substituted.append((r["second"], "/".join(r["reasons"])))
506
+ lines.append(f"TAS substituted: {r['second']:06d} {r['candidates'][0]} -> "
507
+ f"{policy.default_mps:g} m/s ({'/'.join(r['reasons'])}, "
508
+ f"{len(r['candidates'])} row(s))")
509
+ dup = [r for r in report if r["class"] != "out-of-range"]
510
+ ambiguous = [r for r in dup if r["class"] == "ambiguous"]
511
+ refused: list[dict] = []
512
+ for r in ambiguous:
513
+ if r["fallback"] is not None:
514
+ substituted.append((r["second"], "unsettled-duplicate"))
515
+ lines.append(f"TAS substituted: {r['second']:06d} candidates="
516
+ f"{r['candidates']} prev={r['prev']} next={r['next']} -> "
517
+ f"{policy.default_mps:g} m/s (unsettled-duplicate: the duplicate rule "
518
+ "picks no candidate)")
519
+ else:
520
+ refused.append(r)
521
+ gap = [side for side, miss in (("previous", r["prev_missing"]),
522
+ ("next", r["next_missing"])) if miss]
523
+ lines.append(f"TAS duplicate UNRESOLVED: {r['second']:06d} "
524
+ f"candidates={r['candidates']} prev={r['prev']} next={r['next']} "
525
+ f"missing adjacent second: {', '.join(gap) or 'none'}")
526
+ resolved = [r for r in dup if r["class"] != "ambiguous"]
527
+ for r in resolved:
528
+ lines.append(f"TAS duplicate resolved: {r['second']:06d} class={r['class']} "
529
+ f"kept={r['kept']} candidates={r['candidates']} prev={r['prev']} "
530
+ f"next={r['next']}")
531
+ n_id = sum(r["class"] == "identical" for r in resolved)
532
+ substituted.sort()
533
+ lines.append(f"TAS duplicates resolved: {len(resolved)} second(s) ({n_id} "
534
+ f"identical, {len(resolved) - n_id} unambiguous); {len(substituted)} second(s) "
535
+ f"took the default {policy.default_mps:g} m/s; {raw_t.size} rows -> "
536
+ f"{time_hhmmss.size} whole seconds")
537
+ provenance = {
538
+ "tas_source": f"{csv_path} (measured)",
539
+ "tas_second_rule": second_rule,
540
+ "tas_neighbour_rule": neighbour,
541
+ "tas_duplicate_rule": TAS_DUPLICATE_RULE,
542
+ "tas_duplicates_resolved": np.int32(len(resolved)),
543
+ "tas_duplicates_resolved_seconds": ",".join(f"{r['second']:06d}" for r in resolved),
544
+ "tas_unsettled_rule": (
545
+ f"{unsettled} (rule: a duplicated second the duplicate rule cannot settle "
546
+ "takes tas_default_mps)"),
547
+ **policy.attributes(),
548
+ "tas_substituted_count": np.int32(len(substituted)),
549
+ "tas_substituted_seconds": ",".join(f"{s:06d}:{why}" for s, why in substituted),
550
+ "tas_out_of_range_rows": np.int32(sum(len(r["candidates"]) for r in oor)),
551
+ }
552
+ return ProbeReduction(time_hhmmss, tas, lines, provenance, refused, substituted)
553
+
554
+
555
+ def constant_tas(start_hhmmss: float, seconds: int,
556
+ tas_mps: float) -> tuple[np.ndarray, np.ndarray]:
557
+ """A flat 1-Hz series. ``Time`` steps by 1 in HHMMSS, which is only valid inside one
558
+ minute -- so the tool refuses a span that would run past :59 rather than writing a
559
+ time axis that jumps backwards at the minute boundary."""
560
+ if seconds < 1:
561
+ raise ValueError("--seconds must be at least 1")
562
+ ss = int(round(start_hhmmss)) % 100
563
+ if ss + seconds > 60:
564
+ raise ValueError(
565
+ f"--start-hhmmss {start_hhmmss:.0f} plus --seconds {seconds} runs past "
566
+ f":{ss + seconds:02d}, and HHMMSS does not carry across a minute by adding 1. "
567
+ "Give a start earlier in the minute, a shorter span, or use --from-tas-csv")
568
+ t = float(start_hhmmss) + np.arange(seconds, dtype=np.float64)
569
+ return t, np.full(seconds, float(tas_mps), dtype=np.float64)
570
+
571
+
572
+ def build_parser() -> argparse.ArgumentParser:
573
+ """The tool's parser -- also the list ``arrayprobe make-tas-file`` must mirror
574
+ (``tests/test_make_tas_file.py`` compares the two option sets)."""
575
+ parser = argparse.ArgumentParser(
576
+ prog="arrayprobe make-tas-file",
577
+ description="Write the aircraft TAS file stock imgProc_sm.m reads as varargin{1}: "
578
+ "a netCDF file with 1-D `Time` (HHMMSS) and `TAS` (m/s). Required by "
579
+ "the v3.5 engine and by any profile with time_in_seconds_from_tas.")
580
+ parser.add_argument("path", help="output path, e.g. aircraft_160906.cdf")
581
+ src = parser.add_mutually_exclusive_group(required=True)
582
+ src.add_argument("--from-tas-csv", metavar="CSV",
583
+ help="the <stem>.tas.csv sidecar the decode already wrote; its first "
584
+ "two columns are timehhmmss and tas")
585
+ src.add_argument("--from-merge", metavar="NC",
586
+ help="a campaign merge file, e.g. ORACLES mrg1_P3_<yyyymmdd>_R*.nc "
587
+ "(True_Air_Speed on Start_UTC; units read from the file)")
588
+ src.add_argument("--from-aircraft", metavar="NC",
589
+ help="another registered aircraft file, e.g. ARM enaaafmergedF1.c1.*.nc "
590
+ "(true_airspeed on time + base_time) or a UIOPS TAS/Time file")
591
+ src.add_argument("--chain", choices=("auto", "merge", "aircraft", "probe"),
592
+ help="resolve the source through the TAS source chain (merge -> aircraft -> "
593
+ "probe): needs --date, and --search and/or --probe-csv")
594
+ src.add_argument("--constant-tas", type=float, metavar="MPS",
595
+ help="write a FLAT series at this speed instead of a measured one "
596
+ "(needs --start-hhmmss and --seconds)")
597
+ parser.add_argument("--date", default=None, metavar="YYYYMMDD",
598
+ help="--chain: the flight date that fills each source's file pattern")
599
+ parser.add_argument("--search", action="append", default=None, metavar="DIR",
600
+ help="--chain: a directory holding merge/aircraft files (repeatable)")
601
+ parser.add_argument("--probe-csv", default=None, metavar="CSV",
602
+ help="the decode's <stem>.tas.csv: the chain's probe tier, and the "
603
+ "clock an aircraft source must share a second with")
604
+ parser.add_argument("--start-hhmmss", type=float, default=None,
605
+ help="first sample's time as HHMMSS, e.g. 60638 for 06:06:38")
606
+ parser.add_argument("--seconds", type=int, default=None,
607
+ help="number of 1-Hz samples for --constant-tas")
608
+ parser.add_argument("--second-rule", choices=SECOND_RULES, default=AUTHOR_SECOND_RULE,
609
+ help="how a fractional HHMMSS becomes a whole second (--from-tas-csv); "
610
+ f"default {AUTHOR_SECOND_RULE!r}")
611
+ parser.add_argument("--neighbour", choices=NEIGHBOUR_RULES, default=AUTHOR_NEIGHBOUR_RULE,
612
+ help="what the duplicate rule compares a duplicate against: 'adjacent' = "
613
+ "the second just before/after; 'nearest-present' = the nearest "
614
+ f"second present; default {AUTHOR_NEIGHBOUR_RULE!r}")
615
+ parser.add_argument("--on-unsettled", choices=UNSETTLED_RULES, default=AUTHOR_UNSETTLED_RULE,
616
+ help="a duplicated second the duplicate rule cannot settle: 'default' "
617
+ "gives it --default-mps; 'refuse' writes nothing and "
618
+ f"lists them; default {AUTHOR_UNSETTLED_RULE!r}")
619
+ parser.add_argument("--cutoff-mps", type=float, default=DEFAULT_CUTOFF_MPS,
620
+ help="a TAS above this is out of range and takes --default-mps "
621
+ f"(default {DEFAULT_CUTOFF_MPS:g})")
622
+ parser.add_argument("--default-mps", type=float, default=DEFAULT_FALLBACK_MPS,
623
+ help="the value an out-of-range, non-positive or unsettled second "
624
+ f"takes (default {DEFAULT_FALLBACK_MPS:g}, imgProc_sm.m:365's)")
625
+ parser.add_argument("--soda2-pth", default=None, metavar="CSV",
626
+ help="also write the same series as a SODA-2 op.pth ASCII file "
627
+ "(<seconds of day>,<tas> per line)")
628
+ return parser
629
+
630
+
631
+ def main(argv=None) -> int:
632
+ """``arrayprobe make-tas-file`` -- write the aircraft TAS file the pipeline requires.
633
+
634
+ Measured sources (``--from-tas-csv``, ``--from-merge``, ``--from-aircraft``, ``--chain``)
635
+ are converted under the TAS rules and a :class:`TasPolicy`; ``--constant-tas``
636
+ fabricates a series and says so in the file's own provenance (``constant <v> m/s (NOT a
637
+ measurement)``). It refuses to guess a flight's clock or duration. Returns an exit code.
638
+ """
639
+ parser = build_parser()
640
+ args = parser.parse_args(argv)
641
+ try:
642
+ policy = TasPolicy(args.cutoff_mps, args.default_mps)
643
+ except ValueError as exc:
644
+ parser.error(str(exc))
645
+
646
+ # A flag the chosen source never reads is refused rather than ignored (cold-user walk,
647
+ # 2026-09-26): `--from-tas-csv x --start-hhmmss 120000 --seconds 99` and `--from-tas-csv x
648
+ # --date ... --search ...` each wrote the whole csv's series, exit 0, as if the extra
649
+ # flags had trimmed or checked it.
650
+ given = {"--start-hhmmss": args.start_hhmmss, "--seconds": args.seconds,
651
+ "--date": args.date, "--search": args.search, "--probe-csv": args.probe_csv}
652
+ unread: tuple[str, ...]
653
+ if args.constant_tas is not None:
654
+ unread = ("--date", "--search", "--probe-csv")
655
+ elif args.from_tas_csv is not None:
656
+ unread = tuple(given)
657
+ else:
658
+ unread = ("--start-hhmmss", "--seconds")
659
+ ignored = [flag for flag in unread if given[flag] not in (None, [], ())]
660
+ if ignored:
661
+ parser.error(f"{', '.join(ignored)} {'is' if len(ignored) == 1 else 'are'} not read "
662
+ f"with the source given; --start-hhmmss/--seconds belong to "
663
+ f"--constant-tas, --date/--search/--probe-csv to --chain (and "
664
+ f"--from-merge/--from-aircraft)")
665
+
666
+ provenance: dict = {}
667
+ if args.from_tas_csv is not None:
668
+ try:
669
+ red = reduce_probe_csv(args.from_tas_csv, policy=policy,
670
+ second_rule=args.second_rule, neighbour=args.neighbour,
671
+ unsettled=args.on_unsettled)
672
+ except ValueError as exc:
673
+ # A file that is not a decode's <stem>.tas.csv (wrong file, a raw file, a header
674
+ # row) fails inside load_tas_info's numeric parse, and a decode csv whose content
675
+ # cannot be reduced (whole_second_series) fails too, so the wording names
676
+ # neither cause; the exception text says which. Say which file and stop.
677
+ print(f"arrayprobe make-tas-file: {args.from_tas_csv} could not be read as a "
678
+ f"<stem>.tas.csv ({exc}). No file written: {args.path}", file=sys.stderr)
679
+ return 2
680
+ for line in red.lines:
681
+ print(line)
682
+ if red.refused:
683
+ print(f"a choice is needed: the rule picks no candidate here "
684
+ f"({len(red.refused)} second(s) under --second-rule {args.second_rule} "
685
+ f"--neighbour {args.neighbour}); --on-unsettled refuse was given. "
686
+ f"No file written: {args.path}")
687
+ return 1
688
+ time_hhmmss, tas, provenance = red.time, red.tas, red.provenance
689
+ source = f"{args.from_tas_csv} (measured)"
690
+ elif args.constant_tas is not None:
691
+ if args.start_hhmmss is None or args.seconds is None:
692
+ parser.error("--constant-tas needs --start-hhmmss and --seconds -- this tool "
693
+ "will not guess a flight's clock or duration")
694
+ if not args.constant_tas > 0:
695
+ # A zero or negative airspeed was written as given, and the pipeline's own policy
696
+ # then set every second aside for the 170 m/s default -- a different series from
697
+ # the one the file claims.
698
+ parser.error(f"--constant-tas must be a positive speed in m/s, got "
699
+ f"{args.constant_tas}")
700
+ if args.seconds < 1:
701
+ parser.error(f"--seconds must be at least 1, got {args.seconds}")
702
+ # The same clock bounds write_tas_file enforces (:290): HHMMSS, hours up to 47
703
+ # because UIOOPS's midnight crossing is unwrapped (240000, 240001, ...), not wrapped.
704
+ start = int(args.start_hhmmss)
705
+ hh, mm, ss = start // 10000, (start // 100) % 100, start % 100
706
+ if args.start_hhmmss < 0 or hh > 47 or mm >= 60 or ss >= 60:
707
+ parser.error(f"--start-hhmmss must be a clock time HHMMSS (hours 0-47 after a "
708
+ f"midnight crossing, minutes and seconds 0-59), got "
709
+ f"{args.start_hhmmss:.0f}")
710
+ try:
711
+ time_hhmmss, tas = constant_tas(args.start_hhmmss, args.seconds, args.constant_tas)
712
+ except ValueError as exc:
713
+ parser.error(str(exc))
714
+ source = f"constant {args.constant_tas} m/s (NOT a measurement)"
715
+ provenance = {"tas_source": source}
716
+ else:
717
+ from arrayprobe.tools import tas_sources
718
+
719
+ if args.chain is not None:
720
+ if args.date is None:
721
+ parser.error("--chain needs --date YYYYMMDD: the tool will not guess a "
722
+ "flight's date")
723
+ mode, explicit = args.chain, None
724
+ else:
725
+ mode = "merge" if args.from_merge is not None else "aircraft"
726
+ explicit = {mode: args.from_merge or args.from_aircraft}
727
+ try:
728
+ res = tas_sources.resolve_chain(
729
+ mode, yyyymmdd=args.date, search_dirs=args.search or (),
730
+ probe_csv=args.probe_csv, policy=policy, second_rule=args.second_rule,
731
+ neighbour=args.neighbour, explicit=explicit)
732
+ except ValueError as exc:
733
+ print(f"make-tas-file: {exc}. No file written: {args.path}")
734
+ return 1
735
+ for line in res.lines:
736
+ print(line)
737
+ time_hhmmss, tas, provenance = res.time, res.tas, res.provenance
738
+ source = f"{res.path} ({res.tier}:{res.source})"
739
+ try:
740
+ out = write_tas_file(args.path, time_hhmmss, tas, provenance=provenance)
741
+ except ValueError as exc:
742
+ print(f"arrayprobe make-tas-file: {exc}. No file written: {args.path}",
743
+ file=sys.stderr)
744
+ return 2
745
+ print(f"wrote {out} -- {time_hhmmss.size} samples, "
746
+ f"Time {time_hhmmss[0]:.0f}..{time_hhmmss[-1]:.0f} HHMMSS, "
747
+ f"TAS {tas.min():.1f}..{tas.max():.1f} m/s, from {source}")
748
+ if args.soda2_pth is not None:
749
+ from arrayprobe.tools import tas_sources
750
+
751
+ pth = tas_sources.write_soda2_pth_csv(args.soda2_pth, time_hhmmss, tas)
752
+ print(f"wrote {pth} -- the same series as a SODA-2 op.pth ASCII file; name it as "
753
+ "[soda2].pth")
754
+ print(f"next: name it in your run config as [run].tas_file = \"{out}\", "
755
+ "or pass --tas-file to the imgproc stage")
756
+ return 0
757
+
758
+
759
+ if __name__ == "__main__": # pragma: no cover
760
+ raise SystemExit(main())