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,407 @@
|
|
|
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_findsize.pro`` -- every size SODA-2 reports, from one silhouette.
|
|
4
|
+
|
|
5
|
+
89 lines of IDL. Calls ``aspect_ratio`` (and, through it, ``min_circle_fast``
|
|
6
|
+
and ``find_angle``), all already ported and GDL-validated.
|
|
7
|
+
|
|
8
|
+
Provenance: ``SODA2/abansemer-soda2-afcea15/soda2_findsize.pro`` (whole file),
|
|
9
|
+
Aaron Bansemer, NCAR, 2009. Copyright (C) 2016 UCAR, 3-clause BSD.
|
|
10
|
+
Validated against GDL by ``tests/test_soda2_findsize.py``; bank at
|
|
11
|
+
``gdl_oracle/run_soda2_findsize_bank.py``, 22 cases, all matching, 12 of them
|
|
12
|
+
without any shim.
|
|
13
|
+
|
|
14
|
+
**Seven size definitions, and they are not variants of one number.** A caller
|
|
15
|
+
choosing between them is making a physics decision, so the port keeps all
|
|
16
|
+
seven and names what each one measures:
|
|
17
|
+
|
|
18
|
+
=============== =========================================================
|
|
19
|
+
field what it is
|
|
20
|
+
=============== =========================================================
|
|
21
|
+
``xsize`` extent along the diode axis, shadowed columns, inclusive
|
|
22
|
+
``ysize`` extent along the slice axis
|
|
23
|
+
``diam`` ``(circle.diam + 1) * xres`` -- the minimum enclosing
|
|
24
|
+
circle, plus one pixel for the 0.5 shading threshold
|
|
25
|
+
``areasize`` ``diam * sqrt(ar)`` -- area-equivalent, and the only one
|
|
26
|
+
that corrects for a partially imaged particle
|
|
27
|
+
``xextent`` the largest per-*slice* diode span; Korolev's ``Ly``
|
|
28
|
+
``oned`` a 1-D probe emulation: diodes latch once shadowed
|
|
29
|
+
``twod`` a 2-D probe emulation: the fullest single slice
|
|
30
|
+
=============== =========================================================
|
|
31
|
+
|
|
32
|
+
``oned`` and ``twod`` are both per Lyle Lilie, 12/2020, and both deliberately
|
|
33
|
+
ignore gaps. They differ whenever a particle's shadowed diodes are not all
|
|
34
|
+
shadowed in the same slice -- see the bank's
|
|
35
|
+
``gap_makes_oned_and_twod_differ``, where ``oned`` is 4 pixels and ``twod`` 2.
|
|
36
|
+
|
|
37
|
+
**The zero-area early return hands back defaults that look like measurements.**
|
|
38
|
+
``:13`` returns the predefined structure when ``area_original`` is 0, and that
|
|
39
|
+
structure declares ``centerin: 1b`` and ``allin: 0b``. So an empty image
|
|
40
|
+
reports *centre-in* and *not all-in* — the first of which is an assertion the
|
|
41
|
+
routine never checked. Nothing in the return distinguishes it from a real
|
|
42
|
+
particle that happens to score zero. Finding **S3-e**.
|
|
43
|
+
|
|
44
|
+
**And it is reachable by an integer resolution.** ``area_original = total(img)
|
|
45
|
+
* (yres/xres)``: if a caller passes ``xres``/``yres`` as IDL INTs, that
|
|
46
|
+
division is *integer* division, ``yres/xres`` is 0 for any ``yres < xres``,
|
|
47
|
+
and every particle silently reports zero for every size. ``soda2_samplearea``
|
|
48
|
+
guards against exactly this with ``float()`` at its ``:17-18``; this routine
|
|
49
|
+
does not. Measured — the bank's own generator fell into it before it was a
|
|
50
|
+
case. Finding **S3-d**. The port reproduces it: pass ``np.int32`` resolutions
|
|
51
|
+
and you get zeros, as IDL does.
|
|
52
|
+
|
|
53
|
+
**``img`` is reformed in place.** ``:15-18`` reforms ``img`` to a single-slice 2-D shape
|
|
54
|
+
for 1-D input, and IDL passes a named variable by reference, so **the
|
|
55
|
+
caller's own array comes back reshaped**. Measured: a 1-D array of 9 goes in
|
|
56
|
+
and ``size(img,/dimensions)`` afterwards reports ``9x1``. Finding **S3-c**.
|
|
57
|
+
Python has no such semantics; :func:`soda2_findsize` never mutates its
|
|
58
|
+
argument, and :data:`RESHAPES_CALLER_INPUT` documents the divergence so a
|
|
59
|
+
caller porting IDL code that *relied* on it is not silently surprised.
|
|
60
|
+
|
|
61
|
+
**``centerin`` is decided by extent, not by shadow count**, at ``:52`` and
|
|
62
|
+
``:58``, with the shadow-count version sitting commented out directly above
|
|
63
|
+
each — *"This center-in method seems to work best so far, based on
|
|
64
|
+
simulations."* The test is ``ge``, not ``gt``, so a tie sets ``centerin = 0``.
|
|
65
|
+
Both are preserved and both are pinned by the bank.
|
|
66
|
+
|
|
67
|
+
**``!pi`` is single precision** (finding S2-c), and it appears twice in the
|
|
68
|
+
truncated-circle geometry at ``:81``. ``_PI`` below is ``np.float32(pi)`` for
|
|
69
|
+
that reason, not for speed.
|
|
70
|
+
|
|
71
|
+
**The truncation runs in DOUBLE and the all-in branch in FLOAT.** ``:76``
|
|
72
|
+
takes ``x`` from ``circle.center[0]`` -- the raw DOUBLE that ``find_radius``
|
|
73
|
+
produced -- and not from ``out.c[0]``, the FLOAT copy stored into the output
|
|
74
|
+
struct two lines earlier. So every expression in the ``allin eq 0`` branch
|
|
75
|
+
promotes to double, while ``circle_area_imaged = !pi * r^2`` on the other
|
|
76
|
+
branch has no DOUBLE operand and stays single. The same quantity is therefore
|
|
77
|
+
computed at two precisions depending on where the particle sat on the array.
|
|
78
|
+
Finding **S3-f**, and the same FLOAT/DOUBLE mixture S2-e reports for
|
|
79
|
+
``aspect_ratio``. This port got it wrong first -- it used ``out.c[0]`` -- and
|
|
80
|
+
the error was 7e-8 relative in ``ar``, one float32 ulp, which the golden
|
|
81
|
+
caught on every edge-touching case and no amount of reading had.
|
|
82
|
+
"""
|
|
83
|
+
from __future__ import annotations
|
|
84
|
+
|
|
85
|
+
import math
|
|
86
|
+
import warnings
|
|
87
|
+
from dataclasses import dataclass, field
|
|
88
|
+
from typing import Any
|
|
89
|
+
|
|
90
|
+
import numpy as np
|
|
91
|
+
|
|
92
|
+
from arrayprobe_soda2.aspect_ratio import _op as _idl_op
|
|
93
|
+
from arrayprobe_soda2.aspect_ratio import aspect_ratio
|
|
94
|
+
|
|
95
|
+
__all__ = [
|
|
96
|
+
"RESHAPES_CALLER_INPUT",
|
|
97
|
+
"FindSizeResult",
|
|
98
|
+
"soda2_findsize",
|
|
99
|
+
]
|
|
100
|
+
|
|
101
|
+
#: IDL reforms the caller's own ``img`` in place for 1-D input (``:16``);
|
|
102
|
+
#: this port does not. Named so the divergence is greppable rather than
|
|
103
|
+
#: buried in prose. See the module docstring, finding S3-c.
|
|
104
|
+
RESHAPES_CALLER_INPUT = False
|
|
105
|
+
|
|
106
|
+
#: ``!pi``, which IDL types as FLOAT and never as ``!dpi`` anywhere in
|
|
107
|
+
#: SODA-2 (finding S2-c). Used at ``:81`` twice.
|
|
108
|
+
_PI = np.float32(math.pi)
|
|
109
|
+
|
|
110
|
+
#: IDL's ``< 1`` at :77-78 and ``< 1.0`` at :83-84 -- one is an INT literal
|
|
111
|
+
#: and the other a FLOAT one, and the difference is load-bearing. An INT does
|
|
112
|
+
#: not promote a FLOAT operand, so the double precision of the truncation
|
|
113
|
+
#: geometry comes entirely from ``x`` being ``circle.center[0]``'s DOUBLE.
|
|
114
|
+
#: Writing a Python ``1.0`` here instead would promote the expression by
|
|
115
|
+
#: itself and mask that -- measured: it made the "take x from the FLOAT copy"
|
|
116
|
+
#: mutation pass, i.e. the test stopped guarding the thing it was written for.
|
|
117
|
+
_ONE_INT = np.int16(1)
|
|
118
|
+
_ONE_FLOAT = np.float32(1.0)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _f(value: Any) -> np.float32:
|
|
122
|
+
"""A bare IDL decimal literal: FLOAT, not DOUBLE."""
|
|
123
|
+
return np.float32(value)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _idl_div(a: Any, b: Any) -> Any:
|
|
127
|
+
"""``a / b`` as IDL evaluates it, integer division included.
|
|
128
|
+
|
|
129
|
+
NumPy's ``/`` is true division for every dtype, so ``np.int32(5) /
|
|
130
|
+
np.int32(10)`` is 0.5 where IDL gives **0**. That difference is the whole
|
|
131
|
+
of finding S3-d, and a port using bare ``/`` here would quietly repair the
|
|
132
|
+
defect it is meant to reproduce -- which is worse than not porting the
|
|
133
|
+
line, because the repair is invisible.
|
|
134
|
+
|
|
135
|
+
IDL truncates toward zero rather than flooring, so ``-1/2`` is 0 and not
|
|
136
|
+
NumPy's ``-1``. Both operands must be integer types for this to apply;
|
|
137
|
+
one FLOAT promotes the whole expression, which is exactly why
|
|
138
|
+
``soda2_samplearea``'s ``float()`` casts work as a guard.
|
|
139
|
+
"""
|
|
140
|
+
a_arr, b_arr = np.asarray(a), np.asarray(b)
|
|
141
|
+
if (np.issubdtype(a_arr.dtype, np.integer)
|
|
142
|
+
and np.issubdtype(b_arr.dtype, np.integer)):
|
|
143
|
+
quotient = np.trunc(a_arr.astype(np.float64)
|
|
144
|
+
/ b_arr.astype(np.float64))
|
|
145
|
+
return quotient.astype(a_arr.dtype)
|
|
146
|
+
return a / b
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass
|
|
150
|
+
class FindSizeResult:
|
|
151
|
+
"""``soda2_findsize.pro``'s predefined output structure (``:9-10``), field
|
|
152
|
+
for field and in declaration order.
|
|
153
|
+
|
|
154
|
+
The declared types are part of the contract and are reproduced: the seven
|
|
155
|
+
sizes and ``ar``/``arfilled``/``aspr``/``orientation`` are declared
|
|
156
|
+
``0.0`` (FLOAT); ``perimeterarea`` is ``0L`` (LONG); ``allin``,
|
|
157
|
+
``centerin`` and ``edgetouch`` are BYTE; ``c`` is ``fltarr(2)``.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
diam: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
161
|
+
xsize: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
162
|
+
ysize: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
163
|
+
areasize: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
164
|
+
ar: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
165
|
+
arfilled: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
166
|
+
aspr: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
167
|
+
allin: int = 0
|
|
168
|
+
c: np.ndarray = field(
|
|
169
|
+
default_factory=lambda: np.zeros(2, dtype=np.float32))
|
|
170
|
+
centerin: int = 1
|
|
171
|
+
orientation: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
172
|
+
perimeterarea: int = 0
|
|
173
|
+
edgetouch: int = 0
|
|
174
|
+
xextent: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
175
|
+
oned: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
176
|
+
twod: np.float32 = field(default_factory=lambda: np.float32(0.0))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _as_2d(img: Any) -> np.ndarray:
|
|
180
|
+
"""``img`` as ``(n_slices, n_diodes)``.
|
|
181
|
+
|
|
182
|
+
**This is the transpose of IDL's own indexing, and it is the convention
|
|
183
|
+
every image in this port already uses** -- ``aspect_ratio.outline_indices``
|
|
184
|
+
documents it, and ``min_circle_fast``'s tie-breaking depends on the C-order
|
|
185
|
+
``ravel()`` of exactly this layout matching IDL's flat ``where`` order.
|
|
186
|
+
So ``img[x, y]`` in the source is ``im[y, x]`` here, and IDL's ``dim=1``
|
|
187
|
+
(reduce over x) is ``axis=1`` while its ``dim=2`` (reduce over y) is
|
|
188
|
+
``axis=0``. Every reduction below names which it is.
|
|
189
|
+
|
|
190
|
+
``:15-18``'s reform is reproduced on a local copy: a 1-D input becomes one
|
|
191
|
+
slice. The only thing not reproduced is the write-back to the caller's
|
|
192
|
+
variable (:data:`RESHAPES_CALLER_INPUT`).
|
|
193
|
+
"""
|
|
194
|
+
arr = np.asarray(img)
|
|
195
|
+
if arr.ndim == 1:
|
|
196
|
+
return arr.reshape(1, arr.shape[0])
|
|
197
|
+
return arr
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def soda2_findsize(
|
|
201
|
+
img: Any,
|
|
202
|
+
xres: Any,
|
|
203
|
+
yres: Any,
|
|
204
|
+
voidarea: Any = 0,
|
|
205
|
+
) -> FindSizeResult:
|
|
206
|
+
"""``out = soda2_findsize(img, xres, yres, voidarea=voidarea)``.
|
|
207
|
+
|
|
208
|
+
Source: ``soda2_findsize.pro`` (SODA-2).
|
|
209
|
+
|
|
210
|
+
``img`` is a binary silhouette indexed ``[diode, slice]``, matching IDL's
|
|
211
|
+
``img[x, y]``. ``xres`` and ``yres`` are micrometres per pixel along the
|
|
212
|
+
diode and slice axes.
|
|
213
|
+
|
|
214
|
+
**Pass FLOAT resolutions.** An integer ``xres``/``yres`` reproduces IDL's
|
|
215
|
+
integer division at ``:11`` and can zero every returned size without
|
|
216
|
+
error (SODA-2 register entry S3-d), and the reason the type of these two arguments is
|
|
217
|
+
respected rather than coerced.
|
|
218
|
+
"""
|
|
219
|
+
out = FindSizeResult()
|
|
220
|
+
|
|
221
|
+
im = _as_2d(img)
|
|
222
|
+
ny, nx = im.shape # slices, diodes -- see _as_2d
|
|
223
|
+
|
|
224
|
+
# :11-12 -- `total()` on a BYTE array is FLOAT in IDL. `yres/xres` keeps
|
|
225
|
+
# the caller's types, integer division included: that IS the behaviour.
|
|
226
|
+
total_img = im.sum()
|
|
227
|
+
ratio = _idl_div(yres, xres)
|
|
228
|
+
area_original = np.float32(total_img) * ratio
|
|
229
|
+
area_original_filled = np.float32(total_img + voidarea) * ratio
|
|
230
|
+
|
|
231
|
+
# :13 -- the early return. Everything below is left at its declared
|
|
232
|
+
# default, `centerin = 1` among them.
|
|
233
|
+
if area_original == 0:
|
|
234
|
+
return out
|
|
235
|
+
|
|
236
|
+
# :21-22 / :25-26 -- `total(img,2)` sums over IDL's y (the slice axis),
|
|
237
|
+
# giving one number per diode; `total(img,1)` sums over x, one per slice.
|
|
238
|
+
# In this port's (slices, diodes) layout those are axis=0 and axis=1.
|
|
239
|
+
per_diode = im.sum(axis=0)
|
|
240
|
+
per_slice = im.sum(axis=1)
|
|
241
|
+
|
|
242
|
+
w = np.nonzero(per_diode > 0)[0]
|
|
243
|
+
out.xsize = _f(w.max() - w.min() + 1) * xres
|
|
244
|
+
w = np.nonzero(per_slice > 0)[0]
|
|
245
|
+
out.ysize = _f(w.max() - w.min() + 1) * yres
|
|
246
|
+
|
|
247
|
+
# :30 -- the comment is right: min_circle_fast runs inside aspect_ratio,
|
|
248
|
+
# so it must not be run again here. `tas_adjust` is FLOAT in production
|
|
249
|
+
# (both operands are FLOAT probespecs fields), and aspect_ratio selects
|
|
250
|
+
# IDL's type behaviour from the Python type it is handed.
|
|
251
|
+
res = aspect_ratio(im, tas_adjust=np.float32(ratio))
|
|
252
|
+
circle = res.circle
|
|
253
|
+
x_ind, y_ind = res.x_ind, res.y_ind
|
|
254
|
+
|
|
255
|
+
out.aspr = np.float32(res.aspr)
|
|
256
|
+
# :31 -- `(circle.diam+1)*xres`: `circle.diam` is DOUBLE, `1` an INT
|
|
257
|
+
# literal (promotes to DOUBLE), `xres` FLOAT -- IDL's DOUBLE*FLOAT stays
|
|
258
|
+
# DOUBLE, and the *only* rounding to FLOAT happens once, at assignment
|
|
259
|
+
# into the struct's declared-FLOAT `diam` field. Casting `circle.diam`
|
|
260
|
+
# to float32 before the add/multiply (as this line used to) rounds
|
|
261
|
+
# twice in a different order and differs from GDL by exactly one
|
|
262
|
+
# float32 ULP on any particle whose true value sits near a rounding
|
|
263
|
+
# boundary -- measured on `frame_h_all18` particles 4/5/6 (R7C),
|
|
264
|
+
# root-caused by bisection against `min_circle_fast`, which
|
|
265
|
+
# already agreed with GDL bit for bit on these exact ROIs.
|
|
266
|
+
out.diam = _f((float(circle.diam) + 1.0) * float(xres))
|
|
267
|
+
out.c = np.asarray(circle.center, dtype=np.float32)
|
|
268
|
+
out.orientation = res.orientation
|
|
269
|
+
out.perimeterarea = int(circle.area)
|
|
270
|
+
|
|
271
|
+
# :35 -- allin is about the two END diodes only, whatever the particle
|
|
272
|
+
# does in between.
|
|
273
|
+
out.allin = 0 if (im[:, 0].sum() + im[:, nx - 1].sum()) != 0 else 1
|
|
274
|
+
|
|
275
|
+
# :38-45 -- an all-NaN image, filled at the OUTLINE indices only, so the
|
|
276
|
+
# extent is over the outline rather than over every shadowed pixel.
|
|
277
|
+
# `max`/`min` without /NAN meet NaN here; GDL skips it (finding S2-i)
|
|
278
|
+
# and `nanmax`/`nanmin` are the same rule.
|
|
279
|
+
img2 = np.full((ny, nx), np.nan, dtype=np.float32)
|
|
280
|
+
img2[y_ind, x_ind] = y_ind
|
|
281
|
+
with np.errstate(invalid="ignore"):
|
|
282
|
+
# IDL `max(img2, dim=2) - min(img2, dim=2)`: reduce over y, one
|
|
283
|
+
# value per diode. That is axis=0 in this layout.
|
|
284
|
+
extent = _nanspan(img2, axis=0)
|
|
285
|
+
|
|
286
|
+
ileft, iright = 0, nx - 1
|
|
287
|
+
if per_diode[ileft] > 0:
|
|
288
|
+
out.edgetouch += 1
|
|
289
|
+
# :52 -- `ge`, not `gt`: a tie sets centerin to 0.
|
|
290
|
+
if _ge_ignoring_nan(extent[ileft], _nanmax(extent)):
|
|
291
|
+
out.centerin = 0
|
|
292
|
+
if per_diode[iright] > 0:
|
|
293
|
+
out.edgetouch += 2
|
|
294
|
+
if _ge_ignoring_nan(extent[iright], _nanmax(extent)):
|
|
295
|
+
out.centerin = 0
|
|
296
|
+
|
|
297
|
+
# :61-62 -- the SAME NaN image, refilled with the diode index, reduced
|
|
298
|
+
# the other way: the largest x-span within any one slice. Korolev's `Ly`.
|
|
299
|
+
img2[y_ind, x_ind] = x_ind
|
|
300
|
+
with np.errstate(invalid="ignore"):
|
|
301
|
+
# IDL `dim=1`: reduce over x, one value per slice -- axis=1 here.
|
|
302
|
+
xspan = _nanspan(img2, axis=1)
|
|
303
|
+
out.xextent = _f(_nanmax(xspan) + 1.0) * xres
|
|
304
|
+
|
|
305
|
+
# :66-68 -- `total(img,2) < 1` is a MIN: every shadowed diode counts once,
|
|
306
|
+
# however many slices it appears in. Gaps along the slice axis vanish.
|
|
307
|
+
latch = np.minimum(per_diode, 1)
|
|
308
|
+
out.oned = _f(latch.sum()) * xres
|
|
309
|
+
|
|
310
|
+
# :71-72 -- no latching: the single fullest slice decides.
|
|
311
|
+
out.twod = _f(per_slice.max()) * xres
|
|
312
|
+
|
|
313
|
+
# :74-82 -- the truncated-circle correction, reached only when the
|
|
314
|
+
# particle touches an end diode.
|
|
315
|
+
r = out.diam / xres / _f(2.0)
|
|
316
|
+
# :76 -- `x = circle.center[0]`, the raw DOUBLE from `find_radius`, NOT
|
|
317
|
+
# `out.c[0]`, which is the FLOAT copy stored two lines earlier. The
|
|
318
|
+
# distinction is not cosmetic: it makes the whole truncation below run in
|
|
319
|
+
# double, and using the FLOAT copy instead moved `ar` by 7e-8 relative --
|
|
320
|
+
# one float32 ulp, and enough to miss the golden on every edge-touching
|
|
321
|
+
# case. Measured, after the port got it wrong first.
|
|
322
|
+
x = np.float64(circle.center[0])
|
|
323
|
+
if out.allin == 0:
|
|
324
|
+
# `<1` is MIN: acos's domain is enforced by a clamp, not a check.
|
|
325
|
+
# `x` is DOUBLE and `r` FLOAT, so every expression here promotes --
|
|
326
|
+
# the same FLOAT/DOUBLE mixture finding S2-e reports for
|
|
327
|
+
# `aspect_ratio`, in a second routine.
|
|
328
|
+
# `s[1]-1-x` is LONG minus x. NumPy would make `int32 - float32`
|
|
329
|
+
# into float64 -- IDL makes it FLOAT -- so it goes through
|
|
330
|
+
# aspect_ratio's `_op`, the same helper that routine already needs for
|
|
331
|
+
# the same reason. Writing `np.float64(nx - 1)` here instead promoted
|
|
332
|
+
# the sum by itself and masked the `x` mutation: the test then passed
|
|
333
|
+
# with `x` taken from the FLOAT copy, i.e. stopped guarding what it
|
|
334
|
+
# was written to guard.
|
|
335
|
+
right = _idl_op(np.int32(nx - 1), x, np.subtract)
|
|
336
|
+
theta = np.arccos(np.minimum(x / r, _ONE_INT))
|
|
337
|
+
phi = np.arccos(np.minimum(_idl_op(right, r, np.divide), _ONE_INT))
|
|
338
|
+
circle_area_imaged = (
|
|
339
|
+
x * r * np.sin(theta)
|
|
340
|
+
+ _idl_op(right, r, np.multiply) * np.sin(phi)
|
|
341
|
+
+ _PI * r ** 2 * ((_PI - phi - theta) / _PI)
|
|
342
|
+
)
|
|
343
|
+
else:
|
|
344
|
+
# The all-in branch has no DOUBLE operand, so it stays FLOAT. The two
|
|
345
|
+
# branches therefore return different precisions for the same
|
|
346
|
+
# quantity -- preserved, and reported as part of S3-f.
|
|
347
|
+
circle_area_imaged = _PI * r ** 2
|
|
348
|
+
|
|
349
|
+
# :83-84 -- `< 1.0` is MIN again, and it absorbs a non-finite ratio into
|
|
350
|
+
# exactly 1.0, the same overload S2-d reports for `aspect_ratio`.
|
|
351
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
352
|
+
# Computed at whatever precision the branch above produced, then
|
|
353
|
+
# narrowed on assignment because the struct field is `0.0` (FLOAT).
|
|
354
|
+
out.ar = _f(np.minimum(area_original / circle_area_imaged, _ONE_FLOAT))
|
|
355
|
+
out.arfilled = _f(np.minimum(
|
|
356
|
+
area_original_filled / circle_area_imaged, _ONE_FLOAT))
|
|
357
|
+
|
|
358
|
+
# :86 -- "Can show by derivation. This also adjusts for partial images."
|
|
359
|
+
out.areasize = out.diam * np.sqrt(out.ar)
|
|
360
|
+
return out
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _nanspan(arr: np.ndarray, axis: int) -> np.ndarray:
|
|
364
|
+
"""``max(arr, dim=n) - min(arr, dim=n)`` with IDL/GDL's NaN handling.
|
|
365
|
+
|
|
366
|
+
GDL's bare ``min``/``max`` skip NaN (finding S2-i), which is what
|
|
367
|
+
``nanmax``/``nanmin`` do. A column that is entirely NaN -- a diode with no
|
|
368
|
+
outline pixel -- yields NaN here rather than raising, and NaN is then what
|
|
369
|
+
the ``ge`` comparisons below see, which is the behaviour being reproduced.
|
|
370
|
+
"""
|
|
371
|
+
# An all-NaN reduction is EXPECTED here, not exceptional: a diode with no
|
|
372
|
+
# outline pixel has nothing to take a span over, and IDL/GDL return NaN
|
|
373
|
+
# rather than complaining. numpy warns; the warning is suppressed rather
|
|
374
|
+
# than the case avoided, because avoiding it would mean not reproducing it.
|
|
375
|
+
with warnings.catch_warnings():
|
|
376
|
+
warnings.filterwarnings("ignore", r"All-NaN slice encountered",
|
|
377
|
+
RuntimeWarning)
|
|
378
|
+
with np.errstate(invalid="ignore"):
|
|
379
|
+
hi = np.nanmax(arr, axis=axis)
|
|
380
|
+
lo = np.nanmin(arr, axis=axis)
|
|
381
|
+
return hi - lo
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _nanmax(arr: np.ndarray) -> Any:
|
|
385
|
+
"""max(arr) with GDL's NaN-skipping and no warning on an all-NaN
|
|
386
|
+
input, which is a reachable state rather than a mistake."""
|
|
387
|
+
with warnings.catch_warnings():
|
|
388
|
+
warnings.filterwarnings("ignore", r"All-NaN", RuntimeWarning)
|
|
389
|
+
return np.nanmax(arr)
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def _ge_ignoring_nan(value: Any, limit: Any) -> bool:
|
|
393
|
+
"""``value ge limit`` as IDL evaluates it: FALSE if either side is NaN.
|
|
394
|
+
|
|
395
|
+
Spelled out because ``np.nan >= x`` is also False in NumPy and it would
|
|
396
|
+
be easy to leave that to luck. Reproducing it deliberately means a future
|
|
397
|
+
reader knows it was checked.
|
|
398
|
+
"""
|
|
399
|
+
return bool(value >= limit)
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _all_nan_columns_are_possible() -> None: # pragma: no cover - documentation
|
|
403
|
+
"""A diode with no *outline* pixel is entirely NaN in ``img2``, even
|
|
404
|
+
though the diode is shadowed: for a solid block, the interior columns
|
|
405
|
+
keep their outline pixels but a one-pixel-thick interior would not. The
|
|
406
|
+
bank's ``hollow_ring`` reaches the case; this stub exists only so the
|
|
407
|
+
reasoning is greppable from the code that depends on it."""
|
|
@@ -0,0 +1,170 @@
|
|
|
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
|
+
"""``fit_poisson.pro`` + ``fn_poisson.pro`` -- the double-Poisson interarrival
|
|
4
|
+
fit used by ``soda2_particlesort.pro:95`` when ``inttime_reject eq 1`` and a
|
|
5
|
+
one-second bin holds more than 100 particles.
|
|
6
|
+
|
|
7
|
+
Provenance: ``SODA2/abansemer-soda2-afcea15/fit_poisson.pro`` (49 lines) and
|
|
8
|
+
``fn_poisson.pro`` (16 lines), Aaron Bansemer, NCAR, 2009. Copyright (C) 2016
|
|
9
|
+
UCAR, 3-clause BSD.
|
|
10
|
+
|
|
11
|
+
**No GDL oracle exists for this module, and that is a measured fact, not an
|
|
12
|
+
assumption.** GDL 1.1.2 does not implement ``LMFIT``: it is absent from
|
|
13
|
+
``routine_info(/system,/functions)`` and no ``lmfit.pro`` exists under
|
|
14
|
+
``scripts/gdl/share/gnudatalanguage/lib`` (only ``curvefit.pro`` does). This was
|
|
15
|
+
checked directly, not inferred from the file list. Consequently
|
|
16
|
+
``fit_poisson`` cannot be validated bit-for-bit against the real IDL/GDL
|
|
17
|
+
routine the way every other SODA-2 module in this package is. It is **layer 3
|
|
18
|
+
only** (documented semantics + a pinned test), per the
|
|
19
|
+
three-layer validation approach, until an ``LMFIT`` oracle exists. Callers
|
|
20
|
+
that need a fully-oracled path should set ``op.inttime_reject = 0`` on the
|
|
21
|
+
accumulation module (``particlesort.py``), which then skips this branch
|
|
22
|
+
entirely -- exactly as the IDL does.
|
|
23
|
+
|
|
24
|
+
``fn_poisson`` (the model + its analytic Jacobian) has no numerics beyond
|
|
25
|
+
``alog10``/``exp`` and is a hand-derived, reference-independent port: its
|
|
26
|
+
correctness is checked against the closed-form derivative by finite
|
|
27
|
+
differences in ``tests/test_fit_poisson.py``, which is the "third side" the
|
|
28
|
+
project's doctrine asks for.
|
|
29
|
+
|
|
30
|
+
``fit_poisson`` itself calls IDL's ``LMFIT`` (Levenberg-Marquardt, non-linear
|
|
31
|
+
least squares), which this port maps to ``scipy.optimize.least_squares``
|
|
32
|
+
(Levenberg-Marquardt method, ``method="lm"``) rather than hand-rolling LM in
|
|
33
|
+
NumPy -- ``scipy`` is already an accepted *extra* dependency of this package
|
|
34
|
+
(see ``pyproject.toml``'s ``extra = ["scipy>=1.16", ...]``, added for other
|
|
35
|
+
enhancements work), so this is not a new dependency the port would otherwise
|
|
36
|
+
refuse.
|
|
37
|
+
|
|
38
|
+
**Documented substitute, not a bit-faithful port.** IDL ``LMFIT`` (Numerical
|
|
39
|
+
Recipes ``mrqmin``: ``iter`` is an iteration cap, ``tol`` defaults per the
|
|
40
|
+
IDL reference, convergence returned in ``converg``) and
|
|
41
|
+
``scipy.optimize.least_squares(method='lm')`` (MINPACK ``lmder``; ``max_nfev``
|
|
42
|
+
counts *function evaluations*, not iterations; ``ftol/xtol/gtol`` 1e-8) are
|
|
43
|
+
different algorithms with different stopping rules. Coefficients agree only
|
|
44
|
+
to the extent both converge to the same minimum; no oracle has confirmed even
|
|
45
|
+
that. Recorded as a design note, not as a finding. (IDL's own ``LMFIT``
|
|
46
|
+
default ``tol`` value
|
|
47
|
+
is not verified on this machine -- no IDL reference was opened to check it;
|
|
48
|
+
do not infer one.)
|
|
49
|
+
"""
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
from collections.abc import Sequence
|
|
53
|
+
from dataclasses import dataclass
|
|
54
|
+
|
|
55
|
+
import numpy as np
|
|
56
|
+
|
|
57
|
+
__all__ = ["fn_poisson", "fit_poisson", "PoissonFit"]
|
|
58
|
+
|
|
59
|
+
#: ``k=alog10(exp(1))``, fn_poisson.pro:6 -- converts natural-log-based
|
|
60
|
+
#: exponential slopes into the same log10 units the histogram is expressed in.
|
|
61
|
+
_K = np.log10(np.e)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def fn_poisson(dt: np.ndarray | float, ans: Sequence[float] | np.ndarray) -> np.ndarray:
|
|
65
|
+
"""Port of ``fn_poisson.pro``.
|
|
66
|
+
|
|
67
|
+
``ans = [a, sigma, rho]``. Returns a length-4 array (for scalar ``dt``)
|
|
68
|
+
or an ``(4, len(dt))`` array (for array ``dt``): index 0 is the model
|
|
69
|
+
value, indices 1-3 are ``d(value)/d(ans[0..2])`` -- what IDL's ``LMFIT``
|
|
70
|
+
user function contract requires when it computes its own Jacobian
|
|
71
|
+
analytically rather than by finite differences.
|
|
72
|
+
|
|
73
|
+
Ported line-for-line from the IDL; the four output slots are exactly the
|
|
74
|
+
source's ``out[0..3]``.
|
|
75
|
+
"""
|
|
76
|
+
dt_arr = np.asarray(dt, dtype=np.float64)
|
|
77
|
+
a0, a1, a2 = ans[0], ans[1], ans[2]
|
|
78
|
+
|
|
79
|
+
out0 = (
|
|
80
|
+
a0 * a1 * dt_arr * np.exp(-a1 * dt_arr) / _K
|
|
81
|
+
+ (1.0 - a0) * a2 * dt_arr * np.exp(-a2 * dt_arr) / _K
|
|
82
|
+
)
|
|
83
|
+
out1 = a1 * dt_arr * np.exp(-a1 * dt_arr) / _K - a2 * dt_arr * np.exp(-a2 * dt_arr) / _K
|
|
84
|
+
out2 = (
|
|
85
|
+
a0 * dt_arr * np.exp(-a1 * dt_arr) / _K
|
|
86
|
+
- a0 * a1 * dt_arr**2 * np.exp(-a1 * dt_arr) / _K
|
|
87
|
+
)
|
|
88
|
+
out3 = (
|
|
89
|
+
(1.0 - a0) * dt_arr * np.exp(-a2 * dt_arr) / _K
|
|
90
|
+
- (1.0 - a0) * a2 * dt_arr**2 * np.exp(-a2 * dt_arr) / _K
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
if dt_arr.ndim == 0:
|
|
94
|
+
return np.array([out0, out1, out2, out3])
|
|
95
|
+
return np.stack([out0, out1, out2, out3], axis=0)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass
|
|
99
|
+
class PoissonFit:
|
|
100
|
+
"""``fit_poisson``'s return. IDL returns ``{a:[0.0,0.0,0.0]}`` on the
|
|
101
|
+
empty-``iy`` early exit (``:26``) and ``{a:a}`` (the fitted coefficients)
|
|
102
|
+
otherwise -- both cases are one field, ``a``, reproduced here.
|
|
103
|
+
|
|
104
|
+
Source: the return of ``fit_poisson.pro`` (SODA-2); bare line references here are into that
|
|
105
|
+
file."""
|
|
106
|
+
|
|
107
|
+
a: np.ndarray
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def fit_poisson(
|
|
111
|
+
h: np.ndarray,
|
|
112
|
+
dt: np.ndarray,
|
|
113
|
+
minidt: float,
|
|
114
|
+
plot: bool = False,
|
|
115
|
+
) -> PoissonFit:
|
|
116
|
+
"""Port of ``fit_poisson.pro``.
|
|
117
|
+
|
|
118
|
+
``h`` -- histogram counts at the ``dt`` midbins (``d.intspec_all[itime,
|
|
119
|
+
*]`` in the caller). ``minidt`` -- first-guess separator for the two
|
|
120
|
+
Poisson components.
|
|
121
|
+
|
|
122
|
+
``plot`` is accepted for signature parity with the IDL keyword but does
|
|
123
|
+
nothing: the source's plotting branch (``:34-46``) is interactive
|
|
124
|
+
visualisation, out of scope for this accumulation port and never called
|
|
125
|
+
with a true value from ``soda2_particlesort.pro:95`` (``plot=0``).
|
|
126
|
+
"""
|
|
127
|
+
h = np.asarray(h, dtype=np.float64).ravel()
|
|
128
|
+
dt = np.asarray(dt, dtype=np.float64).ravel()
|
|
129
|
+
|
|
130
|
+
# Deconstruct the histogram back into individual interarrival samples,
|
|
131
|
+
# fit_poisson.pro:16-18. IDL's fltarr(h[i]) requires h[i] >= 0; a
|
|
132
|
+
# negative count is a caller bug the source does not guard, so this
|
|
133
|
+
# doesn't either.
|
|
134
|
+
pieces = [np.full(int(h[i]), dt[i], dtype=np.float64) for i in range(len(dt)) if h[i] > 0]
|
|
135
|
+
int_t = np.concatenate(pieces) if pieces else np.array([], dtype=np.float64)
|
|
136
|
+
|
|
137
|
+
dlogdt = 0.2
|
|
138
|
+
th = h.sum()
|
|
139
|
+
# IDL: h/th/dlogdt with th possibly 0 -> IEEE inf/nan, not an exception.
|
|
140
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
141
|
+
h2 = h / th / dlogdt
|
|
142
|
+
|
|
143
|
+
iy = np.where((int_t > minidt) & (int_t < 1.0))[0]
|
|
144
|
+
if iy.size == 0:
|
|
145
|
+
# fit_poisson.pro:26 -- IDL's `where` returning no matches gives
|
|
146
|
+
# iy[0] eq -1, taken as the empty-result sentinel.
|
|
147
|
+
return PoissonFit(a=np.array([0.0, 0.0, 0.0]))
|
|
148
|
+
|
|
149
|
+
mean_iy = np.nanmean(int_t[iy])
|
|
150
|
+
a0 = np.array([0.99, 1.0 / mean_iy, 1.0 / (mean_iy / 1000.0)])
|
|
151
|
+
|
|
152
|
+
def residual(ans: np.ndarray) -> np.ndarray:
|
|
153
|
+
model = fn_poisson(dt, ans)[0]
|
|
154
|
+
return model - h2
|
|
155
|
+
|
|
156
|
+
def jacobian(ans: np.ndarray) -> np.ndarray:
|
|
157
|
+
# fn_poisson's own analytic partials, exactly what LMFIT's `func`
|
|
158
|
+
# contract supplies as out[1:].
|
|
159
|
+
return fn_poisson(dt, ans)[1:4].T
|
|
160
|
+
|
|
161
|
+
from scipy.optimize import least_squares
|
|
162
|
+
|
|
163
|
+
result = least_squares(
|
|
164
|
+
residual,
|
|
165
|
+
a0,
|
|
166
|
+
jac=jacobian,
|
|
167
|
+
method="lm",
|
|
168
|
+
max_nfev=150,
|
|
169
|
+
)
|
|
170
|
+
return PoissonFit(a=result.x)
|
|
@@ -0,0 +1,63 @@
|
|
|
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
|
+
"""SODA-2 ``fix2dimage.pro`` (28 lines): rewrites NCAR-format sync/timing slices of
|
|
4
|
+
a 2DC buffer into the standard ``0x55`` sync pattern. Called by
|
|
5
|
+
``soda2_processbuffer.pro:87`` when a 2DC buffer yields fewer than three syncs.
|
|
6
|
+
|
|
7
|
+
Line map:
|
|
8
|
+
- `:9` candidates: words equal to ``0xFF800000``, ``0``, ``0xFF000000`` or ``0x2A000000``.
|
|
9
|
+
- `:10` fewer than five candidates: the image is returned unchanged.
|
|
10
|
+
- `:13-15` ``diff``/``good``: keep ``test1[k]`` where ``test1[k+1]-test1[k] > 1``. This
|
|
11
|
+
always drops the last candidate (``good`` indexes ``diff``, one shorter); when no gap
|
|
12
|
+
exceeds one, ``where`` gives -1 and ``test1`` is left whole.
|
|
13
|
+
- `:17` ``image[(test1>2)-2] eq 'ffffffff'x or test1 lt 2``: a blank slice two back, or
|
|
14
|
+
an index below 2. ``test1>2`` is IDL's maximum operator.
|
|
15
|
+
- `:18` none: unchanged.
|
|
16
|
+
- `:25-26` ``(w or 0xFF000000) xor 0xAA000000`` -> top byte ``0x55`` at ``timelines`` and
|
|
17
|
+
``timelines-1``, both read from the original ``image``. A timeline at index 0 gives
|
|
18
|
+
subscript -1, which IDL clips to 0 for an array subscript (no ``strictarrsubs``), so
|
|
19
|
+
slice 0 is written twice from ``image[0]``; numpy would wrap -1 to the last slice, so
|
|
20
|
+
it is clipped here explicitly (GDL-confirmed, ``tests/test_soda2_fix2dimage_gdl.py``).
|
|
21
|
+
|
|
22
|
+
Source: ``fix2dimage.pro`` (SODA-2); bare line references here are into that file.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
__all__ = ["fix2dimage"]
|
|
29
|
+
|
|
30
|
+
_CANDIDATES = (0xFF800000, 0, 0xFF000000, 0x2A000000) # :9
|
|
31
|
+
_BLANK = np.uint32(0xFFFFFFFF)
|
|
32
|
+
_OR = np.uint32(0xFF000000)
|
|
33
|
+
_XOR = np.uint32(0xAA000000)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def fix2dimage(image: np.ndarray) -> np.ndarray:
|
|
37
|
+
"""Port of ``fix2dimage.pro:1-28``. Returns a new ULONG array (or the input,
|
|
38
|
+
unchanged, on the two early returns, as IDL returns ``image`` itself)."""
|
|
39
|
+
img_in = np.asarray(image, dtype=np.uint32)
|
|
40
|
+
hit = np.zeros(img_in.shape, dtype=bool)
|
|
41
|
+
for c in _CANDIDATES: # :9
|
|
42
|
+
hit |= img_in == np.uint32(c)
|
|
43
|
+
test1 = np.flatnonzero(hit).astype(np.int64)
|
|
44
|
+
num = test1.size
|
|
45
|
+
if num < 5: # :10
|
|
46
|
+
return img_in
|
|
47
|
+
|
|
48
|
+
diff = test1[1:num] - test1[0:num - 1] # :13
|
|
49
|
+
good = np.flatnonzero(diff > 1) # :14
|
|
50
|
+
if good.size > 0: # :15
|
|
51
|
+
test1 = test1[good]
|
|
52
|
+
|
|
53
|
+
back = img_in[np.maximum(test1, 2) - 2] # :17
|
|
54
|
+
test2 = np.flatnonzero((back == _BLANK) | (test1 < 2))
|
|
55
|
+
if test2.size == 0: # :18
|
|
56
|
+
return img_in
|
|
57
|
+
|
|
58
|
+
timelines = test1[test2] # :20
|
|
59
|
+
img = img_in.copy() # :22
|
|
60
|
+
img[timelines] = (img_in[timelines] | _OR) ^ _XOR # :25
|
|
61
|
+
prev = np.maximum(timelines - 1, 0) # IDL clips subscript -1 to 0
|
|
62
|
+
img[prev] = (img_in[prev] | _OR) ^ _XOR # :26
|
|
63
|
+
return img
|