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,275 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
"""Shared leaf: the imgProc_sm time-base constants and pure helpers both engines use.
|
|
3
|
+
|
|
4
|
+
Moved verbatim from ``arrayprobe.imgproc``;
|
|
5
|
+
that module re-imports them, so its names still resolve. Constants and pure
|
|
6
|
+
functions: no module state, no numba, nothing a worker pickles.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from arrayprobe_uiops import ncio
|
|
16
|
+
from arrayprobe_uiops.matlab_compat import bin2dec, dec2bin_concat, mint8, mint16
|
|
17
|
+
|
|
18
|
+
#: ``imgProc_sm.m:365`` / ``:763``. The true air speed assumed when none is
|
|
19
|
+
#: available, in m/s.
|
|
20
|
+
TAS_FALLBACK = 170.0
|
|
21
|
+
|
|
22
|
+
#: ``imgProc_sm.m:737`` / ``:752``. A particle-to-particle time difference below
|
|
23
|
+
#: this many seconds is read as the 32-bit clock having wrapped, not as time
|
|
24
|
+
#: running backwards.
|
|
25
|
+
ROLLBACK_SECONDS = -250.0
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class UnportedProbeType(NotImplementedError):
|
|
29
|
+
"""A probe whose framing and timing branch is out of the framing stage's scope."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _time_in_seconds_from_tas(part_time, ds, rec, tas, tas_time,
|
|
33
|
+
part_time_prev, time_in_seconds_prev):
|
|
34
|
+
"""``:724-778`` -- Joe Finlon's 2017-03-03 TAS-based accumulation."""
|
|
35
|
+
# :726. The image record's time in HHMMSS, used as the TAS lookup key.
|
|
36
|
+
temp_time = (float(rec["hour"]) * 10000 + float(rec["minute"]) * 100
|
|
37
|
+
+ float(rec["second"]))
|
|
38
|
+
tas2d = tas[tas_time == temp_time] # :727
|
|
39
|
+
|
|
40
|
+
if part_time_prev is None: # :761 -- first particle of the chunk
|
|
41
|
+
if tas2d.size == 0:
|
|
42
|
+
return part_time * (ds / 10 ** 3 / TAS_FALLBACK) # :763
|
|
43
|
+
return part_time * (ds / 10 ** 3 / _one(tas2d, temp_time)) # :765
|
|
44
|
+
|
|
45
|
+
# :730. MATLAB's `if isempty(tas2d) || isnan(tas2d)` requires every element
|
|
46
|
+
# to be NaN when tas2d has more than one, because `if` on a vector is `all`.
|
|
47
|
+
if tas2d.size == 0 or bool(np.all(np.isnan(tas2d))):
|
|
48
|
+
speed = TAS_FALLBACK
|
|
49
|
+
else:
|
|
50
|
+
speed = _one(tas2d, temp_time)
|
|
51
|
+
|
|
52
|
+
scale = ds / 10 ** 3 / speed
|
|
53
|
+
time_diff = (part_time - part_time_prev) * scale # :735 / :750
|
|
54
|
+
if time_diff >= ROLLBACK_SECONDS: # :737 / :752
|
|
55
|
+
return time_in_seconds_prev + time_diff
|
|
56
|
+
# :740 / :755 -- the 32-bit clock wrapped.
|
|
57
|
+
return time_in_seconds_prev + (2 ** 32 - 1 - part_time_prev + part_time) * scale
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _one(tas2d, temp_time):
|
|
61
|
+
"""A TAS lookup that matched more than once would be a vector in MATLAB.
|
|
62
|
+
|
|
63
|
+
``time_in_seconds(kk) = time_in_seconds_prev + timeDiff`` (:738) then assigns
|
|
64
|
+
a vector into a scalar slot, which MATLAB rejects outright. Raised here for
|
|
65
|
+
the same reason rather than silently taking the first match.
|
|
66
|
+
"""
|
|
67
|
+
if tas2d.size != 1:
|
|
68
|
+
raise ValueError(
|
|
69
|
+
f"imgProc_sm.m:727 matched {tas2d.size} TAS samples at time "
|
|
70
|
+
f"{temp_time:.0f}; MATLAB then fails at :738 assigning a "
|
|
71
|
+
"1x{n} vector into time_in_seconds(kk). The aircraft file must "
|
|
72
|
+
"carry one sample per HHMMSS second."
|
|
73
|
+
)
|
|
74
|
+
return float(tas2d[0])
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _pecan_pip_hour_offset(rec, hour):
|
|
78
|
+
"""``:664-695`` -- PECAN's PIP flew on local time for part of the campaign.
|
|
79
|
+
|
|
80
|
+
``handles.month``/``handles.day``/``handles.hour`` are the IMAGE
|
|
81
|
+
RECORD's own header fields (read once per record, unaffected by any
|
|
82
|
+
particle-level offset), matching :func:`_read_record_header`'s ``rec``.
|
|
83
|
+
Only the hour offset is ever non-zero in the source; minute/second
|
|
84
|
+
offsets are declared but always 0, so they are not reproduced as
|
|
85
|
+
separate no-op additions.
|
|
86
|
+
"""
|
|
87
|
+
month, day = int(rec["month"]), int(rec["day"])
|
|
88
|
+
if month == 6 and day == 17:
|
|
89
|
+
return hour - 12
|
|
90
|
+
if month == 6 and day == 20:
|
|
91
|
+
return hour - 12 if rec["hour"] < 6 else hour
|
|
92
|
+
if month == 7 and 6 <= day <= 13:
|
|
93
|
+
return hour - 12
|
|
94
|
+
return hour
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass(frozen=True)
|
|
98
|
+
class VariableSpec:
|
|
99
|
+
"""One ``netcdf.defVar`` call, with the attributes that follow it.
|
|
100
|
+
|
|
101
|
+
Source: one call in the ``netcdf.defVar`` block of ``imgProc_sm.m:241-448`` (UIOOPS v3.1.4).
|
|
102
|
+
|
|
103
|
+
Definition *order* is part of the contract, not presentation: MATLAB assigns
|
|
104
|
+
variable IDs in creation order and ``sizeDist`` reads some of them by ID.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
name: str
|
|
108
|
+
xtype: str
|
|
109
|
+
dims: tuple[str, ...]
|
|
110
|
+
units: str = ""
|
|
111
|
+
description: str = ""
|
|
112
|
+
attrs: tuple[tuple[str, str], ...] = field(default_factory=tuple)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _read_record_header(src, i):
|
|
116
|
+
"""``:206-212`` -- the seven per-record time fields, at 0-based ``i-1``."""
|
|
117
|
+
names = ("year", "month", "day", "hour", "minute", "second", "millisec")
|
|
118
|
+
return {
|
|
119
|
+
name: float(np.ravel(
|
|
120
|
+
ncio.get_var(src, ncio.inq_var_id(src, name), i - 1, 1)
|
|
121
|
+
)[0])
|
|
122
|
+
for name in names
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _particle_time_pms(acc, kk, data, header_loc, src, i, cfg, ind_matrix): # noqa: N803
|
|
127
|
+
"""``:580-587`` -- the probetype-0 (2DC/2DP) half of F9.
|
|
128
|
+
|
|
129
|
+
Validated against a hand-built synthetic oracle
|
|
130
|
+
(``octave_oracle/run_s7c_2dc_bank.py`` -> ``tests/data/s7c_2dc_octave_golden.nc``),
|
|
131
|
+
bit-exact on the first run.
|
|
132
|
+
|
|
133
|
+
``:582-585``. The 24-bit TAS-clock particle time lives at
|
|
134
|
+
``data(header_loc, 2:4)`` (MATLAB 1-based) -- the row immediately after
|
|
135
|
+
the boundary word, whose first byte the boundary-companion check
|
|
136
|
+
(``cfg.boundary_needs_time``) already required to equal ``boundarytime``.
|
|
137
|
+
``tas2d`` is this image RECORD's own ``tas`` field (read fresh per
|
|
138
|
+
particle, matching the source, which re-reads it inside the per-particle
|
|
139
|
+
loop even though every particle in a record shares the same value).
|
|
140
|
+
"""
|
|
141
|
+
h = header_loc - 1 # MATLAB 1-based row -> Python row index.
|
|
142
|
+
bin_convert = dec2bin_concat(data[h:h + 1, 1:4], 8) # :582
|
|
143
|
+
tas_clock = bin2dec(bin_convert) # :583
|
|
144
|
+
tas2d = float(np.ravel(
|
|
145
|
+
ncio.get_var(src, ncio.inq_var_id(src, "tas"), i - 1, 1)
|
|
146
|
+
)[0]) # :584
|
|
147
|
+
# :585. IEEE division, not Python's: a record whose ``tas`` is 0 gives Inf
|
|
148
|
+
# (NaN for a zero clock) in MATLAB, where a float ``/`` raised.
|
|
149
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
150
|
+
part_time = float(np.float64(tas_clock) / np.float64(tas2d) * cfg.ds / 1e3)
|
|
151
|
+
|
|
152
|
+
acc.int_arrival[kk] = part_time # :586
|
|
153
|
+
acc.time_in_seconds[kk] = part_time # :587
|
|
154
|
+
|
|
155
|
+
# :628-629. Only meaningful for kk>1; harmless to compute unconditionally
|
|
156
|
+
# since kk==1 never reads it (see _pms_time_accumulate).
|
|
157
|
+
with np.errstate(invalid="ignore"):
|
|
158
|
+
frac_time = (part_time - np.floor(part_time)) * 1000
|
|
159
|
+
_pms_time_accumulate(acc, kk, ind_matrix, part_time, frac_time, src, i)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _particle_time_fast2dc(acc, kk, data, header_loc, src, i, ind_matrix): # noqa: N803
|
|
163
|
+
"""``:588-599`` -- the probetype-3 (Fast2DC) half of F9.
|
|
164
|
+
|
|
165
|
+
**A real, previously-undocumented-by-this-project fact, found only by
|
|
166
|
+
running this and comparing against the oracle**: Fast2DC is NOT the
|
|
167
|
+
self-contained branch its own `:594-598` if/else suggests. The shared
|
|
168
|
+
``firstpart``/accumulate cascade at ``:601-652`` (see
|
|
169
|
+
:func:`_pms_time_accumulate`) applies to probetype 3 exactly as it does
|
|
170
|
+
to probetype 0 -- it lives OUTSIDE the ``if probetype==0 ...
|
|
171
|
+
elseif probetype==3`` sub-block, inside the OUTER
|
|
172
|
+
``if probetype==0||probetype==3`` one. So Fast2DC particles ALSO seed
|
|
173
|
+
from the record header's int8-typed ``hour``/``minute``/``second``
|
|
174
|
+
fields and are subject to the same saturating ``particle_time`` write
|
|
175
|
+
(A15) -- confirmed against a synthetic oracle
|
|
176
|
+
(``octave_oracle/run_s7e_f2dc_bank.py`` ->
|
|
177
|
+
``tests/data/s7e_f2dc_octave_golden.nc``), not assumed.
|
|
178
|
+
|
|
179
|
+
``:588-592``. The 40-bit free-running 12 MHz clock lives at
|
|
180
|
+
``data(header_loc-1, 4:8)`` (MATLAB 1-based) -- the SAME row as the
|
|
181
|
+
boundary word itself (Fast2DC has no separate boundary-companion row;
|
|
182
|
+
``cfg.boundary_needs_time`` is ``False``), not the row after it the way
|
|
183
|
+
probetype 0's does.
|
|
184
|
+
"""
|
|
185
|
+
h = header_loc - 2 # data(header_loc-1, ...) MATLAB 1-based -> Python row.
|
|
186
|
+
bin_convert = dec2bin_concat(data[h:h + 1, 3:8], 8) # :589-590
|
|
187
|
+
clock_count = bin2dec(bin_convert) # :591
|
|
188
|
+
part_time = clock_count / 12 / 1e6 # :591-592
|
|
189
|
+
|
|
190
|
+
acc.time_in_seconds[kk] = part_time # :593
|
|
191
|
+
if kk > 1: # :594-598
|
|
192
|
+
time_diff = part_time - acc.time_in_seconds[kk - 1]
|
|
193
|
+
acc.int_arrival[kk] = time_diff
|
|
194
|
+
frac_time = 1000 * (time_diff - np.floor(time_diff)) # :630-632
|
|
195
|
+
else:
|
|
196
|
+
acc.int_arrival[kk] = 0.0
|
|
197
|
+
frac_time = 0.0 # unused: kk==1 never reads it below.
|
|
198
|
+
|
|
199
|
+
_pms_time_accumulate(acc, kk, ind_matrix, part_time, frac_time, src, i)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _pms_time_accumulate(acc, kk, ind_matrix, part_time, frac_time, src, i):
|
|
203
|
+
"""``:601-652`` -- shared between probetype 0 and 3.
|
|
204
|
+
|
|
205
|
+
``part_time`` feeds ``part_sec``'s accumulation (``:636``) directly and
|
|
206
|
+
UNCONDITIONALLY in both cases, even though ``frac_time`` (used only when
|
|
207
|
+
``kk>1``) is computed differently per probetype by the two callers.
|
|
208
|
+
"""
|
|
209
|
+
acc.particle_sliceCount[kk] = float(ind_matrix.shape[0]) # :601
|
|
210
|
+
acc.particle_DOF[kk] = float(np.ravel(
|
|
211
|
+
ncio.get_var(src, ncio.inq_var_id(src, "wkday"), i - 1, 1)
|
|
212
|
+
)[0]) # :602
|
|
213
|
+
|
|
214
|
+
if kk == 1: # :604-625. `firstpart` and `kk==1` coincide -- both reset
|
|
215
|
+
# only at a record boundary, and firstpart is cleared the
|
|
216
|
+
# moment the first particle in a record reaches this branch.
|
|
217
|
+
acc.part_hour[kk] = float(np.ravel(
|
|
218
|
+
ncio.get_var(src, ncio.inq_var_id(src, "hour"), i - 1, 1))[0])
|
|
219
|
+
acc.part_min[kk] = float(np.ravel(
|
|
220
|
+
ncio.get_var(src, ncio.inq_var_id(src, "minute"), i - 1, 1))[0])
|
|
221
|
+
acc.part_sec[kk] = float(np.ravel(
|
|
222
|
+
ncio.get_var(src, ncio.inq_var_id(src, "second"), i - 1, 1))[0])
|
|
223
|
+
acc.part_mil[kk] = float(np.ravel(
|
|
224
|
+
ncio.get_var(src, ncio.inq_var_id(src, "millisec"), i - 1, 1))[0])
|
|
225
|
+
acc.part_micro[kk] = 0.0
|
|
226
|
+
else: # :627-638
|
|
227
|
+
# The seed above fixes the classes: part_hour/part_min/part_sec are
|
|
228
|
+
# int8 and part_mil int16, the header variables' own types (the same
|
|
229
|
+
# fact _particle_time_write rests on), while part_micro starts from a
|
|
230
|
+
# double 0. So each sum is rounded and saturated as it is stored: a
|
|
231
|
+
# tas of 0 makes part_time Inf, part_sec saturates at 127 and part_mil,
|
|
232
|
+
# fed NaN, becomes 0.
|
|
233
|
+
with np.errstate(invalid="ignore"):
|
|
234
|
+
acc.part_micro[kk] = (acc.part_micro[kk - 1]
|
|
235
|
+
+ (frac_time - np.floor(frac_time)) * 1000)
|
|
236
|
+
acc.part_mil[kk] = float(mint16(acc.part_mil[kk - 1] + np.floor(frac_time)))
|
|
237
|
+
acc.part_sec[kk] = float(mint8(acc.part_sec[kk - 1] + np.floor(part_time)))
|
|
238
|
+
acc.part_min[kk] = acc.part_min[kk - 1]
|
|
239
|
+
acc.part_hour[kk] = acc.part_hour[kk - 1]
|
|
240
|
+
|
|
241
|
+
_pms_carry(acc, kk)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _pms_carry(acc, kk):
|
|
245
|
+
"""``:641-652`` (v3.5 ``:922-933``) -- the carry fix-up, applied to the
|
|
246
|
+
WHOLE vector ``1..kk`` at every particle, in the integer classes above.
|
|
247
|
+
|
|
248
|
+
Each line is a masked whole-vector assignment, so a particle that one pass
|
|
249
|
+
leaves at 60 or more -- ``part_sec`` saturated at 127 comes out at 67 -- is
|
|
250
|
+
carried again by the next particle's pass. The masks are recomputed line by
|
|
251
|
+
line, in the source's order."""
|
|
252
|
+
micro = np.asarray(acc.part_micro[1:kk], dtype=np.float64).copy()
|
|
253
|
+
mil = np.asarray(acc.part_mil[1:kk], dtype=np.float64).copy()
|
|
254
|
+
sec = np.asarray(acc.part_sec[1:kk], dtype=np.float64).copy()
|
|
255
|
+
mnt = np.asarray(acc.part_min[1:kk], dtype=np.float64).copy()
|
|
256
|
+
hour = np.asarray(acc.part_hour[1:kk], dtype=np.float64).copy()
|
|
257
|
+
m = micro >= 1000 # :641-642
|
|
258
|
+
mil[m] = mint16(mil[m] + 1)
|
|
259
|
+
micro[m] = micro[m] - 1000
|
|
260
|
+
m = mil >= 1000 # :644-645
|
|
261
|
+
sec[m] = mint8(sec[m] + 1)
|
|
262
|
+
mil[m] = mint16(mil[m] - 1000)
|
|
263
|
+
m = sec >= 60 # :647-648
|
|
264
|
+
mnt[m] = mint8(mnt[m] + 1)
|
|
265
|
+
sec[m] = mint8(sec[m] - 60)
|
|
266
|
+
m = mnt >= 60 # :650-651
|
|
267
|
+
hour[m] = mint8(hour[m] + 1)
|
|
268
|
+
mnt[m] = mint8(mnt[m] - 60)
|
|
269
|
+
m = hour >= 24 # :652
|
|
270
|
+
hour[m] = mint8(hour[m] - 24)
|
|
271
|
+
acc.part_micro[1:kk] = micro
|
|
272
|
+
acc.part_mil[1:kk] = mil
|
|
273
|
+
acc.part_sec[1:kk] = sec
|
|
274
|
+
acc.part_min[1:kk] = mnt
|
|
275
|
+
acc.part_hour[1:kk] = hour
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
"""The robust bimodal inter-arrival-time fit -- IntArrAnalysis_time.m's core numeric routine.
|
|
3
|
+
|
|
4
|
+
``IntArrAnalysis_time.m:152-154`` fits a two-population exponential mixture to a
|
|
5
|
+
normalized inter-arrival-time histogram for each block of particles, using
|
|
6
|
+
MATLAB's ``nlinfit(..., statset('Robust', 'on', 'FunValCheck', 'off', 'MaxIter', 1000))``::
|
|
7
|
+
|
|
8
|
+
bimodalfit = @(tau, dt) (1-tau(3)).*(dt/tau(1)).*exp(-dt/tau(1)) + ...
|
|
9
|
+
(tau(3)).*(dt/tau(2)).*exp(-dt/tau(2));
|
|
10
|
+
tau_std = abs(nlinfit(binsCenter, h./sum(h)./width, bimodalfit, beta0, ...));
|
|
11
|
+
|
|
12
|
+
**This is the one routine in the port that structurally cannot be bit-exact against
|
|
13
|
+
MATLAB, and that is a documented conclusion, not an assumption** (a recorded port gap).
|
|
14
|
+
Neither of the port's
|
|
15
|
+
usual two validation layers reaches it:
|
|
16
|
+
|
|
17
|
+
* **Layer 1 (a real MATLAB-written reference)** does not exist for this routine on
|
|
18
|
+
this machine -- no archived ``*_intArrThreshold_*.cdf`` product is held, and
|
|
19
|
+
separately (a real finding, not this routine's own): the ORACLES 2D-S product of
|
|
20
|
+
record calls ``sizeDist`` with a *missing* threshold-file argument
|
|
21
|
+
(``2DS_intArrThreshold_MISSING.cdf``), so ``sizeDist.m:70`` falls back to
|
|
22
|
+
``iaThreshFile = 'NONE'`` and this routine's output was never actually consumed
|
|
23
|
+
by the archived product this port targets.
|
|
24
|
+
* **Layer 2 (the Octave differential oracle) fails silently, not loudly, which is
|
|
25
|
+
the trap worth recording.** Octave's ``optim-1.6.3`` package does ship
|
|
26
|
+
``nlinfit``/``statset`` (traced ``nlinfit.m``/``statget.m``: confirmed by running
|
|
27
|
+
it -- ``statset`` prints ``warning: unrecognized option: Robust`` and
|
|
28
|
+
``...FunValCheck`` and silently drops both, computing a plain *unweighted*
|
|
29
|
+
Levenberg-Marquardt fit instead of the bisquare-robust one MATLAB performs).
|
|
30
|
+
A routine that *runs under Octave with no error* is not evidence it runs the
|
|
31
|
+
*same algorithm* -- confirmed here by directly observing the warning, not
|
|
32
|
+
inferred from reading the wrapper source alone.
|
|
33
|
+
|
|
34
|
+
**So this module is Layer 3: a documented, standard algorithm, validated on its
|
|
35
|
+
own terms rather than against an oracle that cannot check it.** ``robust_nlinfit``
|
|
36
|
+
implements bisquare iteratively-reweighted least squares (IRLS) around
|
|
37
|
+
``scipy.optimize.least_squares(method='lm')`` -- the same well-known robust-
|
|
38
|
+
regression family MATLAB's own ``nlinfit(...,'Robust','on')`` belongs to (bisquare
|
|
39
|
+
weight function, tuning constant 4.685, MAD-based scale estimate), but without
|
|
40
|
+
MATLAB's own leverage-adjustment refinement to the residuals, which cannot be
|
|
41
|
+
confirmed without the proprietary source or a license. This is a real, deliberate
|
|
42
|
+
simplification, not an oversight -- see the module's own test file for how it is
|
|
43
|
+
validated instead:
|
|
44
|
+
|
|
45
|
+
* ``robust=False`` reproduces exactly the *unweighted* fit -- the one case with a
|
|
46
|
+
real oracle, since that is what Octave's own ``nlinfit`` silently computes even
|
|
47
|
+
when asked for ``'Robust','on'``. Validated bit-close (5+ significant figures)
|
|
48
|
+
against a real Octave run on a synthetic bimodal histogram
|
|
49
|
+
(``tests/test_intarr.py``, ``tests/data/s8_intarr_octave_golden.json``).
|
|
50
|
+
* A hand-built histogram with one deliberately corrupted bin demonstrates the
|
|
51
|
+
actual property this routine exists for: the unweighted fit is thrown badly off
|
|
52
|
+
(a nonsensical mixture fraction > 1 in one measured case) while the robust fit
|
|
53
|
+
stays close to the clean-data answer and assigns the corrupted bin exactly zero
|
|
54
|
+
weight -- the qualitative behavior the MATLAB source's own comment
|
|
55
|
+
("bimodal fit still isn't achieved") exists to guard against, even though the
|
|
56
|
+
two implementations' precise numeric agreement can never be checked.
|
|
57
|
+
|
|
58
|
+
Provenance: ``IntArrAnalysis_time.m`` (the ORACLES production variant's file, not shipped --
|
|
59
|
+
NOT the stock tree's differently-named ``IntArrAnalysis.m``, which this port does
|
|
60
|
+
not target). This module ports only the fit itself, not the surrounding
|
|
61
|
+
histogram-population loop, threshold-selection logic, or the three plotting
|
|
62
|
+
routines in the source -- those are not yet ported.
|
|
63
|
+
"""
|
|
64
|
+
|
|
65
|
+
from __future__ import annotations
|
|
66
|
+
|
|
67
|
+
import numpy as np
|
|
68
|
+
|
|
69
|
+
# scipy is an *extra* (``arrayprobe[extra]``), so it is imported lazily inside
|
|
70
|
+
# the one function that needs it: importing ``arrayprobe`` must not require it.
|
|
71
|
+
|
|
72
|
+
__all__ = ["bimodal_model", "robust_nlinfit", "fit_bimodal_intarr"]
|
|
73
|
+
|
|
74
|
+
_BISQUARE_TUNE = 4.685
|
|
75
|
+
_DEFAULT_BETA0 = (1e-2, 1e-6, 0.5)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def bimodal_model(tau, dt):
|
|
79
|
+
"""``IntArrAnalysis_time.m:132``'s ``bimodalfit`` -- a two-population exponential mixture.
|
|
80
|
+
|
|
81
|
+
``tau = (tau1, tau2, tau3)``: the two population time constants and the
|
|
82
|
+
mixture fraction of population 2.
|
|
83
|
+
"""
|
|
84
|
+
tau1, tau2, tau3 = tau
|
|
85
|
+
dt = np.asarray(dt, dtype=float)
|
|
86
|
+
return (1 - tau3) * (dt / tau1) * np.exp(-dt / tau1) + tau3 * (dt / tau2) * np.exp(-dt / tau2)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _lm_fit(model, x, y, beta0, weights=None):
|
|
90
|
+
if weights is None:
|
|
91
|
+
def resid(beta):
|
|
92
|
+
"""Unweighted residual vector, the first ``nlinfit`` pass."""
|
|
93
|
+
return y - model(beta, x)
|
|
94
|
+
else:
|
|
95
|
+
sqrt_w = np.sqrt(weights)
|
|
96
|
+
|
|
97
|
+
def resid(beta):
|
|
98
|
+
"""Residuals pre-multiplied by ``sqrt(w)``.
|
|
99
|
+
|
|
100
|
+
MATLAB's ``nlinfit`` takes weights and minimises ``sum(w * r^2)``;
|
|
101
|
+
``least_squares`` minimises ``sum(r^2)`` of whatever it is handed,
|
|
102
|
+
so the weight is folded into the residual as its square root. The
|
|
103
|
+
two objectives are then the same function, not merely similar.
|
|
104
|
+
"""
|
|
105
|
+
return sqrt_w * (y - model(beta, x))
|
|
106
|
+
|
|
107
|
+
from scipy.optimize import least_squares # extra dependency, see module header
|
|
108
|
+
|
|
109
|
+
result = least_squares(resid, beta0, method="lm", max_nfev=1000 * (len(beta0) + 1))
|
|
110
|
+
return result.x
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _bisquare_weights(scaled_resid):
|
|
114
|
+
w = np.zeros_like(scaled_resid)
|
|
115
|
+
inside = np.abs(scaled_resid) < 1
|
|
116
|
+
w[inside] = (1 - scaled_resid[inside] ** 2) ** 2
|
|
117
|
+
return w
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def robust_nlinfit(x, y, model, beta0, *, robust=True, tune=_BISQUARE_TUNE,
|
|
121
|
+
max_iter=1000, tol=1e-8):
|
|
122
|
+
"""Bisquare-IRLS nonlinear least squares around ``scipy.optimize.least_squares``.
|
|
123
|
+
|
|
124
|
+
``robust=False`` is the ordinary unweighted Levenberg-Marquardt fit -- the
|
|
125
|
+
one case validated against a real Octave run, since Octave's own
|
|
126
|
+
``nlinfit(...,'Robust','on')`` silently computes exactly this (see the
|
|
127
|
+
module docstring). ``robust=True`` (the default, matching the MATLAB call
|
|
128
|
+
site) performs the iteratively-reweighted loop: fit, compute a MAD-based
|
|
129
|
+
robust scale of the residuals, compute bisquare weights from the scaled
|
|
130
|
+
residuals, refit weighted, repeat until the parameter vector stops moving
|
|
131
|
+
(or ``max_iter`` is reached -- MATLAB's own ``MaxIter`` cap, matched here).
|
|
132
|
+
"""
|
|
133
|
+
x = np.asarray(x, dtype=float)
|
|
134
|
+
y = np.asarray(y, dtype=float)
|
|
135
|
+
beta0 = np.asarray(beta0, dtype=float)
|
|
136
|
+
|
|
137
|
+
beta = _lm_fit(model, x, y, beta0)
|
|
138
|
+
if not robust:
|
|
139
|
+
return beta
|
|
140
|
+
|
|
141
|
+
for _ in range(max_iter):
|
|
142
|
+
resid = y - model(beta, x)
|
|
143
|
+
scale = np.median(np.abs(resid)) / 0.6745
|
|
144
|
+
if scale == 0 or not np.isfinite(scale):
|
|
145
|
+
break # residuals already (near) zero -- nothing left to reweight
|
|
146
|
+
weights = _bisquare_weights(resid / (tune * scale))
|
|
147
|
+
beta_new = _lm_fit(model, x, y, beta, weights)
|
|
148
|
+
if np.allclose(beta_new, beta, rtol=tol, atol=tol):
|
|
149
|
+
beta = beta_new
|
|
150
|
+
break
|
|
151
|
+
beta = beta_new
|
|
152
|
+
return beta
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def fit_bimodal_intarr(bins_center, hist_counts, width, beta0=_DEFAULT_BETA0):
|
|
156
|
+
"""``IntArrAnalysis_time.m:152-154`` -- the per-population bimodal robust fit.
|
|
157
|
+
|
|
158
|
+
``hist_counts`` is the raw histogram count array (``h`` in the source);
|
|
159
|
+
normalized to a density (``h/sum(h)/width``) before fitting, exactly as the
|
|
160
|
+
source does. Returns ``abs(tau)`` -- the source's own ``abs(nlinfit(...))``,
|
|
161
|
+
preserved verbatim: a fit that converges to a negative time constant is
|
|
162
|
+
sign-flipped, not rejected, matching MATLAB bug-for-bug.
|
|
163
|
+
"""
|
|
164
|
+
h = np.asarray(hist_counts, dtype=float)
|
|
165
|
+
y = h / h.sum() / width
|
|
166
|
+
beta = robust_nlinfit(bins_center, y, bimodal_model, beta0, robust=True, max_iter=1000)
|
|
167
|
+
return np.abs(beta)
|