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,396 @@
|
|
|
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_export_ncdf_raf.pro`` (312 lines): SODA-2's NCAR-RAF/nimbus netCDF export.
|
|
4
|
+
|
|
5
|
+
Who calls it: like its sibling ``soda2_export_ncdf.pro`` (ported as
|
|
6
|
+
:mod:`arrayprobe_soda2.export_ncdf`), only the GUI (``soda2_export.pro``);
|
|
7
|
+
the driver ``soda2_process_2d.pro`` never does. Input is the same ``data``
|
|
8
|
+
structure (:class:`~arrayprobe_soda2.process_2d.ProcessData`, or a mapping
|
|
9
|
+
of IDL tag to value in declaration order, with ``op`` a mapping).
|
|
10
|
+
|
|
11
|
+
Format: ``ncdf_create(outfile[0], /clobber)`` (`:14`), no NETCDF4 keyword,
|
|
12
|
+
so ``NETCDF3_CLASSIC``.
|
|
13
|
+
|
|
14
|
+
Ported whole: dimensions (`:16-29`), global attributes (`:31-55`), the
|
|
15
|
+
three time variables (`:57-74`), the main-tag loop (`:77-237`) and the
|
|
16
|
+
bulk-variable loop (`:239-312`: LWC, IWC, IWC100, AREA, AREA100, MVD, MND,
|
|
17
|
+
NT, MVD100, MND100, NT100 from ``compute_bulk_simple``/``compute_area``,
|
|
18
|
+
always from the normalized ``data.conc1d`` whatever ``normalize`` is).
|
|
19
|
+
Refused by name: ``i100 = -1`` or ``= numbins`` (`:241-242`,
|
|
20
|
+
:class:`~arrayprobe_soda2.export_ncdf.MinsizeBinstartOutOfRange`) and a
|
|
21
|
+
``data`` whose last tag is CONC1D/SPEC1D (`:296-301`,
|
|
22
|
+
:class:`BulkAttnameCarryOver`).
|
|
23
|
+
|
|
24
|
+
Quirks preserved (bug-for-bug, never fixed):
|
|
25
|
+
|
|
26
|
+
- ``sps1`` (`:19`) is ``(1.0/data.op.rate)>1``, a FLOAT dimension size
|
|
27
|
+
that the ncdf layer truncates to a long: rate 1 -> 1, rate 0.1 -> 10,
|
|
28
|
+
rate 0.3 -> 3, rate 10 -> 1. The 3-D variables are then written with a
|
|
29
|
+
``reform(..., numbins, 1, ntime)`` value (`:186`, `:197`), so when
|
|
30
|
+
``sps1 > 1`` only the ``sps1 = 0`` slab is written and the rest keeps the
|
|
31
|
+
fill value (derived from ``ncdf_varput``'s default COUNT = the value's
|
|
32
|
+
own dimensions; pinned by GDL).
|
|
33
|
+
- Three ``Vector<n>`` dimensions are named by their length (`:22-29`), so
|
|
34
|
+
two equal lengths collide: IDL halts at the second ``ncdf_dimdef``
|
|
35
|
+
(:class:`~arrayprobe_soda2.export_ncdf.DimensionNameInUse`). The
|
|
36
|
+
area-ratio dimension (`:29`) is defined and never used.
|
|
37
|
+
- ``Time``/``base_time``/``utc_time`` are LONG variables (`:59-67`) fed
|
|
38
|
+
the float ``data.time`` (`:71-73`): the store truncates toward zero.
|
|
39
|
+
``base_time`` is ``data.time[0] + days1970*86400L`` evaluated in
|
|
40
|
+
``data.time``'s own type first, so a FLOAT time loses its seconds before
|
|
41
|
+
the truncation.
|
|
42
|
+
- An empty-string ``op`` field is replaced by ``'none'`` in the caller's
|
|
43
|
+
own ``op`` (`:53`, by reference).
|
|
44
|
+
- A main tag whose output name already exists as a variable is re-put
|
|
45
|
+
into it rather than redefined (`:223-224`): ``'C'+probetype`` with
|
|
46
|
+
probetype ``'LH'`` lands in ``CLH``.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
from __future__ import annotations
|
|
50
|
+
|
|
51
|
+
import datetime as _dt
|
|
52
|
+
from collections.abc import MutableMapping
|
|
53
|
+
from pathlib import Path
|
|
54
|
+
from typing import Any
|
|
55
|
+
|
|
56
|
+
import numpy as np
|
|
57
|
+
|
|
58
|
+
from .export_ascii import compute_bulk_simple, unnormalize
|
|
59
|
+
from .export_ncdf import (
|
|
60
|
+
DimensionNameInUse,
|
|
61
|
+
MinsizeBinstartOutOfRange,
|
|
62
|
+
_first,
|
|
63
|
+
_idl_value,
|
|
64
|
+
_min_where_ge,
|
|
65
|
+
_n_elements,
|
|
66
|
+
_put_att,
|
|
67
|
+
_tags,
|
|
68
|
+
compute_area,
|
|
69
|
+
idl_sfm2hms,
|
|
70
|
+
)
|
|
71
|
+
from .pbp_writer import _idl_hms_string, engine_attrs
|
|
72
|
+
from .spec_index import julday
|
|
73
|
+
from .timeconv import soda2_parsedate
|
|
74
|
+
|
|
75
|
+
__all__ = [
|
|
76
|
+
"BulkAttnameCarryOver",
|
|
77
|
+
"FillValueOnExistingVariable",
|
|
78
|
+
"MinsizeBinstartOutOfRange",
|
|
79
|
+
"soda2_export_ncdf_raf",
|
|
80
|
+
"sps1_size",
|
|
81
|
+
]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class BulkAttnameCarryOver(IndexError):
|
|
85
|
+
"""`:296-301`: the bulk loop never resets ``attname``, so it inherits the
|
|
86
|
+
main loop's last value (reset each pass at `:84`). When the last tag of
|
|
87
|
+
``data`` is CONC1D (nine names, `:165`) or SPEC1D (four, `:190`), the
|
|
88
|
+
loop walks past the two-field bulk ``attvalue``: ``attvalue.(2)`` at
|
|
89
|
+
`:297` is out of range, and ``attname[0] = '_FillValue'`` already pairs
|
|
90
|
+
with the long-name string at `:300` (derived, not GDL-measured). IDL
|
|
91
|
+
halts with the file open; the port raises before writing a bulk tag."""
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class FillValueOnExistingVariable(NotImplementedError):
|
|
95
|
+
"""`:223-229`: a CONC1D/SPEC1D output name that repeats an existing
|
|
96
|
+
variable re-puts ``_FillValue`` on it. netCDF4-python refuses a
|
|
97
|
+
``_FillValue`` after creation, so this path is refused by name."""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
# `:91-152`, `:200-218` -- (long_name, units, dimension) per simple tag.
|
|
101
|
+
_MAIN_SIMPLE: dict[str, tuple[str, str, str]] = {
|
|
102
|
+
"SA": ("Sample Area", "m2", "size"),
|
|
103
|
+
"COUNT_ACCEPTED": ("Count Accepted", "#", "time"),
|
|
104
|
+
"TAS": ("True Air speed used", "m/s", "time"),
|
|
105
|
+
"CLH": ("CU Laser Hygrometer, Condensed Water Content", "g/m3", "time"),
|
|
106
|
+
"LAT": ("Latitude", "degrees", "time"),
|
|
107
|
+
"LON": ("Longitude", "degrees", "time"),
|
|
108
|
+
"GALT": ("GPS Altitude", "meters", "time"),
|
|
109
|
+
"T": ("Temperature", "degrees Celsius", "time"),
|
|
110
|
+
"PRES": ("Pressure", "hPa", "time"),
|
|
111
|
+
"ACTIVETIME": ("Probe activity time", "s", "time"),
|
|
112
|
+
"CDP_NT": ("Total number concentration from the CDP", "#/cm3", "time"),
|
|
113
|
+
"CDP_LWC": ("Total LWC derived from the CDP", "g/m3", "time"),
|
|
114
|
+
"CDP_MEAND": ("Mean diameter from the CDP", "microns", "time"),
|
|
115
|
+
"CONCU": ("UHSAS Total Concentration", "#/cm3", "time"),
|
|
116
|
+
"CONCU100": ("UHSAS Concentration, 0.1 micron and bigger", "#/cm3", "time"),
|
|
117
|
+
"CONCU500": ("UHSAS Concentration, 0.5 microns and bigger", "#/cm3", "time"),
|
|
118
|
+
"W": ("GPS-Corrected Wind Vector, Vertical Gust Component", "m/s", "time"),
|
|
119
|
+
"V": ("GPS-Corrected Wind Vector, North Component", "m/s", "time"),
|
|
120
|
+
"U": ("GPS-Corrected Wind Vector, East Component", "m/s", "time"),
|
|
121
|
+
"WSC": ("GPS-Corrected Horizontal Wind Speed", "m/s", "time"),
|
|
122
|
+
"INTSPEC_ALL": ("Particle Count Per Interarrival Bin, All Particles", "#", "int2"),
|
|
123
|
+
"INTSPEC_ACCEPTED": ("Particle Count Per Interarrival Bin, Accepted Particles", "#",
|
|
124
|
+
"int2"),
|
|
125
|
+
"MIDBINS": ("Size Bin Mid-points", "um", "size"),
|
|
126
|
+
"INTMIDBINS": ("Interarrival Bin Mid-points", "s", "int"),
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# `:256-289` -- (long_name, units) per bulk tag; all on ("Time",) (`:250`).
|
|
131
|
+
_BULK: dict[str, tuple[str, str]] = {
|
|
132
|
+
"LWC": ("Liquid Water Content", "gram/m3"),
|
|
133
|
+
"IWC": ("Ice Water Content, All Particles", "gram/m3"),
|
|
134
|
+
"IWC100": ("Ice Water Content, Particles Larger than 100um in Diameter", "gram/m3"),
|
|
135
|
+
"AREA": ("Projected Particle Area, All Particles", "1/m"),
|
|
136
|
+
"AREA100": ("Projected Particle Area, Particles Larger than 100um in Diameter", "1/m"),
|
|
137
|
+
"MVD": ("Median Volume Diameter", "um"),
|
|
138
|
+
"MND": ("Mean Diameter", "um"),
|
|
139
|
+
"NT": ("Total Number Concentration, All Particles", "#/m3"),
|
|
140
|
+
"MVD100": ("Median Volume Diameter, Particles Larger than 100um in Diameter", "um"),
|
|
141
|
+
"MND100": ("Mean Diameter, Particles Larger than 100um in Diameter", "um"),
|
|
142
|
+
"NT100": ("Total Number Concentration, Particles Larger than 100um in Diameter",
|
|
143
|
+
"#/m3"),
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def sps1_size(rate: Any) -> int:
|
|
148
|
+
"""`:19` ``(1.0/data.op.rate)>1``: FLOAT (DOUBLE for a DOUBLE rate),
|
|
149
|
+
truncated to a long dimension size."""
|
|
150
|
+
r = _first(_idl_value(rate))
|
|
151
|
+
if isinstance(r, np.float64):
|
|
152
|
+
q: float = float(np.float64(1.0) / r)
|
|
153
|
+
else:
|
|
154
|
+
q = float(np.float32(1.0) / np.float32(r))
|
|
155
|
+
return int(max(q, 1.0))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _to_long(x: np.ndarray) -> np.ndarray:
|
|
159
|
+
"""``ncdf_varput`` of a float into a LONG variable: truncation toward 0."""
|
|
160
|
+
arr = np.asarray(x)
|
|
161
|
+
if arr.dtype.kind == "f":
|
|
162
|
+
arr = np.trunc(arr)
|
|
163
|
+
return arr.astype(np.int32)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def soda2_export_ncdf_raf(
|
|
167
|
+
data: Any,
|
|
168
|
+
outfile: str,
|
|
169
|
+
*,
|
|
170
|
+
normalize: int = 1,
|
|
171
|
+
suffix: str = "",
|
|
172
|
+
legacybinning: int = 0,
|
|
173
|
+
date_created: str | None = None,
|
|
174
|
+
stamp_profile: str | None = None,
|
|
175
|
+
) -> str:
|
|
176
|
+
"""``soda2_export_ncdf_raf.pro``. Keywords as IDL's (`:7-9` defaults).
|
|
177
|
+
``date_created`` overrides ``systime()`` (`:47`, non-deterministic)."""
|
|
178
|
+
import netCDF4
|
|
179
|
+
|
|
180
|
+
normalize = int(normalize)
|
|
181
|
+
legacybinning = int(legacybinning)
|
|
182
|
+
tags = _tags(data)
|
|
183
|
+
op: MutableMapping[str, Any] = tags["OP"]
|
|
184
|
+
opl = {str(k).lower(): k for k in op}
|
|
185
|
+
opnames = [str(k).upper() for k in op]
|
|
186
|
+
|
|
187
|
+
def opget(name: str) -> Any:
|
|
188
|
+
return op[opl[name]]
|
|
189
|
+
|
|
190
|
+
time = np.asarray(tags["TIME"])
|
|
191
|
+
ntimes = int(time.size)
|
|
192
|
+
endbins = _idl_value(opget("endbins"))
|
|
193
|
+
|
|
194
|
+
Path(outfile).unlink(missing_ok=True) # /clobber
|
|
195
|
+
ds = netCDF4.Dataset(outfile, "w", format="NETCDF3_CLASSIC")
|
|
196
|
+
try:
|
|
197
|
+
ds.createDimension("Time", ntimes) # `:17`
|
|
198
|
+
nsps = sps1_size(opget("rate")) # `:19`
|
|
199
|
+
ds.createDimension("sps1", nsps)
|
|
200
|
+
|
|
201
|
+
def dimdef(n: int, line: str) -> str:
|
|
202
|
+
name = f"Vector{n}"
|
|
203
|
+
if name in ds.dimensions:
|
|
204
|
+
raise DimensionNameInUse(
|
|
205
|
+
f"soda2_export_ncdf_raf.pro:{line}: NCDF_DIMDEF: (NC_ERROR=-42) -- "
|
|
206
|
+
f"dimension {name!r} is already defined")
|
|
207
|
+
ds.createDimension(name, n)
|
|
208
|
+
return name
|
|
209
|
+
|
|
210
|
+
ne = _n_elements(endbins)
|
|
211
|
+
numbins = ne if legacybinning else ne - 1 # `:21`
|
|
212
|
+
dim_size = dimdef(numbins, "23")
|
|
213
|
+
dim_int = dimdef(_n_elements(tags["INTMIDBINS"]), "26")
|
|
214
|
+
dimdef(_n_elements(opget("arendbins")) - 1, "29") # defined, never used
|
|
215
|
+
|
|
216
|
+
date = soda2_parsedate(str(opget("date"))) # `:34-36`
|
|
217
|
+
days1970 = int(date.julday) - julday(1, 1, 1970)
|
|
218
|
+
flightdate = f"{date.month}/{date.day}/{date.year}"
|
|
219
|
+
starttime = _idl_hms_string(idl_sfm2hms(float(np.min(time)))) # `:38-42`
|
|
220
|
+
stoptime = _idl_hms_string(idl_sfm2hms(float(np.max(time))))
|
|
221
|
+
|
|
222
|
+
# `:45-55` -- global attributes.
|
|
223
|
+
ds.setncattr("Source", "SODA-2 OAP Processing Software")
|
|
224
|
+
ds.setncattr("Conventions", "NCAR-RAF/nimbus")
|
|
225
|
+
ds.setncattr("DateCreated", date_created if date_created is not None
|
|
226
|
+
else _dt.datetime.now().ctime())
|
|
227
|
+
ds.setncattr("FlightDate", flightdate)
|
|
228
|
+
ds.setncattr("DateProcessed", str(tags["DATE_PROCESSED"]))
|
|
229
|
+
ds.setncattr("TimeInterval", f"{starttime}-{stoptime}")
|
|
230
|
+
for key, name in zip(list(op.keys()), opnames, strict=True):
|
|
231
|
+
first = _first(op[key])
|
|
232
|
+
if isinstance(first, str) and first == "":
|
|
233
|
+
# `:53` -- written into the caller's own op (by reference).
|
|
234
|
+
v = op[key]
|
|
235
|
+
if isinstance(v, str):
|
|
236
|
+
op[key] = "none"
|
|
237
|
+
else:
|
|
238
|
+
arr = np.asarray(v).astype(object)
|
|
239
|
+
arr.ravel()[0] = "none"
|
|
240
|
+
op[key] = arr.astype(str)
|
|
241
|
+
first = "none"
|
|
242
|
+
_put_att(ds, name, first, long_int=False)
|
|
243
|
+
# In-file provenance (author, 2026-09-24) -- not IDL output; see pbp_writer.engine_attrs.
|
|
244
|
+
for name, value in engine_attrs(stamp_profile).items():
|
|
245
|
+
ds.setncattr(name, value)
|
|
246
|
+
|
|
247
|
+
# `:57-68` -- the three LONG time variables.
|
|
248
|
+
vt = ds.createVariable("Time", "i4", ("Time",))
|
|
249
|
+
vt.setncattr("long_name", "Time")
|
|
250
|
+
vt.setncattr("units", f"seconds since {date.year}-{date.month}-{date.day} "
|
|
251
|
+
f"{starttime} +0000")
|
|
252
|
+
vb = ds.createVariable("base_time", "i4", ())
|
|
253
|
+
vb.setncattr("long_name", "Base time")
|
|
254
|
+
vb.setncattr("units", "seconds since 01/01/1970")
|
|
255
|
+
vu = ds.createVariable("utc_time", "i4", ("Time",))
|
|
256
|
+
vu.setncattr("long_name", "UTC time")
|
|
257
|
+
vu.setncattr("units", "seconds from midnight of start date")
|
|
258
|
+
# `:71-73`
|
|
259
|
+
vu[:] = _to_long(time)
|
|
260
|
+
t0 = time.ravel()[0]
|
|
261
|
+
base: Any
|
|
262
|
+
if time.dtype == np.float32:
|
|
263
|
+
base = np.float32(t0) + np.float32(days1970 * 86400)
|
|
264
|
+
elif time.dtype.kind == "f":
|
|
265
|
+
base = np.float64(t0) + np.float64(days1970 * 86400)
|
|
266
|
+
else:
|
|
267
|
+
base = np.int64(t0) + np.int64(days1970 * 86400)
|
|
268
|
+
vb.assignValue(_to_long(np.asarray(base))[()])
|
|
269
|
+
vt[:] = _to_long(time - t0)
|
|
270
|
+
|
|
271
|
+
# `:77-237` -- main structure tags.
|
|
272
|
+
ncdims = {"time": ("Time",), "size": (dim_size,), "int": (dim_int,),
|
|
273
|
+
"int2": ("Time", dim_int), "3d": ("Time", "sps1", dim_size)}
|
|
274
|
+
probetype = str(_first(opget("probetype")))
|
|
275
|
+
for tag in list(tags):
|
|
276
|
+
value = tags[tag]
|
|
277
|
+
tagname = tag + suffix # `:88`
|
|
278
|
+
atts: list[tuple[str, Any]]
|
|
279
|
+
if tag in _MAIN_SIMPLE:
|
|
280
|
+
ln, un, dkey = _MAIN_SIMPLE[tag]
|
|
281
|
+
atts = [("long_name", ln), ("units", un)]
|
|
282
|
+
current = np.asarray(value)
|
|
283
|
+
if tag in ("SA", "MIDBINS") and legacybinning == 1:
|
|
284
|
+
# `:94`, `:213` -- [0, data.sa]: INT 0 promoted to the array's type.
|
|
285
|
+
current = np.concatenate([np.zeros(1, dtype=current.dtype), current])
|
|
286
|
+
elif tag in ("CONC1D", "SPEC1D"):
|
|
287
|
+
dkey = "3d"
|
|
288
|
+
if tag == "CONC1D": # `:153-188`
|
|
289
|
+
if legacybinning == 1:
|
|
290
|
+
note = "CellSizes are upper bin limits as particle size"
|
|
291
|
+
firstbin = np.int16(1)
|
|
292
|
+
lastbin = np.int16(_n_elements(tags["MIDBINS"]))
|
|
293
|
+
else:
|
|
294
|
+
note = "CellSizes are lower bin limits as particle size"
|
|
295
|
+
firstbin = np.int16(0)
|
|
296
|
+
lastbin = np.int16(_n_elements(tags["MIDBINS"]) - 1)
|
|
297
|
+
if normalize == 1:
|
|
298
|
+
ln = "Particle Concentration Per Channel, Normalized by Bin Width"
|
|
299
|
+
un = "#/m4"
|
|
300
|
+
src = np.asarray(value)
|
|
301
|
+
elif normalize == 0:
|
|
302
|
+
ln, un = "Particle Concentration Per Channel", "#/L"
|
|
303
|
+
un_m3 = unnormalize(np.asarray(value), np.asarray(endbins))
|
|
304
|
+
src = un_m3 / np.asarray(np.float32(1e3), dtype=un_m3.dtype) # `:179`
|
|
305
|
+
else:
|
|
306
|
+
# IDL: neither branch runs, attvalue stays a 2-string array and
|
|
307
|
+
# `attvalue.(k)` errors at `:226`.
|
|
308
|
+
raise ValueError(
|
|
309
|
+
"soda2_export_ncdf_raf.pro:166-180: normalize must be 0 or 1")
|
|
310
|
+
atts = [("_FillValue", np.float32(-32767.0)), ("long_name", ln),
|
|
311
|
+
("units", un), ("FirstBin", firstbin), ("LastBin", lastbin),
|
|
312
|
+
("CellSizes", endbins), ("CellSizeUnits", "micrometers"),
|
|
313
|
+
("Category", "PMS Probe"), ("CellSizeNote", note)]
|
|
314
|
+
tagname = "C" + probetype + suffix # `:187`
|
|
315
|
+
else: # `:189-199`
|
|
316
|
+
src = np.asarray(value)
|
|
317
|
+
atts = [("_FillValue", np.float32(-32767.0)),
|
|
318
|
+
("long_name", "Particle Count Per Size Bin"),
|
|
319
|
+
("units", "count"), ("Category", "PMS Probe")]
|
|
320
|
+
tagname = "A" + probetype + suffix # `:198`
|
|
321
|
+
# `:184-186` -- fltarr(ntime, numbins), legacy pads bin 0.
|
|
322
|
+
grid = np.zeros((ntimes, numbins), dtype=np.float32)
|
|
323
|
+
if legacybinning:
|
|
324
|
+
grid[:, 1:] = src
|
|
325
|
+
else:
|
|
326
|
+
grid[:, :] = src
|
|
327
|
+
current = grid.reshape(ntimes, 1, numbins)
|
|
328
|
+
else:
|
|
329
|
+
continue # ELSE: skiptag (`:219`)
|
|
330
|
+
|
|
331
|
+
# `:222-235`
|
|
332
|
+
fill = None
|
|
333
|
+
if atts[0][0] == "_FillValue":
|
|
334
|
+
fill = atts[0][1]
|
|
335
|
+
if tagname in ds.variables:
|
|
336
|
+
var = ds.variables[tagname]
|
|
337
|
+
if fill is not None:
|
|
338
|
+
raise FillValueOnExistingVariable(
|
|
339
|
+
f"soda2_export_ncdf_raf.pro:223-229: {tagname!r} already exists")
|
|
340
|
+
else:
|
|
341
|
+
var = ds.createVariable(tagname, "f4", ncdims[dkey], fill_value=fill)
|
|
342
|
+
for aname, aval in atts:
|
|
343
|
+
if aname == "_FillValue":
|
|
344
|
+
continue # set at creation (netCDF4-python's rule)
|
|
345
|
+
# `:226-227` -- an INT attribute goes out /LONG.
|
|
346
|
+
_put_att(var, aname, aval, long_int=True)
|
|
347
|
+
# `:234` currentdata*1.0 into a FLOAT variable.
|
|
348
|
+
arr = np.asarray(current).astype(np.float32)
|
|
349
|
+
if dkey == "3d":
|
|
350
|
+
var[:, 0:1, :] = arr
|
|
351
|
+
else:
|
|
352
|
+
var[:] = arr
|
|
353
|
+
# `:84` resets attname on every main-loop pass (skipped tags too), so
|
|
354
|
+
# the bulk loop below inherits the LAST tag's list.
|
|
355
|
+
last_tag = list(tags)[-1] if tags else ""
|
|
356
|
+
|
|
357
|
+
# `:239-245` -- bulk structure: compute_bulk_simple's tags, then the
|
|
358
|
+
# 100-um subset and the two areas, in create_struct order.
|
|
359
|
+
eb = np.asarray(endbins, dtype=np.float32)
|
|
360
|
+
conc1d = tags["CONC1D"]
|
|
361
|
+
bulkall = compute_bulk_simple(conc1d, eb, binstart=0) # `:240`
|
|
362
|
+
i100 = _min_where_ge(eb, 100) # `:241`
|
|
363
|
+
nb = len(eb) - 1
|
|
364
|
+
if i100 < 0 or i100 > nb - 1:
|
|
365
|
+
raise MinsizeBinstartOutOfRange(
|
|
366
|
+
f"soda2_export_ncdf_raf.pro:242: binstart={i100} for {nb} bins "
|
|
367
|
+
f"(endbins up to {float(eb[-1])}) -- compute_bulk_simple halts")
|
|
368
|
+
bulk100 = compute_bulk_simple(conc1d, eb, binstart=i100) # `:242`
|
|
369
|
+
area = compute_area(tags) # `:243`
|
|
370
|
+
area100 = compute_area(tags, binstart=i100) # `:244`
|
|
371
|
+
bulk: dict[str, Any] = {k.upper(): v for k, v in bulkall.items()}
|
|
372
|
+
bulk.update({"NT100": bulk100["nt"], "MND100": bulk100["mnd"],
|
|
373
|
+
"MVD100": bulk100["mvd"], "IWC100": bulk100["iwc"],
|
|
374
|
+
"AREA": area["area"], "AREA100": area100["area"]})
|
|
375
|
+
|
|
376
|
+
if last_tag in ("CONC1D", "SPEC1D"):
|
|
377
|
+
raise BulkAttnameCarryOver(
|
|
378
|
+
f"soda2_export_ncdf_raf.pro:296-301: the last data tag is {last_tag!r}, "
|
|
379
|
+
"so attname has more entries than the bulk attvalue's two fields")
|
|
380
|
+
|
|
381
|
+
# `:247-308`
|
|
382
|
+
for tag, value in bulk.items():
|
|
383
|
+
if tag not in _BULK:
|
|
384
|
+
continue # ELSE: skiptag (`:290`)
|
|
385
|
+
tagname = tag + suffix # `:254`
|
|
386
|
+
ln, un = _BULK[tag]
|
|
387
|
+
if tagname in ds.variables: # `:294`
|
|
388
|
+
var = ds.variables[tagname]
|
|
389
|
+
else:
|
|
390
|
+
var = ds.createVariable(tagname, "f4", ("Time",)) # `:295`
|
|
391
|
+
var.setncattr("long_name", ln) # `:296-302`
|
|
392
|
+
var.setncattr("units", un)
|
|
393
|
+
var[:] = np.asarray(value).astype(np.float32) # `:305` currentdata*1.0
|
|
394
|
+
finally:
|
|
395
|
+
ds.close() # `:311`
|
|
396
|
+
return str(outfile)
|
|
@@ -0,0 +1,161 @@
|
|
|
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
|
+
"""``fillholes.pro`` -- fill interior holes in a binary particle image.
|
|
4
|
+
|
|
5
|
+
Source: ``SODA2/abansemer-soda2-afcea15/fillholes.pro`` (22 lines). Called
|
|
6
|
+
at ``soda2_processbuffer.pro:714`` on ``roi`` (``bitimage[fp:lp,
|
|
7
|
+
startline:stopline]``, IDL dims ``[ndiodes, roilen]``);
|
|
8
|
+
``area_filled = total(roifilled)`` (``:715``) feeds
|
|
9
|
+
``poisson_spot_correct`` (``:716``, ``arrayprobe_soda2.poisson_spot_correct``)
|
|
10
|
+
and ``voidarea`` (``:719``). Reaches output.
|
|
11
|
+
|
|
12
|
+
::
|
|
13
|
+
|
|
14
|
+
FUNCTION fillholes, img ; :1
|
|
15
|
+
img = byte(img) ; :5
|
|
16
|
+
s = size(img) ; :7
|
|
17
|
+
IF (s[1] lt 4) or (s[2] lt 4) THEN return, img ; :8
|
|
18
|
+
reverse = byte(label_blobs(img xor 1b)) ; :9
|
|
19
|
+
edges = reverse
|
|
20
|
+
f = [transpose(edges[0,*]), edges[*,0],
|
|
21
|
+
transpose(edges[s[1]-1,*]), edges[*,s[2]-1]] ; :11-12
|
|
22
|
+
f = f[sort(f)] ; :13
|
|
23
|
+
edge_labels = f[uniq(f)] ; :14
|
|
24
|
+
FOR i=0,n_elements(edge_labels)-1 DO
|
|
25
|
+
reverse[where(reverse eq edge_labels[i])] = 0b ; :16-18
|
|
26
|
+
newimg = img or (reverse<1b) ; :20
|
|
27
|
+
return, newimg ; :21
|
|
28
|
+
END
|
|
29
|
+
|
|
30
|
+
``:7`` ``size(img)`` (no ``/dim``) returns the IDL *dimension-slots* array:
|
|
31
|
+
``s[1]`` is the first dimension size, ``s[2]`` the second -- **not**
|
|
32
|
+
``size(/dim)``. A 1-slice ROI indexes down to a 1-D IDL array, whose
|
|
33
|
+
``size()`` puts the *type code* in slot 2 (BYTE = 1), so it too is
|
|
34
|
+
``lt 4`` and returned unchanged -- the same early return, reached through
|
|
35
|
+
a different field. Ported on this package's transposed ``(roilen,
|
|
36
|
+
ndiodes)`` array as ``if roilen < 4 or ndiodes < 4: return
|
|
37
|
+
img.astype(uint8)``.
|
|
38
|
+
|
|
39
|
+
**``:9`` -- the BYTE wrap (finding S4-u).** ``label_blobs(img xor 1b)`` is
|
|
40
|
+
called with **no keywords**, i.e. ``dilatelength=0, integer=0``: 4-connected
|
|
41
|
+
``label_region`` on a 1-pixel zero-padded copy of the *negative* image
|
|
42
|
+
(``label_blobs.pro:12-28``), cropped, then cast to **BYTE** at
|
|
43
|
+
``label_blobs.pro:28`` -- and ``fillholes.pro:9`` casts the (already-byte)
|
|
44
|
+
result to byte again. An ROI whose negative decomposes into more than 255
|
|
45
|
+
4-connected regions **wraps labels modulo 256**: region 256 becomes label
|
|
46
|
+
0 (the value ``label_blobs`` also uses for "no negative pixel here" is
|
|
47
|
+
never assigned by ``label_region`` itself, but 0 is also what a removed
|
|
48
|
+
edge blob is zeroed to at ``:18``, so a wrapped 256th region is
|
|
49
|
+
indistinguishable from "not part of any blob" and is never filled);
|
|
50
|
+
region 257 shares label 1's fate (filled if label 1 survives the edge
|
|
51
|
+
scan, removed if it does not). See ``label_blobs.py`` for the
|
|
52
|
+
labeller itself -- this module cites ``label_blobs.pro:28`` as the line the
|
|
53
|
+
wrap is reached through; it is a ``fillholes`` finding (S4-u), not a
|
|
54
|
+
duplicate of the geometry port's own finding about ``label_blobs.pro:29``'s BYTE return
|
|
55
|
+
type.
|
|
56
|
+
|
|
57
|
+
**This module lazily imports ``label_blobs``** (ported
|
|
58
|
+
in parallel and not present in this worktree before the merge) so that
|
|
59
|
+
importing ``fillholes`` itself never fails: ``from .label_blobs import
|
|
60
|
+
label_blobs`` is the first statement inside :func:`fillholes`, called with
|
|
61
|
+
**defaults only** (``label_blobs(neg)``), matching ``fillholes.pro:9``'s
|
|
62
|
+
keyword-less call exactly. ``label_blobs.pro:28``'s own BYTE cast is
|
|
63
|
+
the labeller's responsibility under ``integer=False``; ``fillholes.pro:9``'s own
|
|
64
|
+
``byte()`` is reproduced here as an explicit ``.astype(np.uint8)`` -- a
|
|
65
|
+
no-op on an already-uint8 input, kept so the line stays visible.
|
|
66
|
+
|
|
67
|
+
**Border-vector mapping.** IDL indexes ``[ndiodes, roilen]``; this
|
|
68
|
+
package's array is ``(roilen, ndiodes)``. So ``edges[0,*]`` (IDL: all of
|
|
69
|
+
diode-index 0, every slice) is this array's **column 0**, ``edges[*,0]``
|
|
70
|
+
(IDL: slice 0, every diode) is this array's **row 0**, and so on for the
|
|
71
|
+
opposite edges. ``np.unique`` replaces ``sort`` + ``uniq``: both compute
|
|
72
|
+
the *set* of distinct edge labels, and removal at ``:16-18`` is by label
|
|
73
|
+
identity, so the order ``uniq`` happens to return in is irrelevant here.
|
|
74
|
+
|
|
75
|
+
Validated against GDL by ``tests/test_soda2_fillholes.py``; bank at
|
|
76
|
+
``gdl_oracle/run_soda2_fillholes_bank.py``.
|
|
77
|
+
"""
|
|
78
|
+
from __future__ import annotations
|
|
79
|
+
|
|
80
|
+
import numpy as np
|
|
81
|
+
|
|
82
|
+
__all__ = ["fillholes"]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _labelled_negative(img: np.ndarray, *, jit: bool = False) -> np.ndarray:
|
|
86
|
+
"""``byte(label_blobs(img xor 1b))`` -- ``fillholes.pro:9`` -- exposed
|
|
87
|
+
separately so the BYTE-wrap case (S4-u) is assertable directly,
|
|
88
|
+
whichever labeller (real or test stub) is behind it.
|
|
89
|
+
|
|
90
|
+
**Axis convention mismatch, found at the round-5 merge.**
|
|
91
|
+
``label_blobs`` (``label_blobs.py``) assumes its caller passes
|
|
92
|
+
an array with axis 0 = diode, axis 1 = slice (IDL-native, matching
|
|
93
|
+
``label_blobs.pro``'s own ``img[ndiodes, roilen]`` and confirmed
|
|
94
|
+
against GDL's ``label_region`` raster order on the label_blobs bank:
|
|
95
|
+
``gdl_oracle/run_soda2_label_blobs_bank.py`` builds its ``img`` with
|
|
96
|
+
"rows = diodes (axis0/x), cols = slices (axis1/y)"). This module's own
|
|
97
|
+
``img``/``arr`` is on this *package's* transposed convention -- axis 0 =
|
|
98
|
+
slice (``roilen``), axis 1 = diode (``ndiodes``), per the module
|
|
99
|
+
docstring's border-vector mapping. Passing ``arr`` straight through
|
|
100
|
+
would scan slice-fastest instead of diode-fastest; the two scan orders
|
|
101
|
+
agree on *which* pixels are connected (so every case below the 256-label
|
|
102
|
+
wrap matched anyway) but disagree on *label numbering order*, which only
|
|
103
|
+
matters once the label count crosses the 255/256 byte-wrap boundary
|
|
104
|
+
(S4-u) -- caught by ``tests/test_soda2_fillholes.py``'s ``many_holes``
|
|
105
|
+
case (400 holes) against the GDL golden. Fixed by transposing into
|
|
106
|
+
label_blobs's expected axis order on the way in and back out."""
|
|
107
|
+
from .label_blobs import label_blobs # lazy import
|
|
108
|
+
|
|
109
|
+
neg = np.asarray(img, dtype=np.uint8) ^ np.uint8(1)
|
|
110
|
+
# neg is (roilen, ndiodes); label_blobs wants (ndiodes, roilen).
|
|
111
|
+
labelled = np.asarray(label_blobs(neg.T, jit=jit))
|
|
112
|
+
return labelled.T.astype(np.uint8)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def fillholes(img: np.ndarray, *, jit: bool = False) -> np.ndarray:
|
|
116
|
+
"""``newimg = fillholes(img)``.
|
|
117
|
+
|
|
118
|
+
Source: ``fillholes.pro`` (SODA-2).
|
|
119
|
+
|
|
120
|
+
``img`` is a 2-D binary (0/1) array on this package's ``(roilen,
|
|
121
|
+
ndiodes)`` convention (IDL: ``[ndiodes, roilen]``). Returns a uint8
|
|
122
|
+
array of the same shape.
|
|
123
|
+
"""
|
|
124
|
+
arr = np.asarray(img, dtype=np.uint8)
|
|
125
|
+
|
|
126
|
+
# `:7-8` -- `size(img)` dimension-slot early return; a 1-slice ROI
|
|
127
|
+
# indexes to 1-D in IDL and hits this through the type-code slot.
|
|
128
|
+
if arr.ndim < 2:
|
|
129
|
+
return arr.astype(np.uint8)
|
|
130
|
+
roilen, ndiodes = arr.shape
|
|
131
|
+
if roilen < 4 or ndiodes < 4:
|
|
132
|
+
return arr.astype(np.uint8)
|
|
133
|
+
|
|
134
|
+
# `:9`.
|
|
135
|
+
reverse = _labelled_negative(arr, jit=jit)
|
|
136
|
+
|
|
137
|
+
# `:11-12` -- border vectors. IDL `edges[0,*]` -> column 0 here;
|
|
138
|
+
# `edges[*,0]` -> row 0; `edges[s[1]-1,*]` -> last column;
|
|
139
|
+
# `edges[*,s[2]-1]` -> last row.
|
|
140
|
+
edges = np.concatenate([
|
|
141
|
+
reverse[:, 0],
|
|
142
|
+
reverse[0, :],
|
|
143
|
+
reverse[:, -1],
|
|
144
|
+
reverse[-1, :],
|
|
145
|
+
])
|
|
146
|
+
|
|
147
|
+
# `:13-14` -- `sort`+`uniq` gives the set of distinct edge labels;
|
|
148
|
+
# `np.unique` gives the same set (order is irrelevant, `:16-18` removes
|
|
149
|
+
# by identity).
|
|
150
|
+
edge_labels = np.unique(edges)
|
|
151
|
+
|
|
152
|
+
# `:16-18` -- zero every blob carrying an edge label. `where` at `:17`
|
|
153
|
+
# can never be empty: every edge label was read from `reverse` itself.
|
|
154
|
+
mask = np.isin(reverse, edge_labels)
|
|
155
|
+
reverse = np.where(mask, np.uint8(0), reverse)
|
|
156
|
+
|
|
157
|
+
# `:20` -- `img or (reverse<1b)`; `<` is IDL's binary MIN, so
|
|
158
|
+
# `reverse<1b` clips every surviving nonzero label to 1.
|
|
159
|
+
surviving_holes = np.minimum(reverse, np.uint8(1))
|
|
160
|
+
newimg = (arr.astype(bool) | surviving_holes.astype(bool)).astype(np.uint8)
|
|
161
|
+
return newimg
|
|
@@ -0,0 +1,105 @@
|
|
|
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
|
+
"""``find_radius.pro`` -- Goldman's circumradius, and the degenerate value
|
|
4
|
+
``min_circle_fast`` depends on.
|
|
5
|
+
|
|
6
|
+
The radius and centre of the circle through three points, from the "Triangles"
|
|
7
|
+
article in Graphics Gems. `min_circle_fast` calls it for its three-point case
|
|
8
|
+
and then tests ``IF finite(circ.r) eq 0`` — so what this routine returns for a
|
|
9
|
+
degenerate triangle is not an edge case, it is the branch condition of its only
|
|
10
|
+
caller.
|
|
11
|
+
|
|
12
|
+
::
|
|
13
|
+
|
|
14
|
+
d1 = (p3-p1).(p2-p1) d2 = (p3-p2).(p1-p2) d3 = (p1-p3).(p2-p3)
|
|
15
|
+
c = d2*d3 + d3*d1 + d1*d2
|
|
16
|
+
r = 0.5*sqrt( (d1+d2)*(d2+d3)*(d3+d1) / c )
|
|
17
|
+
cent = ((c2+c3)*p1 + (c3+c1)*p2 + (c1+c2)*p3) / (2*c)
|
|
18
|
+
|
|
19
|
+
**Two degenerate regimes, and they are not the same.** Measured under GDL:
|
|
20
|
+
|
|
21
|
+
========================= ========== ====================
|
|
22
|
+
input ``r`` ``center``
|
|
23
|
+
========================= ========== ====================
|
|
24
|
+
collinear, points distinct ``+inf`` ``(nan, nan)``
|
|
25
|
+
nearly collinear (1e-12) ``+inf`` ``(nan, +inf)``
|
|
26
|
+
two points coincident ``nan`` ``(nan, nan)``
|
|
27
|
+
all three coincident ``nan`` ``(nan, nan)``
|
|
28
|
+
========================= ========== ====================
|
|
29
|
+
|
|
30
|
+
**The caller's comment about this is wrong.** ``min_circle_fast.pro`` introduces
|
|
31
|
+
its fallback with *"Catch and correct error which can occur if all points are on
|
|
32
|
+
a very long straight line"* and *"Radius will be NaN in this case"*. Measured, a
|
|
33
|
+
collinear triple gives **+inf**, not NaN. The code is unaffected — IDL's
|
|
34
|
+
``finite()`` is false for both — so this is a comment that misdescribes the value
|
|
35
|
+
it catches, not a defect. It is reported because a reader trusting the comment
|
|
36
|
+
would write a NaN-only guard and silently lose the collinear case.
|
|
37
|
+
|
|
38
|
+
Note the mixed result for the nearly-collinear triple: ``center`` comes back
|
|
39
|
+
``(nan, +inf)``, one coordinate of each kind. Any caller testing only
|
|
40
|
+
``center[0]`` would reach a different conclusion from one testing ``center[1]``.
|
|
41
|
+
|
|
42
|
+
**A stale comment in the source itself**, worth knowing when reading it: the
|
|
43
|
+
centre is computed in a block dated ``3-31-03`` sitting directly beneath a
|
|
44
|
+
comment saying *"Formula for coordinates of center is given in reference, but is
|
|
45
|
+
not computed here"*.
|
|
46
|
+
|
|
47
|
+
Provenance: ``SODA2/abansemer-soda2-afcea15/find_radius.pro`` (whole file).
|
|
48
|
+
IDL's ``##`` on two 2-vectors yields the 1×1 matrix product, i.e. the dot
|
|
49
|
+
product, which is what ``d1``/``d2``/``d3`` are. Validated against GDL by
|
|
50
|
+
``tests/test_soda2_find_radius.py``.
|
|
51
|
+
"""
|
|
52
|
+
from __future__ import annotations
|
|
53
|
+
|
|
54
|
+
from dataclasses import dataclass
|
|
55
|
+
|
|
56
|
+
import numpy as np
|
|
57
|
+
from numpy.typing import ArrayLike
|
|
58
|
+
|
|
59
|
+
__all__ = ["Circle", "find_radius"]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True)
|
|
63
|
+
class Circle:
|
|
64
|
+
"""``{r: ..., center: ...}`` -- the IDL anonymous structure this returns.
|
|
65
|
+
|
|
66
|
+
Source: the return structure of ``find_radius.pro`` (SODA-2).
|
|
67
|
+
|
|
68
|
+
``r`` is a **radius**; note that ``min_circle_fast`` doubles it on the way
|
|
69
|
+
out and its own return field is named ``diam``.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
r: float
|
|
73
|
+
center: np.ndarray
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def find_radius(p1: ArrayLike, p2: ArrayLike, p3: ArrayLike) -> Circle:
|
|
77
|
+
"""``find_radius(p1, p2, p3)`` -- circumradius and centre of three points.
|
|
78
|
+
|
|
79
|
+
Source: ``find_radius.pro`` (SODA-2).
|
|
80
|
+
|
|
81
|
+
Each point is 2-element ``[x, y]``. Degenerate inputs return ``inf`` or
|
|
82
|
+
``nan`` rather than raising, exactly as the IDL does — see the module
|
|
83
|
+
docstring for the four measured regimes, and note that the caller's own
|
|
84
|
+
comment about which one occurs is wrong.
|
|
85
|
+
"""
|
|
86
|
+
a = np.asarray(p1, dtype=np.float64).ravel()
|
|
87
|
+
b = np.asarray(p2, dtype=np.float64).ravel()
|
|
88
|
+
c_ = np.asarray(p3, dtype=np.float64).ravel()
|
|
89
|
+
|
|
90
|
+
# np.float64, deliberately NOT Python float: `x / 0.0` on a Python float
|
|
91
|
+
# raises ZeroDivisionError, where IDL -- and numpy -- yield inf or nan. The
|
|
92
|
+
# degenerate values are the whole point of this routine (its caller branches
|
|
93
|
+
# on them), so an exception here would replace the behaviour being ported.
|
|
94
|
+
d1 = np.dot(c_ - a, b - a)
|
|
95
|
+
d2 = np.dot(c_ - b, a - b)
|
|
96
|
+
d3 = np.dot(a - c_, b - c_)
|
|
97
|
+
|
|
98
|
+
cc = d2 * d3 + d3 * d1 + d1 * d2
|
|
99
|
+
|
|
100
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
101
|
+
r = 0.5 * np.sqrt((d1 + d2) * (d2 + d3) * (d3 + d1) / cc)
|
|
102
|
+
c1, c2, c3 = d2 * d3, d3 * d1, d1 * d2
|
|
103
|
+
cent = ((c2 + c3) * a + (c3 + c1) * b + (c1 + c2) * c_) / (2.0 * cc)
|
|
104
|
+
|
|
105
|
+
return Circle(r=float(r), center=np.asarray(cent, dtype=np.float64))
|