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,626 @@
|
|
|
1
|
+
# SPDX-License-Identifier: BSD-3-Clause
|
|
2
|
+
# Reproduces SODA-2, Copyright (c) 2016 UCAR; see LICENSES/BSD-3-Clause.txt and NOTICE.md.
|
|
3
|
+
"""``soda2_process_2d.pro:449-573``'s buffer loop, split across processes.
|
|
4
|
+
|
|
5
|
+
**Not part of the port's reproduction.** SODA-2's IDL has no parallelism; this
|
|
6
|
+
module changes no computed number and exists only to make a flight fit in a
|
|
7
|
+
night. It is the SODA-2 half of the CIP end-to-end run and sits in the port rather than in
|
|
8
|
+
``enhancements_soda2/`` because *"speed work
|
|
9
|
+
is the one category that lives in BOTH spaces"*: it moves no written byte, is
|
|
10
|
+
opt-in, defaults to serial, and adds no dependency (``concurrent.futures`` and
|
|
11
|
+
``multiprocessing`` are stdlib).
|
|
12
|
+
|
|
13
|
+
Why the loop splits at all, and what had to be established first
|
|
14
|
+
----------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
The loop walks buffers. Splitting it needs to know, for each thing the body
|
|
17
|
+
touches, whether it is a function of that buffer alone. Read off
|
|
18
|
+
``process_2d.py``'s loop and the two buffer processors (CIP-1's
|
|
19
|
+
``processbuffer_cip.py``; ``processbuffer_spec.py``), **buffer-local**:
|
|
20
|
+
|
|
21
|
+
* ``buffpoint[i]`` addresses the buffer directly, so ``f.seek`` + ``read2dbuffer``
|
|
22
|
+
needs no predecessor -- the property the whole split rests on, the same one
|
|
23
|
+
``readers/spec.read_binary_SPEC_parallel`` rests on for UIOOPS S2.
|
|
24
|
+
* ``bufftime[i]`` / ``timeindex`` / ``pth_tas[timeindex]``, and the SPEC
|
|
25
|
+
``nimages``/``imagepointers``/``hkpointers``/``probetas`` lookups, are all
|
|
26
|
+
reads of arrays computed before the loop.
|
|
27
|
+
* ``process_buffer_tail`` -- the image processing, **97.3 % of the loop** --
|
|
28
|
+
is a pure function of its own buffer, once ``lastdhist`` is dead (below).
|
|
29
|
+
|
|
30
|
+
**Not** buffer-local, and how each is handled:
|
|
31
|
+
|
|
32
|
+
1. ``misc``: ``lastclock``/``lastbufftime``/``maxsfm`` (SPEC,
|
|
33
|
+
``processbuffer_spec.py:321``, ``:363-364``) and
|
|
34
|
+
``lastclock``/``lastparticlecount`` (CIP, ``processbuffer_cip.py:166``,
|
|
35
|
+
``:170``). A genuine sequential chain -- and the whole of it lives in
|
|
36
|
+
``_front_half``. Its share of the loop depends on the probe: **2.7 %** on
|
|
37
|
+
CIP (measured: read 3.63 ms, front 10.70 ms, tail 518.29 ms per buffer, 60
|
|
38
|
+
real UND 2016-09-06 CIP buffers), and about 15 % of the split loop on a
|
|
39
|
+
1 GB 2D-S file (sweep 4,384.2 s of 29,940.4 s, derived from
|
|
40
|
+
the 2D-S SODA-2 replay launch log, 2026-09-25). So
|
|
41
|
+
:func:`_iter_carry_in` runs that half **serially, in the parent**, for every
|
|
42
|
+
buffer, and yields ``misc`` at each chunk's first buffer; each chunk goes
|
|
43
|
+
to a worker as soon as its state exists, so the pool computes while the
|
|
44
|
+
sweep continues. Each worker starts from the recorded state. The sweep and
|
|
45
|
+
the workers call the same ``_front_half`` in the same order with the same
|
|
46
|
+
inputs, and nothing in the tail feeds back into ``misc``.
|
|
47
|
+
2. ``lastdhist`` (``dhist[timeindex-1]``, trap S6-c) is read by
|
|
48
|
+
``process_buffer_tail`` **only under ``op.stuckbits``**
|
|
49
|
+
(``processbuffer_tail.py:195-196``); it would otherwise couple a buffer's
|
|
50
|
+
image processing to every earlier buffer's output. ``stuckbits`` is
|
|
51
|
+
therefore **refused** with ``jobs > 1``, by name. Not worked around.
|
|
52
|
+
3. ``dhist``, ``numbuffsaccepted``, ``numbuffsrejected`` accumulate. Not
|
|
53
|
+
merged here by any new arithmetic: the workers report each buffer's own
|
|
54
|
+
``p.dhist`` and accept/reject, and ``run_parallel_loop`` replays the
|
|
55
|
+
driver's own ``+=`` lines in buffer order.
|
|
56
|
+
4. ``istop``/``istart``/``pbpstartindex``/``ncdf_offset`` and the
|
|
57
|
+
10,000,000-particle flush (`:565-573`, trap S6-d) are a sequential counter.
|
|
58
|
+
Same answer: replayed in buffer order from the per-buffer particle counts,
|
|
59
|
+
so the flush lands on exactly the buffer it lands on serially.
|
|
60
|
+
5. The accumulator ``d`` and the PBP writers are reached **only** through the
|
|
61
|
+
driver's own ``_flush``, which this module calls and does not reimplement.
|
|
62
|
+
So ``soda2_particlesort`` sees one ordered array per flush, the same one it
|
|
63
|
+
sees serially.
|
|
64
|
+
|
|
65
|
+
What a worker sends back is therefore per-buffer facts plus the particle
|
|
66
|
+
columns built by the driver's own ``_append_particle``; the parent does all the
|
|
67
|
+
arithmetic. Byte-identity is asserted on a real CIP fixture by
|
|
68
|
+
``tests/test_soda2_parallel.py`` -- a claim is a test.
|
|
69
|
+
|
|
70
|
+
**One thing this is NOT.** ``_front_half``/``_tail_half`` are a second written
|
|
71
|
+
form of the serial loop's `:449-470`, not the form the serial loop runs: the
|
|
72
|
+
serial loop calls the composed ``soda2_processbuffer`` as a module global
|
|
73
|
+
because that is a substitution surface. So a correction applied in the parent
|
|
74
|
+
process -- a SODA-2 enhancement through ``enhancement_hooks.overridden``, or
|
|
75
|
+
the 2016 UND emulation's recompile-and-rebind -- reaches the serial path and
|
|
76
|
+
does not reach a ``spawn``-started worker by itself. An earlier draft had the
|
|
77
|
+
serial loop call the halves directly; the suite showed it bypassed every
|
|
78
|
+
correction and the emulation, and it was reverted.
|
|
79
|
+
|
|
80
|
+
**Corrections are carried into the workers instead of being refused.**
|
|
81
|
+
The author's ruling is that the default is the corrected engine at its fastest
|
|
82
|
+
settings, so *fast* and *corrected* cannot be a choice. A substitution that is
|
|
83
|
+
installed with an ``enhancement_hooks.Reconstruction`` -- a factory name and a
|
|
84
|
+
picklable payload, which is what
|
|
85
|
+
``arrayprobe_soda2_enhancements.registry.apply`` installs -- is rebuilt inside
|
|
86
|
+
each worker by :func:`_init_worker` before any chunk runs, so the sweep in the
|
|
87
|
+
parent and the tails in the workers call the same callables. Each worker reports
|
|
88
|
+
what it substituted (``_ChunkResult.hooks``) and
|
|
89
|
+
:func:`run_parallel_loop` refuses a chunk whose worker disagrees with the
|
|
90
|
+
parent, because byte-identity alone would not notice corrections that failed to
|
|
91
|
+
install. :func:`refuse_unsplittable` still refuses what cannot be rebuilt by
|
|
92
|
+
name: an ad-hoc callable installed with no plan, and a rebound driver call.
|
|
93
|
+
``tests/test_soda2_parallel_enhancements.py`` is the proof, corrections on.
|
|
94
|
+
|
|
95
|
+
One resource difference, stated because it is real: serial flushes at
|
|
96
|
+
``num2process`` particles and frees ``x``; here a finished chunk's columns are
|
|
97
|
+
held until the replay reaches them, and chunks that finish ahead of the one
|
|
98
|
+
being replayed wait in memory, so peak memory is higher for a run that would
|
|
99
|
+
flush. The
|
|
100
|
+
columns are typed arrays rather than the serial path's Python lists, which
|
|
101
|
+
more than pays for it below the flush threshold (~176 B/particle against
|
|
102
|
+
~1.3 kB), and above it the run is >= 10,000,000 particles either way.
|
|
103
|
+
"""
|
|
104
|
+
from __future__ import annotations
|
|
105
|
+
|
|
106
|
+
import logging
|
|
107
|
+
import multiprocessing
|
|
108
|
+
import time
|
|
109
|
+
from collections.abc import Callable, Iterator, Mapping, Sequence
|
|
110
|
+
from concurrent.futures import ProcessPoolExecutor
|
|
111
|
+
from dataclasses import dataclass, replace
|
|
112
|
+
from typing import TYPE_CHECKING, Any
|
|
113
|
+
|
|
114
|
+
import numpy as np
|
|
115
|
+
|
|
116
|
+
from .processbuffer_cip import CipMisc
|
|
117
|
+
from .processbuffer_spec import NullBuffer, SpecMisc
|
|
118
|
+
|
|
119
|
+
if TYPE_CHECKING: # pragma: no cover - typing only
|
|
120
|
+
from .particlesort import Accumulator, ParticlesortOptions
|
|
121
|
+
from .process_2d import _LoopContext
|
|
122
|
+
|
|
123
|
+
__all__ = ["Soda2ParallelRefused", "chunk_bounds", "refuse_unsplittable",
|
|
124
|
+
"run_parallel_loop"]
|
|
125
|
+
|
|
126
|
+
_log = logging.getLogger("arrayprobe_soda2.process_2d.progress")
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class Soda2ParallelRefused(NotImplementedError):
|
|
130
|
+
"""``jobs > 1`` asked for on a run whose loop this module cannot split
|
|
131
|
+
exactly. Never downgraded to a warning: the alternative to refusing is a
|
|
132
|
+
number that is wrong in a way nothing would catch."""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass
|
|
136
|
+
class _ChunkResult:
|
|
137
|
+
"""One contiguous buffer range's output, as its worker reports it.
|
|
138
|
+
|
|
139
|
+
Per-buffer arrays are in buffer order, one entry per buffer in ``[lo, hi)``.
|
|
140
|
+
``x`` holds the particles of the accepted buffers, concatenated in the same
|
|
141
|
+
order the serial loop appends them."""
|
|
142
|
+
|
|
143
|
+
lo: int
|
|
144
|
+
hi: int
|
|
145
|
+
x: dict[str, np.ndarray]
|
|
146
|
+
counts: np.ndarray # particles contributed by each buffer (0 if not accepted)
|
|
147
|
+
accepted: np.ndarray # bool: neither a NullBuffer nor rejectbuffer != 0
|
|
148
|
+
is_null: np.ndarray # bool: the front half returned a NullBuffer
|
|
149
|
+
timeindex: np.ndarray # int64
|
|
150
|
+
dhist: np.ndarray # (nbuffers, numdiodes) int16, zero rows where is_null
|
|
151
|
+
#: `enhancement_hooks.active()` AS THE WORKER SAW IT while this chunk ran
|
|
152
|
+
#: Reported rather than assumed, so `run_parallel_loop` can refuse
|
|
153
|
+
#: a result computed by a worker whose corrections failed to install --
|
|
154
|
+
#: byte-identity alone would not catch that, and the SODA-2 lane has already
|
|
155
|
+
#: been bitten once by output that matched with every correction bypassed.
|
|
156
|
+
hooks: dict[str, str]
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def chunk_bounds(firstbuff: int, lastbuff: int, nchunks: int) -> list[tuple[int, int]]:
|
|
160
|
+
"""Split ``[firstbuff, lastbuff]`` (inclusive, the driver's own range) into
|
|
161
|
+
at most ``nchunks`` contiguous half-open ranges, none empty.
|
|
162
|
+
|
|
163
|
+
Contiguous and in order, so an ordered concatenation of the chunks is the
|
|
164
|
+
serial sequence -- the same partition property
|
|
165
|
+
a range-iteration test pins for the UIOOPS decode.
|
|
166
|
+
"""
|
|
167
|
+
n = lastbuff + 1 - firstbuff
|
|
168
|
+
if n <= 0:
|
|
169
|
+
return []
|
|
170
|
+
k = max(1, min(int(nchunks), n))
|
|
171
|
+
edges = [firstbuff + (n * j) // k for j in range(k + 1)]
|
|
172
|
+
return [(a, b) for a, b in zip(edges[:-1], edges[1:], strict=True) if b > a]
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _misc_state(misc: SpecMisc | CipMisc) -> dict[str, float | int]:
|
|
176
|
+
"""The carry-in chain, and nothing else: the ``(*pmisc)`` fields a buffer
|
|
177
|
+
processor *reads from its predecessor*. Everything else on ``misc``
|
|
178
|
+
(``nimages``, the pointer arrays, ``probetas``, ``aircrafttas``) is
|
|
179
|
+
rewritten from the index by ``_front_half`` before it is read, so it is
|
|
180
|
+
not state and is deliberately not carried."""
|
|
181
|
+
if isinstance(misc, CipMisc):
|
|
182
|
+
return {"lastclock": float(misc.lastclock),
|
|
183
|
+
"lastparticlecount": int(misc.lastparticlecount)}
|
|
184
|
+
return {"lastclock": float(misc.lastclock),
|
|
185
|
+
"lastbufftime": float(misc.lastbufftime),
|
|
186
|
+
"maxsfm": float(misc.maxsfm)}
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _misc_from_state(template: SpecMisc | CipMisc,
|
|
190
|
+
state: dict[str, float | int]) -> SpecMisc | CipMisc:
|
|
191
|
+
return replace(template, **state) # type: ignore[arg-type]
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _iter_carry_in(ctx: _LoopContext, bounds: list[tuple[int, int]],
|
|
195
|
+
misc: SpecMisc | CipMisc) -> Iterator[tuple[int, dict[str, float | int]]]:
|
|
196
|
+
"""The one part of the loop that cannot be split: walk every buffer's
|
|
197
|
+
``_front_half`` in order, in this process, and yield ``(j, misc state)`` as
|
|
198
|
+
the walk reaches chunk ``j``'s first buffer.
|
|
199
|
+
|
|
200
|
+
A generator, so :func:`run_parallel_loop` can hand chunk ``j`` to a worker
|
|
201
|
+
the moment its start state exists and keep walking while the workers
|
|
202
|
+
compute; the states are the same values either way. ``_front_half`` is the
|
|
203
|
+
serial loop's own, so the states are the ones the serial loop has at those
|
|
204
|
+
buffers, by construction rather than by argument.
|
|
205
|
+
"""
|
|
206
|
+
from .process_2d import _front_half
|
|
207
|
+
|
|
208
|
+
starts = {lo: j for j, (lo, _hi) in enumerate(bounds)}
|
|
209
|
+
lo0, hi_last = bounds[0][0], bounds[-1][1]
|
|
210
|
+
with open(ctx.fn_list[0], "rb") as f:
|
|
211
|
+
for i in range(lo0, hi_last):
|
|
212
|
+
if i in starts:
|
|
213
|
+
yield starts[i], _misc_state(misc)
|
|
214
|
+
_front_half(ctx, i, f, misc)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
#: Set once per worker process by :func:`_init_worker`; never mutated after.
|
|
218
|
+
_CTX: _LoopContext | None = None
|
|
219
|
+
_MISC_TEMPLATE: SpecMisc | CipMisc | None = None
|
|
220
|
+
#: The worker's own ``enhancement_hooks.overridden`` block, entered by
|
|
221
|
+
#: :func:`_init_worker` and held open for the process's life. Kept so the
|
|
222
|
+
#: substitution cannot be garbage-collected out from under the chunks, and so
|
|
223
|
+
#: :func:`worker_substitution` can report it.
|
|
224
|
+
_HOOKS: Any | None = None
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _init_worker(ctx: _LoopContext, misc_template: SpecMisc | CipMisc,
|
|
228
|
+
plan: Any = None) -> None:
|
|
229
|
+
"""One worker process's setup: the loop context, the ``misc`` template, and
|
|
230
|
+
-- the parent's enhancement substitution rebuilt from ``plan``.
|
|
231
|
+
|
|
232
|
+
``plan`` is an ``enhancement_hooks.Reconstruction`` (plain data: an
|
|
233
|
+
importable ``"module:callable"`` and a picklable payload) or ``None``. It is
|
|
234
|
+
rebuilt and installed **here**, before any chunk runs, so a worker's
|
|
235
|
+
``_front_half``/``_tail_half`` call exactly the callables the parent's
|
|
236
|
+
carry-in sweep called. The ``with`` block is entered and deliberately never
|
|
237
|
+
exited: the substitution is this process's whole life, and the process is
|
|
238
|
+
torn down by the pool.
|
|
239
|
+
|
|
240
|
+
A failure to rebuild raises here, which the pool surfaces on the first
|
|
241
|
+
``map`` result. That is the right direction: a worker that silently fell
|
|
242
|
+
back to the port's own functions would produce uncorrected numbers under a
|
|
243
|
+
run the user asked corrections for, which is the one outcome this module
|
|
244
|
+
exists to prevent.
|
|
245
|
+
"""
|
|
246
|
+
global _CTX, _MISC_TEMPLATE, _HOOKS
|
|
247
|
+
_CTX = ctx
|
|
248
|
+
_MISC_TEMPLATE = misc_template
|
|
249
|
+
if plan is not None:
|
|
250
|
+
import atexit
|
|
251
|
+
|
|
252
|
+
from . import enhancement_hooks
|
|
253
|
+
repl = plan.build()
|
|
254
|
+
cm = enhancement_hooks.overridden(repl, reconstruction=plan)
|
|
255
|
+
cm.__enter__()
|
|
256
|
+
_HOOKS = cm
|
|
257
|
+
# Closed at `atexit` rather than left to the interpreter's final garbage
|
|
258
|
+
# collection: an un-exited `@contextmanager` generator is finalised after
|
|
259
|
+
# `sys.meta_path` is gone, and `overridden`'s `finally` does an
|
|
260
|
+
# `importlib.import_module` -- which then raises "Python is likely
|
|
261
|
+
# shutting down" onto every worker's stderr. Harmless, but it would put
|
|
262
|
+
# a traceback in the log of every successful split run.
|
|
263
|
+
atexit.register(cm.__exit__, None, None, None)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def worker_substitution() -> dict[str, str]:
|
|
267
|
+
"""What this process has substituted -- ``enhancement_hooks.active()``.
|
|
268
|
+
|
|
269
|
+
A worker-side observation rather than an echo of the argument, so a test can
|
|
270
|
+
assert the corrections really are installed *in the worker* and not merely
|
|
271
|
+
that a plan was passed to it.
|
|
272
|
+
"""
|
|
273
|
+
from . import enhancement_hooks
|
|
274
|
+
return enhancement_hooks.active()
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _run_chunk(task: tuple[int, int, dict[str, float | int], int]) -> _ChunkResult:
|
|
278
|
+
"""One chunk, in a worker process: the driver's loop body minus the
|
|
279
|
+
bookkeeping, for buffers ``[lo, hi)``.
|
|
280
|
+
|
|
281
|
+
Calls ``_front_half`` and ``_tail_half`` -- a second written form of the
|
|
282
|
+
serial loop's `:449-470`, see the module docstring -- and appends particles
|
|
283
|
+
with ``_append_particle``, which IS the serial loop's own row builder, so
|
|
284
|
+
nothing about a particle's *value* depends on having come through here.
|
|
285
|
+
"""
|
|
286
|
+
from .process_2d import _X_KEYS, _append_particle, _front_half, _new_x, _tail_half, _x_to_arrays
|
|
287
|
+
|
|
288
|
+
lo, hi, misc_state, report_every = task
|
|
289
|
+
ctx, template = _CTX, _MISC_TEMPLATE
|
|
290
|
+
assert ctx is not None and template is not None, "worker initializer did not run"
|
|
291
|
+
misc = _misc_from_state(template, misc_state)
|
|
292
|
+
|
|
293
|
+
# Dead by refusal: `run_parallel_loop` rejects `stuckbits`, the only reader
|
|
294
|
+
# (`processbuffer_tail.py:195-196`). Shaped so the tail's own shape check
|
|
295
|
+
# (`:170-174`) sees what it sees serially.
|
|
296
|
+
lastdhist = np.zeros(ctx.numdiodes, dtype=np.int32)
|
|
297
|
+
|
|
298
|
+
x = _new_x()
|
|
299
|
+
n_buf = hi - lo
|
|
300
|
+
counts = np.zeros(n_buf, dtype=np.int64)
|
|
301
|
+
accepted = np.zeros(n_buf, dtype=bool)
|
|
302
|
+
is_null = np.zeros(n_buf, dtype=bool)
|
|
303
|
+
timeindex = np.zeros(n_buf, dtype=np.int64)
|
|
304
|
+
dhist = np.zeros((n_buf, ctx.numdiodes), dtype=np.int16)
|
|
305
|
+
|
|
306
|
+
started = time.monotonic()
|
|
307
|
+
with open(ctx.fn_list[0], "rb") as f:
|
|
308
|
+
for k, i in enumerate(range(lo, hi)):
|
|
309
|
+
front, b_time, ti, aircrafttas_i = _front_half(ctx, i, f, misc)
|
|
310
|
+
p = _tail_half(ctx, front, lastdhist)
|
|
311
|
+
timeindex[k] = ti
|
|
312
|
+
if isinstance(p, NullBuffer):
|
|
313
|
+
is_null[k] = True
|
|
314
|
+
else:
|
|
315
|
+
dhist[k, :] = p.dhist
|
|
316
|
+
if p.rejectbuffer == 0:
|
|
317
|
+
accepted[k] = True
|
|
318
|
+
n = int(p.diam.size)
|
|
319
|
+
counts[k] = n
|
|
320
|
+
for j in range(n):
|
|
321
|
+
_append_particle(x, p, b_time, aircrafttas_i, j)
|
|
322
|
+
if report_every > 0 and (k + 1) % report_every == 0:
|
|
323
|
+
print(f" ...chunk {lo}-{hi} buffer {k + 1}/{n_buf}, "
|
|
324
|
+
f"{time.monotonic() - started:.1f} s", flush=True)
|
|
325
|
+
|
|
326
|
+
arrays = _x_to_arrays(x)
|
|
327
|
+
return _ChunkResult(lo=lo, hi=hi, x={key: arrays[key] for key in _X_KEYS},
|
|
328
|
+
counts=counts, accepted=accepted, is_null=is_null,
|
|
329
|
+
timeindex=timeindex, dhist=dhist,
|
|
330
|
+
hooks=worker_substitution())
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def refuse_unsplittable(op: Mapping[str, Any], fn_list: Sequence[Any],
|
|
334
|
+
jobs: int) -> None:
|
|
335
|
+
"""Every configuration whose loop this module cannot split exactly, refused
|
|
336
|
+
by name and by the line that makes it so.
|
|
337
|
+
|
|
338
|
+
Called from ``soda2_process_2d`` **before anything is opened or read** --
|
|
339
|
+
beside the driver's other configuration refusals (`:478-520`) rather than
|
|
340
|
+
at the point of the split -- because a refusal raised later would leave the
|
|
341
|
+
PBP writers open behind it (the shape of SODA-2 register entry S6-f), and a configuration error
|
|
342
|
+
should cost no file.
|
|
343
|
+
"""
|
|
344
|
+
if int(op.get("stuckbits", 0)) != 0:
|
|
345
|
+
raise Soda2ParallelRefused(
|
|
346
|
+
"jobs > 1 with op.stuckbits set: `process_buffer_tail` then reads "
|
|
347
|
+
"`lastdhist = dhist[timeindex-1]` (processbuffer_tail.py:195-196), "
|
|
348
|
+
"which is every earlier buffer's output, so a buffer's image "
|
|
349
|
+
f"processing is not buffer-local. Run with jobs=1 (got jobs={jobs}).")
|
|
350
|
+
if len(fn_list) != 1:
|
|
351
|
+
raise Soda2ParallelRefused(
|
|
352
|
+
"jobs > 1 with more than one raw file: the split carries no "
|
|
353
|
+
"per-buffer file index or per-file pointer "
|
|
354
|
+
"(soda2_process_2d.pro:364-391), and SPEC stops at :376 anyway; "
|
|
355
|
+
f"run with jobs=1 (got {len(fn_list)} files).")
|
|
356
|
+
if int(op.get("activetimefrommissed", 0)) == 1:
|
|
357
|
+
raise Soda2ParallelRefused(
|
|
358
|
+
"jobs > 1 with op.activetimefrommissed: soda2_process_2d.pro:493 is "
|
|
359
|
+
"an IDL `stop` ('Under development'), raised serially per buffer; "
|
|
360
|
+
"run with jobs=1 to get that error where the IDL gives it.")
|
|
361
|
+
|
|
362
|
+
# A SODA-2 correction, or the 2016 UND emulation, is applied by replacing a
|
|
363
|
+
# module-global binding IN THIS PROCESS (`enhancement_hooks.overridden`,
|
|
364
|
+
# recompile-and-rebind). A `spawn`-started
|
|
365
|
+
# worker re-imports the package and inherits none of it -- so a split run
|
|
366
|
+
# whose workers did nothing about it would apply the substitution to the
|
|
367
|
+
# carry-in sweep, which happens in the parent, and NOT to the tails, which
|
|
368
|
+
# are 97 % of the work. Every number would then be some unnamed mixture.
|
|
369
|
+
#
|
|
370
|
+
# That was lifted for the case where the substitution can be REBUILT in the
|
|
371
|
+
# worker from plain data: `enhancement_hooks.reconstruction_plan()` is the
|
|
372
|
+
# installer's statement of how, `_init_worker` performs it, and
|
|
373
|
+
# `tests/test_soda2_parallel_enhancements.py` proves the split is then
|
|
374
|
+
# byte-identical to serial with the same corrections on. What stays refused
|
|
375
|
+
# is what still cannot be rebuilt by name: an ad-hoc callable passed through
|
|
376
|
+
# `overridden` with no plan, and a rebound driver call (the emulation's
|
|
377
|
+
# recompile-and-rebind, which replaces the composed `soda2_processbuffer`
|
|
378
|
+
# that the split does not call at all). Read from the port's own hook
|
|
379
|
+
# registry rather than a list typed here, so a hook point added later is
|
|
380
|
+
# covered without this function being edited.
|
|
381
|
+
from . import enhancement_hooks, process_2d
|
|
382
|
+
substituted = sorted(n for n, ok in enhancement_hooks.pristine().items() if not ok)
|
|
383
|
+
rebound = sorted(n for n, fn in process_2d._PRISTINE_CALLS.items()
|
|
384
|
+
if getattr(process_2d, n, None) is not fn)
|
|
385
|
+
if rebound:
|
|
386
|
+
raise Soda2ParallelRefused(
|
|
387
|
+
f"jobs > 1 with a rebound driver call {rebound}: it replaces the "
|
|
388
|
+
"composed `soda2_processbuffer`, which the split does not call -- it "
|
|
389
|
+
"calls `_front_half`/`_tail_half` -- so there is nothing for a worker "
|
|
390
|
+
"to honour and no way to rebuild it by name. Run with jobs=1.")
|
|
391
|
+
if substituted and enhancement_hooks.reconstruction_plan() is None:
|
|
392
|
+
raise Soda2ParallelRefused(
|
|
393
|
+
f"jobs > 1 with a live in-process substitution (hook points "
|
|
394
|
+
f"{substituted}) that carries no reconstruction plan: a spawn-started "
|
|
395
|
+
"worker re-imports the package and inherits no monkey-patch, so the "
|
|
396
|
+
"split would apply it to the serial carry-in pass and not to the "
|
|
397
|
+
"per-buffer tails. Install the substitution with "
|
|
398
|
+
"`enhancement_hooks.overridden(repl, reconstruction=...)` -- which is "
|
|
399
|
+
"what `arrayprobe_soda2_enhancements.registry.apply` does, so the "
|
|
400
|
+
"shipped corrections DO split -- or run with jobs=1. This "
|
|
401
|
+
"refusal is about the substitution and NOT about `jit`, which installs "
|
|
402
|
+
"nothing and is unaffected.")
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def run_parallel_loop(
|
|
406
|
+
ctx: _LoopContext,
|
|
407
|
+
firstbuff: int,
|
|
408
|
+
lastbuff: int,
|
|
409
|
+
misc: SpecMisc | CipMisc,
|
|
410
|
+
*,
|
|
411
|
+
jobs: int,
|
|
412
|
+
chunks: int = 0,
|
|
413
|
+
report_every: int = 0,
|
|
414
|
+
d: Accumulator,
|
|
415
|
+
dhist: np.ndarray,
|
|
416
|
+
numbuffsaccepted: np.ndarray,
|
|
417
|
+
numbuffsrejected: np.ndarray,
|
|
418
|
+
pbpstartindex: np.ndarray,
|
|
419
|
+
num2process: int,
|
|
420
|
+
psopts: ParticlesortOptions,
|
|
421
|
+
flush: Callable[..., int],
|
|
422
|
+
csv_f: Any,
|
|
423
|
+
ncdf_ds: Any,
|
|
424
|
+
) -> tuple[int, int, dict[str, np.ndarray]]:
|
|
425
|
+
"""Run `:449-573` across ``jobs`` processes and replay the driver's
|
|
426
|
+
bookkeeping over the result.
|
|
427
|
+
|
|
428
|
+
Mutates ``dhist``, ``numbuffsaccepted``, ``numbuffsrejected``,
|
|
429
|
+
``pbpstartindex`` and (through ``flush``) ``d`` and the PBP writers exactly
|
|
430
|
+
as the serial loop does, and returns the ``(istop, ncdf_offset, x)`` the
|
|
431
|
+
serial loop would be holding when it fell out -- so everything after the
|
|
432
|
+
loop in ``soda2_process_2d`` is reached in the same state.
|
|
433
|
+
"""
|
|
434
|
+
# Re-checked here as well as at the driver's top, so an in-tree caller that
|
|
435
|
+
# reaches this function directly cannot skip the refusals.
|
|
436
|
+
refuse_unsplittable(ctx.op, ctx.fn_list, jobs)
|
|
437
|
+
bounds = chunk_bounds(firstbuff, lastbuff, chunks if chunks > 0 else 4 * jobs)
|
|
438
|
+
if not bounds: # the caller's `(lastbuff - firstbuff) <= 0` already returned
|
|
439
|
+
return -1, 0, {}
|
|
440
|
+
|
|
441
|
+
# A copy, so the sweep leaves the caller's `misc` untouched and the workers'
|
|
442
|
+
# template is the driver's pristine initial state (`:39-41`).
|
|
443
|
+
template = replace(misc)
|
|
444
|
+
|
|
445
|
+
# What this parent has substituted, and how a worker rebuilds it. Read
|
|
446
|
+
# here rather than passed in, so the driver signature does not have to carry
|
|
447
|
+
# an enhancements concept the port does not own; `refuse_unsplittable` above
|
|
448
|
+
# has already established that a live substitution comes with a plan.
|
|
449
|
+
from . import enhancement_hooks
|
|
450
|
+
plan = enhancement_hooks.reconstruction_plan()
|
|
451
|
+
expected_hooks = enhancement_hooks.active()
|
|
452
|
+
|
|
453
|
+
# A worker's own liveness interval, in buffers. Not `report_every` (20,000
|
|
454
|
+
# buffers, the whole-run figure) -- a chunk is typically far smaller than
|
|
455
|
+
# that and would print nothing, leaving `--worker-stall-min`-class watchdogs
|
|
456
|
+
# and a human reading the log with a silent process. Pair J's lesson on the
|
|
457
|
+
# UIOOPS decode (`readers/spec._report_part_progress`), applied here.
|
|
458
|
+
worker_every = min(report_every, 100) if report_every > 0 else 0
|
|
459
|
+
replay = _Replayer(d=d, dhist=dhist, numbuffsaccepted=numbuffsaccepted,
|
|
460
|
+
numbuffsrejected=numbuffsrejected, pbpstartindex=pbpstartindex,
|
|
461
|
+
num2process=num2process, psopts=psopts, flush=flush,
|
|
462
|
+
csv_f=csv_f, ncdf_ds=ncdf_ds)
|
|
463
|
+
t0 = time.monotonic()
|
|
464
|
+
t_replay = 0.0
|
|
465
|
+
n_particles = 0
|
|
466
|
+
# ``spawn`` on every platform: a ``fork``-started worker (Linux's default)
|
|
467
|
+
# inherits the parent's already-installed enhancement hooks, and
|
|
468
|
+
# ``_init_worker`` then refuses to install them a second time. Windows
|
|
469
|
+
# and macOS spawn already; this makes Linux compute the same way.
|
|
470
|
+
with ProcessPoolExecutor(max_workers=jobs, initializer=_init_worker,
|
|
471
|
+
initargs=(ctx, template, plan),
|
|
472
|
+
mp_context=multiprocessing.get_context("spawn")) as pool:
|
|
473
|
+
# Chunk j is submitted the moment the sweep has recorded its start
|
|
474
|
+
# state, so the workers compute while the parent keeps sweeping. The
|
|
475
|
+
# states are the ones a finished sweep would have handed over.
|
|
476
|
+
futures: list[Any] = [
|
|
477
|
+
pool.submit(_run_chunk, (lo, hi, state, worker_every))
|
|
478
|
+
for (lo, hi), (_j, state)
|
|
479
|
+
in zip(bounds, _iter_carry_in(ctx, bounds, replace(misc)), strict=True)]
|
|
480
|
+
t_sweep = time.monotonic() - t0
|
|
481
|
+
if report_every > 0:
|
|
482
|
+
_log.info(" ...carry-in sweep: %d buffers in %.1f s; %d chunks over %d jobs",
|
|
483
|
+
bounds[-1][1] - bounds[0][0], t_sweep, len(bounds), jobs)
|
|
484
|
+
# Collected in submission order, which is buffer order, and replayed as
|
|
485
|
+
# each arrives -- the replay depends on that order and on nothing else
|
|
486
|
+
# about scheduling. A chunk that finishes early waits for its turn.
|
|
487
|
+
for j in range(len(futures)):
|
|
488
|
+
part = futures[j].result()
|
|
489
|
+
futures[j] = None # released once replayed
|
|
490
|
+
# The worker's own report of what it had substituted while it ran
|
|
491
|
+
# Not a formality: a worker whose corrections failed to
|
|
492
|
+
# install would still return well-shaped arrays, and the parent
|
|
493
|
+
# would replay them into a product that names those corrections in
|
|
494
|
+
# its sidecar. Checked per chunk, against the parent's own live set.
|
|
495
|
+
if part.hooks != expected_hooks:
|
|
496
|
+
raise Soda2ParallelRefused(
|
|
497
|
+
f"chunk {part.lo}-{part.hi} was computed by a worker whose "
|
|
498
|
+
f"substitution was {sorted(part.hooks)}, but this process has "
|
|
499
|
+
f"{sorted(expected_hooks)} live. The split would mix corrected "
|
|
500
|
+
"and uncorrected buffers into one product; refused rather than "
|
|
501
|
+
"written.")
|
|
502
|
+
t_r = time.monotonic()
|
|
503
|
+
replay.feed(part)
|
|
504
|
+
t_replay += time.monotonic() - t_r
|
|
505
|
+
n_particles += int(part.counts.sum())
|
|
506
|
+
if report_every > 0:
|
|
507
|
+
_log.info(" ...chunk %d-%d done (%d/%d), %.1f min elapsed",
|
|
508
|
+
part.lo, part.hi, j + 1, len(futures),
|
|
509
|
+
(time.monotonic() - t0) / 60.0)
|
|
510
|
+
|
|
511
|
+
out = replay.finish()
|
|
512
|
+
if report_every > 0:
|
|
513
|
+
# Where the time went, so a disappointing speedup is diagnosable from
|
|
514
|
+
# the log instead of re-measured. `sweep` is the serial carry-in pass,
|
|
515
|
+
# which the pool overlaps; `pool` is the wall time after the sweep until
|
|
516
|
+
# the last chunk was replayed, less the replay itself; `replay` is the
|
|
517
|
+
# driver's own bookkeeping, plus any `num2process` flush it triggers,
|
|
518
|
+
# summed over the chunks as they arrived. It holds no final flush: the
|
|
519
|
+
# single final `_flush` happens in `soda2_process_2d` AFTER this
|
|
520
|
+
# returns. The accumulation that flush performs (`soda2_particlesort`
|
|
521
|
+
# and the PBP writes) is serial in both paths and is the remaining floor
|
|
522
|
+
# on the WHOLE run; it is not parallelised and this line does not
|
|
523
|
+
# pretend to cover it.
|
|
524
|
+
total = time.monotonic() - t0
|
|
525
|
+
_log.info(" ...split loop: sweep %.1f s, pool %.1f s, replay %.1f s "
|
|
526
|
+
"(%d particles; the final flush is the driver's, after this)",
|
|
527
|
+
t_sweep, total - t_sweep - t_replay, t_replay, n_particles)
|
|
528
|
+
return out
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
class _Replayer:
|
|
532
|
+
"""`:495-573`, buffer by buffer, fed one chunk result at a time in buffer order.
|
|
533
|
+
|
|
534
|
+
Line for line the serial body's second half, with ``p.dhist``,
|
|
535
|
+
``p.rejectbuffer`` and ``p.diam.size`` read out of a chunk result instead of
|
|
536
|
+
off a buffer just processed. The arithmetic is the driver's, so the int16
|
|
537
|
+
``numbuffs*`` wrap, the int32 ``dhist`` accumulation and the ``istop``
|
|
538
|
+
counter are whatever they are serially -- no wider working type is
|
|
539
|
+
introduced anywhere.
|
|
540
|
+
|
|
541
|
+
Fed as chunks arrive, so the bookkeeping and any ``num2process`` flush run
|
|
542
|
+
while later chunks are still in the pool. Particle columns are kept as the
|
|
543
|
+
chunks' own arrays and concatenated only when a flush needs them. A flush is
|
|
544
|
+
handed every particle fed and not yet flushed; ``_flush`` reads
|
|
545
|
+
``x[key][:istop + 1]`` of it and nothing beyond, and those are the particles
|
|
546
|
+
of the buffers replayed so far, in order -- the values the serial ``x``
|
|
547
|
+
holds at that buffer. The columns share one dtype per key in every chunk
|
|
548
|
+
(``_x_to_arrays``), so a concatenation's dtype does not depend on which
|
|
549
|
+
chunks it spans.
|
|
550
|
+
"""
|
|
551
|
+
|
|
552
|
+
def __init__(self, *, d: Accumulator, dhist: np.ndarray, numbuffsaccepted: np.ndarray,
|
|
553
|
+
numbuffsrejected: np.ndarray, pbpstartindex: np.ndarray,
|
|
554
|
+
num2process: int, psopts: ParticlesortOptions,
|
|
555
|
+
flush: Callable[..., int], csv_f: Any, ncdf_ds: Any) -> None:
|
|
556
|
+
from .process_2d import _X_KEYS
|
|
557
|
+
|
|
558
|
+
self.keys = list(_X_KEYS)
|
|
559
|
+
self.d = d
|
|
560
|
+
self.dhist = dhist
|
|
561
|
+
self.numbuffsaccepted = numbuffsaccepted
|
|
562
|
+
self.numbuffsrejected = numbuffsrejected
|
|
563
|
+
self.pbpstartindex = pbpstartindex
|
|
564
|
+
self.num2process = num2process
|
|
565
|
+
self.psopts = psopts
|
|
566
|
+
self.flush = flush
|
|
567
|
+
self.csv_f = csv_f
|
|
568
|
+
self.ncdf_ds = ncdf_ds
|
|
569
|
+
#: The fed chunks' columns not yet wholly flushed, in buffer order, and
|
|
570
|
+
#: how many particles at the front of the first have been flushed.
|
|
571
|
+
self.pending: list[dict[str, np.ndarray]] = []
|
|
572
|
+
self.head = 0
|
|
573
|
+
self.istop = -1
|
|
574
|
+
self.ncdf_offset = 0
|
|
575
|
+
|
|
576
|
+
def _block(self) -> dict[str, np.ndarray]:
|
|
577
|
+
"""Every particle fed and not yet flushed, in order."""
|
|
578
|
+
if not self.pending:
|
|
579
|
+
from .process_2d import _new_x, _x_to_arrays
|
|
580
|
+
return _x_to_arrays(_new_x())
|
|
581
|
+
return {key: np.concatenate([self.pending[0][key][self.head:]]
|
|
582
|
+
+ [cols[key] for cols in self.pending[1:]])
|
|
583
|
+
for key in self.keys}
|
|
584
|
+
|
|
585
|
+
def _consume(self, n: int) -> None:
|
|
586
|
+
"""Drop the first ``n`` pending particles, the ones a flush just wrote."""
|
|
587
|
+
while n > 0 and self.pending:
|
|
588
|
+
left = self.pending[0][self.keys[0]].size - self.head
|
|
589
|
+
if n < left:
|
|
590
|
+
self.head += n
|
|
591
|
+
return
|
|
592
|
+
n -= left
|
|
593
|
+
self.pending.pop(0)
|
|
594
|
+
self.head = 0
|
|
595
|
+
if n > 0:
|
|
596
|
+
raise AssertionError("a flush consumed more particles than were replayed")
|
|
597
|
+
|
|
598
|
+
def feed(self, part: _ChunkResult) -> None:
|
|
599
|
+
self.pending.append(part.x)
|
|
600
|
+
dhist = self.dhist
|
|
601
|
+
for k, i in enumerate(range(part.lo, part.hi)):
|
|
602
|
+
ti = int(part.timeindex[k])
|
|
603
|
+
if not part.is_null[k]:
|
|
604
|
+
dhist[ti, :] = dhist[ti, :] + part.dhist[k, :]
|
|
605
|
+
# `lastdhist = dhist[max(ti-1,0), :]` is not carried here: it feeds
|
|
606
|
+
# only the next `process_buffer_tail`, which has already run, and
|
|
607
|
+
# `stuckbits` -- its one reader -- is refused above.
|
|
608
|
+
if not part.accepted[k]:
|
|
609
|
+
self.numbuffsrejected[ti] += 1
|
|
610
|
+
else:
|
|
611
|
+
self.numbuffsaccepted[ti] += 1
|
|
612
|
+
n = int(part.counts[k])
|
|
613
|
+
istart = self.istop + 1
|
|
614
|
+
self.istop = istart + n - 1
|
|
615
|
+
self.pbpstartindex[i] = istart + self.ncdf_offset # `:507`
|
|
616
|
+
if self.istop + 500 > self.num2process:
|
|
617
|
+
self.ncdf_offset += self.flush(
|
|
618
|
+
self.psopts, self._block(), self.d, self.istop, csv_f=self.csv_f,
|
|
619
|
+
ncdf_ds=self.ncdf_ds, ncdf_offset=self.ncdf_offset)
|
|
620
|
+
self._consume(self.istop + 1)
|
|
621
|
+
self.istop = -1
|
|
622
|
+
|
|
623
|
+
def finish(self) -> tuple[int, int, dict[str, np.ndarray]]:
|
|
624
|
+
"""What the serial loop holds when it falls out: ``(istop,
|
|
625
|
+
ncdf_offset, x)``, ``x`` being the particles not yet flushed."""
|
|
626
|
+
return self.istop, self.ncdf_offset, self._block()
|