arrayprobe 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. arrayprobe/__init__.py +219 -0
  2. arrayprobe/__main__.py +19 -0
  3. arrayprobe/_v314_lazy.py +48 -0
  4. arrayprobe/ai_ready.py +212 -0
  5. arrayprobe/attributed_export.py +1333 -0
  6. arrayprobe/authordefaults.py +267 -0
  7. arrayprobe/cli.py +3510 -0
  8. arrayprobe/combine.py +12 -0
  9. arrayprobe/compare.py +950 -0
  10. arrayprobe/config.py +1239 -0
  11. arrayprobe/constants.py +12 -0
  12. arrayprobe/count_closure.py +204 -0
  13. arrayprobe/diagnostic_views.py +769 -0
  14. arrayprobe/diode_report.py +265 -0
  15. arrayprobe/driver/__init__.py +5 -0
  16. arrayprobe/driver/_load_record.py +331 -0
  17. arrayprobe/driver/preflight_inputs.py +250 -0
  18. arrayprobe/driver/reprocess.py +553 -0
  19. arrayprobe/driver/run_flight.py +8166 -0
  20. arrayprobe/driver/tas_from_probe_housekeeping.py +124 -0
  21. arrayprobe/dropsize.py +519 -0
  22. arrayprobe/friendly.py +206 -0
  23. arrayprobe/geometry/__init__.py +77 -0
  24. arrayprobe/geometry/min_rectangle.py +92 -0
  25. arrayprobe/intarr.py +12 -0
  26. arrayprobe/intarr_analysis.py +16 -0
  27. arrayprobe/intarr_plots.py +12 -0
  28. arrayprobe/inventory.py +129 -0
  29. arrayprobe/jit_kernels.py +344 -0
  30. arrayprobe/lwc.py +44 -0
  31. arrayprobe/masks.py +349 -0
  32. arrayprobe/matio.py +410 -0
  33. arrayprobe/matlab_compat.py +13 -0
  34. arrayprobe/ncio.py +26 -0
  35. arrayprobe/particle.py +55 -0
  36. arrayprobe/particle_perimeter.py +12 -0
  37. arrayprobe/products.py +78 -0
  38. arrayprobe/profiles.py +179 -0
  39. arrayprobe/provenance.py +21 -0
  40. arrayprobe/py.typed +11 -0
  41. arrayprobe/readers/__init__.py +9 -0
  42. arrayprobe/readers/dmt.py +603 -0
  43. arrayprobe/readers/mask_csv.py +12 -0
  44. arrayprobe/readers/pms.py +12 -0
  45. arrayprobe/readers/sea.py +433 -0
  46. arrayprobe/readers/tasinfo.py +12 -0
  47. arrayprobe/regimes.py +507 -0
  48. arrayprobe/render.py +728 -0
  49. arrayprobe/reproduce_report.py +149 -0
  50. arrayprobe/review_agreement.py +135 -0
  51. arrayprobe/review_sampling.py +327 -0
  52. arrayprobe/run_page.py +624 -0
  53. arrayprobe/sample_area.py +12 -0
  54. arrayprobe/selector.py +206 -0
  55. arrayprobe/sizing.py +151 -0
  56. arrayprobe/time_convert.py +12 -0
  57. arrayprobe/timing_closure.py +141 -0
  58. arrayprobe/tools/__init__.py +27 -0
  59. arrayprobe/tools/make_demo_flight.py +1089 -0
  60. arrayprobe/tools/make_tas_file.py +760 -0
  61. arrayprobe/tools/probe_comparison.py +569 -0
  62. arrayprobe/tools/synthetic_truth.py +698 -0
  63. arrayprobe/tools/tas_sources.py +705 -0
  64. arrayprobe/triage_context.py +488 -0
  65. arrayprobe/triage_server.py +5215 -0
  66. arrayprobe/tune/__init__.py +15 -0
  67. arrayprobe/tune/diodes.py +400 -0
  68. arrayprobe/tune/distributions.py +300 -0
  69. arrayprobe/tune/sample.py +243 -0
  70. arrayprobe/tune/score.py +230 -0
  71. arrayprobe/tune/settings.py +354 -0
  72. arrayprobe/validate_by_condition.py +208 -0
  73. arrayprobe/validation_report.py +166 -0
  74. arrayprobe-0.1.0.dist-info/METADATA +260 -0
  75. arrayprobe-0.1.0.dist-info/RECORD +189 -0
  76. arrayprobe-0.1.0.dist-info/WHEEL +5 -0
  77. arrayprobe-0.1.0.dist-info/entry_points.txt +2 -0
  78. arrayprobe-0.1.0.dist-info/licenses/LICENSE +31 -0
  79. arrayprobe-0.1.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +47 -0
  80. arrayprobe-0.1.0.dist-info/licenses/NOTICE.md +369 -0
  81. arrayprobe-0.1.0.dist-info/top_level.txt +4 -0
  82. arrayprobe_soda2/__init__.py +131 -0
  83. arrayprobe_soda2/angles.py +143 -0
  84. arrayprobe_soda2/aspect_ratio.py +541 -0
  85. arrayprobe_soda2/backfill.py +100 -0
  86. arrayprobe_soda2/binary_dof.py +181 -0
  87. arrayprobe_soda2/buildindex.py +113 -0
  88. arrayprobe_soda2/decompress_dmt.py +285 -0
  89. arrayprobe_soda2/enhancement_hooks.py +275 -0
  90. arrayprobe_soda2/export_ascii.py +732 -0
  91. arrayprobe_soda2/export_ncdf.py +683 -0
  92. arrayprobe_soda2/export_ncdf_raf.py +396 -0
  93. arrayprobe_soda2/fillholes.py +161 -0
  94. arrayprobe_soda2/find_radius.py +105 -0
  95. arrayprobe_soda2/findsize.py +407 -0
  96. arrayprobe_soda2/fit_poisson.py +170 -0
  97. arrayprobe_soda2/fix2dimage.py +63 -0
  98. arrayprobe_soda2/fixraking.py +162 -0
  99. arrayprobe_soda2/fixstuckbits.py +146 -0
  100. arrayprobe_soda2/hvps4_read_frame.py +121 -0
  101. arrayprobe_soda2/jit_kernels.py +152 -0
  102. arrayprobe_soda2/label_blobs.py +177 -0
  103. arrayprobe_soda2/min_circle_fast.py +320 -0
  104. arrayprobe_soda2/particlesort.py +703 -0
  105. arrayprobe_soda2/pbp_writer.py +558 -0
  106. arrayprobe_soda2/poisson_spot_correct.py +183 -0
  107. arrayprobe_soda2/princomp.py +107 -0
  108. arrayprobe_soda2/probespecs.py +361 -0
  109. arrayprobe_soda2/process_2d.py +1364 -0
  110. arrayprobe_soda2/process_2d_parallel.py +626 -0
  111. arrayprobe_soda2/process_hk.py +512 -0
  112. arrayprobe_soda2/processbuffer_2dc.py +155 -0
  113. arrayprobe_soda2/processbuffer_cip.py +213 -0
  114. arrayprobe_soda2/processbuffer_f2dc.py +139 -0
  115. arrayprobe_soda2/processbuffer_spec.py +441 -0
  116. arrayprobe_soda2/processbuffer_tail.py +350 -0
  117. arrayprobe_soda2/pth_readers.py +245 -0
  118. arrayprobe_soda2/py.typed +11 -0
  119. arrayprobe_soda2/read2dbuffer.py +371 -0
  120. arrayprobe_soda2/reject.py +246 -0
  121. arrayprobe_soda2/reprocess_pbp.py +156 -0
  122. arrayprobe_soda2/sample_area.py +264 -0
  123. arrayprobe_soda2/save_writer.py +480 -0
  124. arrayprobe_soda2/sea.py +324 -0
  125. arrayprobe_soda2/spec_absolutepointers.py +109 -0
  126. arrayprobe_soda2/spec_decompress.py +203 -0
  127. arrayprobe_soda2/spec_index.py +476 -0
  128. arrayprobe_soda2/spec_read_frame.py +286 -0
  129. arrayprobe_soda2/spec_read_hk.py +301 -0
  130. arrayprobe_soda2/spec_readint.py +127 -0
  131. arrayprobe_soda2/timeconv.py +77 -0
  132. arrayprobe_soda2/update_op.py +101 -0
  133. arrayprobe_uiops/__init__.py +45 -0
  134. arrayprobe_uiops/combine.py +192 -0
  135. arrayprobe_uiops/combine_fork.py +359 -0
  136. arrayprobe_uiops/constants.py +830 -0
  137. arrayprobe_uiops/decode_naming.py +113 -0
  138. arrayprobe_uiops/diode_mask.py +250 -0
  139. arrayprobe_uiops/engine_absence.py +41 -0
  140. arrayprobe_uiops/export_oap.py +325 -0
  141. arrayprobe_uiops/geometry_core.py +366 -0
  142. arrayprobe_uiops/habit.py +749 -0
  143. arrayprobe_uiops/habit_core.py +248 -0
  144. arrayprobe_uiops/hollow_size_rule.py +376 -0
  145. arrayprobe_uiops/imgproc.py +2081 -0
  146. arrayprobe_uiops/imgproc_core.py +275 -0
  147. arrayprobe_uiops/intarr.py +167 -0
  148. arrayprobe_uiops/intarr_analysis.py +569 -0
  149. arrayprobe_uiops/intarr_plots.py +119 -0
  150. arrayprobe_uiops/jit_kernels.py +430 -0
  151. arrayprobe_uiops/lwc.py +70 -0
  152. arrayprobe_uiops/matlab_compat.py +860 -0
  153. arrayprobe_uiops/measure.py +346 -0
  154. arrayprobe_uiops/min_circle.py +204 -0
  155. arrayprobe_uiops/min_ellipse.py +161 -0
  156. arrayprobe_uiops/min_rectangle.py +200 -0
  157. arrayprobe_uiops/ncar_2dc_timing.py +100 -0
  158. arrayprobe_uiops/ncio.py +810 -0
  159. arrayprobe_uiops/oap_read.py +228 -0
  160. arrayprobe_uiops/particle.py +51 -0
  161. arrayprobe_uiops/particle_perimeter.py +94 -0
  162. arrayprobe_uiops/particle_physics.py +199 -0
  163. arrayprobe_uiops/pecan_params.py +134 -0
  164. arrayprobe_uiops/probe_cases.py +298 -0
  165. arrayprobe_uiops/product_sanity.py +337 -0
  166. arrayprobe_uiops/profile.py +71 -0
  167. arrayprobe_uiops/profiles.py +756 -0
  168. arrayprobe_uiops/provenance.py +804 -0
  169. arrayprobe_uiops/py.typed +11 -0
  170. arrayprobe_uiops/qc.py +169 -0
  171. arrayprobe_uiops/readers/__init__.py +8 -0
  172. arrayprobe_uiops/readers/mask_csv.py +74 -0
  173. arrayprobe_uiops/readers/pms.py +239 -0
  174. arrayprobe_uiops/readers/tasinfo.py +57 -0
  175. arrayprobe_uiops/rect_ellipse.py +129 -0
  176. arrayprobe_uiops/register_image_assisted.py +25 -0
  177. arrayprobe_uiops/reject.py +501 -0
  178. arrayprobe_uiops/reject_core.py +220 -0
  179. arrayprobe_uiops/sample_area.py +93 -0
  180. arrayprobe_uiops/sizedist.py +1923 -0
  181. arrayprobe_uiops/sizedist_core.py +814 -0
  182. arrayprobe_uiops/sizedist_tables.py +642 -0
  183. arrayprobe_uiops/spec.py +1094 -0
  184. arrayprobe_uiops/spec_core.py +703 -0
  185. arrayprobe_uiops/stray_pixel.py +103 -0
  186. arrayprobe_uiops/tas.py +191 -0
  187. arrayprobe_uiops/time_convert.py +41 -0
  188. uiops/__init__.py +402 -0
  189. uiops/py.typed +11 -0
@@ -0,0 +1,480 @@
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
+ """The IDL SAVE file ``soda2_process_2d.pro:729-731`` writes --
4
+ ``save, file=fn_out, data, /compress`` -- ported as a file-format writer
5
+ Replaces the earlier ``pbp_writer.SaveFileNotPorted``.
6
+
7
+ **This is file-format porting, not algorithm porting.** The target is
8
+ *restore-equality*, not byte-identity with IDL: a zlib stream differs between
9
+ implementations, and the ``TIMESTAMP`` record carries the date, user and host.
10
+ What is asserted instead (``tests/test_soda2_save_writer.py``,
11
+ ``tests/test_soda2_save_writer_gdl.py``):
12
+
13
+ - ``scipy.io.readsav`` reads the file back to the same ``data`` struct,
14
+ field for field (IDL type, dimensions, values);
15
+ - GDL ``RESTORE`` of this file equals GDL ``RESTORE`` of GDL's own ``SAVE`` of
16
+ the same struct (``gdl_oracle/run_soda2_save_writer_bank.py``);
17
+ - the descriptor fields that neither reader needs -- tag offsets, tag and
18
+ variable flags, ``PREDEF`` -- follow what IDL 8.5 itself wrote, measured
19
+ from the descriptor (structure only, never values) of an IDL-written
20
+ SODA-2 ``.dat``. Where GDL's own ``SAVE`` writes something else (it does,
21
+ for all four), this module follows IDL, not GDL.
22
+
23
+ **Format** (C. Markwardt's *Unofficial Format Specification of the IDL SAVE
24
+ File*, as implemented by ``scipy/io/_idl.py``; every field below was checked
25
+ against a GDL-written and an IDL-written file):
26
+
27
+ - signature ``SR``, then ``00 04`` (plain) or ``00 06`` (``/compress``);
28
+ - records, each ``RECTYPE`` (LONG), ``NEXTREC`` (two unsigned LONGs, low
29
+ word first: the absolute file offset of the next record), 4 zero bytes,
30
+ then the body; under ``/compress`` each body is zlib-compressed on its own
31
+ and ``NEXTREC`` points into the compressed file;
32
+ - record sequence ``TIMESTAMP`` (10), ``VERSION`` (14), one ``VARIABLE`` (2)
33
+ per variable, ``END_MARKER`` (6) -- the sequence IDL 8.5 wrote. IDL's
34
+ ``END_MARKER`` is 16 bytes and ends the file; GDL appends 20 (plain) or
35
+ hundreds (compressed) bytes of stale buffer after it, which this module
36
+ does not reproduce;
37
+ - all numbers big-endian (XDR). INT/UINT are widened to 4 bytes on the wire
38
+ (INT sign-extended, UINT zero-extended); a BYTE scalar is a LONG 1 then
39
+ the byte padded to 4; a BYTE array is its byte count (LONG) then the bytes
40
+ padded to 4; a STRING is its length, then (if non-empty) the length again
41
+ and the bytes padded to 4 -- an empty string is one LONG 0 (measured:
42
+ ``readsav`` and GDL agree on an IDL-written empty ``op.outdir``);
43
+ - arrays are written in IDL (column-major) order with IDL's dimensions. The
44
+ port keeps IDL index order in its numpy shapes (``conc1d[i, j]`` is IDL's
45
+ ``conc1d[i, j]``), so the IDL dimensions *are* the numpy shape and the
46
+ bytes are the array in Fortran order. ``readsav`` therefore returns the
47
+ transpose of the port's array, exactly as it does for an IDL-written file.
48
+
49
+ **Python value -> IDL type** (the port's arrays already carry their IDL
50
+ types; only native Python scalars in ``op`` need a rule):
51
+
52
+ - numpy scalars and arrays keep their dtype: ``uint8``->BYTE, ``int16``->INT,
53
+ ``int32``->LONG, ``float32``->FLOAT, ``float64``->DOUBLE,
54
+ ``complex64``->COMPLEX, ``complex128``->DCOMPLEX, ``uint16``->UINT,
55
+ ``uint32``->ULONG, ``int64``->LONG64, ``uint64``->ULONG64, ``bool``->BYTE;
56
+ - a Python ``int`` follows IDL's integer-literal rule: INT if it fits
57
+ 16 bits, else LONG, else LONG64 (``soda2_update_op.pro:30``'s
58
+ ``seatag=[33000,0,0]`` is LONG for that reason, ``update_op.py``); a list
59
+ of ints takes the widest element's type, as an IDL array literal does;
60
+ - a Python ``float`` is **DOUBLE**. That is the port's standing convention
61
+ (a Python float is a C double; ``process_2d.py``'s ``activetime`` rule
62
+ reads it the same way). IDL's bare ``1.0`` is FLOAT: a caller who wants
63
+ FLOAT passes ``np.float32``;
64
+ - ``str`` -> STRING; a ``dict`` or dataclass -> an anonymous one-element
65
+ structure, tags in insertion / declaration order, names upper-cased.
66
+
67
+ **Refused by name** (:class:`IdlSaveUnsupported`), never silently coerced:
68
+ ``int8``/``float16``/object arrays (no IDL type), a zero-length array (IDL
69
+ has none), more than 8 dimensions (IDL's limit), ``None``, arrays of
70
+ structures (the SODA-2 ``data`` has none), strings that are not Latin-1,
71
+ and a single array over 2**31-1 bytes (the 64-bit ``ARRSTART 18``
72
+ descriptor; no SODA-2 field approaches it).
73
+ """
74
+ from __future__ import annotations
75
+
76
+ import dataclasses
77
+ import getpass
78
+ import platform
79
+ import socket
80
+ import struct
81
+ import time
82
+ import zlib
83
+ from collections.abc import Mapping, Sequence
84
+ from pathlib import Path
85
+ from typing import Any
86
+
87
+ import numpy as np
88
+
89
+ __all__ = [
90
+ "IdlSaveUnsupported",
91
+ "PROCESS_DATA_TAGS",
92
+ "write_idl_save",
93
+ "save_process_data",
94
+ "struct_layout",
95
+ ]
96
+
97
+
98
+ class IdlSaveUnsupported(ValueError):
99
+ """A value this writer cannot represent in an IDL SAVE file."""
100
+
101
+
102
+ #: ``soda2_process_2d.pro:678-687`` -- the ``data`` tag order, transcribed
103
+ #: from the source (not from ``ProcessData``; ``test_soda2_save_writer`` checks
104
+ #: the two agree). ``Date_Processed`` is written upper-case, as IDL stores
105
+ #: every tag name.
106
+ PROCESS_DATA_TAGS: tuple[str, ...] = (
107
+ "op", "time", "tas", "probetas", "midbins", "activetime",
108
+ "date_processed", "sa", "intspec_all", "intspec_accepted",
109
+ "intendbins", "intmidbins", "count_rejected",
110
+ "total_count_rejected", "count_accepted", "count_missed",
111
+ "missed_hist", "conc1d", "spec1d", "spec2d", "spec2d_aspr",
112
+ "corr_fac", "poisson_fac", "intcutoff", "zdspec",
113
+ "zdendbins", "zdmidbins", "pointer", "ind", "currentfile",
114
+ "numbuffsaccepted", "numbuffsrejected", "dhist", "hist3d",
115
+ "spec2d_orientation", "orientation_index", "house",
116
+ "pbpstartindex",
117
+ )
118
+
119
+ # --- IDL type codes -------------------------------------------------------
120
+
121
+ BYTE, INT, LONG, FLOAT, DOUBLE, COMPLEX, STRING, STRUCT = 1, 2, 3, 4, 5, 6, 7, 8
122
+ DCOMPLEX, UINT, ULONG, LONG64, ULONG64 = 9, 12, 13, 14, 15
123
+
124
+ _DTYPE_TO_CODE: dict[str, int] = {
125
+ "u1": BYTE, "b1": BYTE, "i2": INT, "i4": LONG, "f4": FLOAT, "f8": DOUBLE,
126
+ "c8": COMPLEX, "c16": DCOMPLEX, "u2": UINT, "u4": ULONG, "i8": LONG64,
127
+ "u8": ULONG64,
128
+ }
129
+ #: code -> big-endian wire dtype for the raw-bytes array types.
130
+ _WIRE: dict[int, str] = {
131
+ BYTE: ">u1", INT: ">i4", LONG: ">i4", FLOAT: ">f4", DOUBLE: ">f8",
132
+ COMPLEX: ">c8", DCOMPLEX: ">c16", UINT: ">u4", ULONG: ">u4",
133
+ LONG64: ">i8", ULONG64: ">u8",
134
+ }
135
+ #: In-memory element size and alignment on 64-bit IDL (``IDL_STRING`` is 16
136
+ #: bytes, 8-aligned). Measured: every tag offset of an IDL 8.5-written SODA-2
137
+ #: ``data`` and its ``op`` follows these with C natural alignment
138
+ #: (``test_soda2_save_writer.TestLayoutAgainstIdlDescriptor``).
139
+ _SIZE: dict[int, int] = {
140
+ BYTE: 1, INT: 2, LONG: 4, FLOAT: 4, DOUBLE: 8, COMPLEX: 8, STRING: 16,
141
+ DCOMPLEX: 16, UINT: 2, ULONG: 4, LONG64: 8, ULONG64: 8,
142
+ }
143
+ _ALIGN: dict[int, int] = {
144
+ BYTE: 1, INT: 2, LONG: 4, FLOAT: 4, DOUBLE: 8, COMPLEX: 4, STRING: 8,
145
+ DCOMPLEX: 8, UINT: 2, ULONG: 4, LONG64: 8, ULONG64: 8,
146
+ }
147
+
148
+ #: Descriptor flag values IDL 8.5 wrote (measured from an IDL-written
149
+ #: ``.dat``'s descriptor): ``IDL_V_ARR`` 4, ``IDL_V_DYNAMIC`` 16,
150
+ #: ``IDL_V_STRUCT`` 32. GDL writes 0 / 4 / 36 and ``PREDEF`` 40 instead.
151
+ _FLAG_SCALAR, _FLAG_STRING, _FLAG_ARRAY, _FLAG_STRUCT = 0, 16, 20, 52
152
+ _PREDEF = 8
153
+
154
+ _INT16 = (-(2**15), 2**15 - 1)
155
+ _INT32 = (-(2**31), 2**31 - 1)
156
+ _MAX_ARRAY_BYTES = 2**31 - 1
157
+
158
+ # --- the value model -------------------------------------------------------
159
+
160
+
161
+ @dataclasses.dataclass
162
+ class _Scalar:
163
+ code: int
164
+ value: Any
165
+
166
+
167
+ @dataclasses.dataclass
168
+ class _Array:
169
+ code: int
170
+ dims: tuple[int, ...] # IDL order (= the port's numpy shape)
171
+ flat: np.ndarray # IDL (column-major) element order
172
+
173
+
174
+ @dataclasses.dataclass
175
+ class _Struct:
176
+ tags: list[tuple[str, _Scalar | _Array | _Struct]]
177
+
178
+
179
+ _Node = _Scalar | _Array | _Struct
180
+
181
+
182
+ def _int_code(lo: int, hi: int) -> int:
183
+ if _INT16[0] <= lo and hi <= _INT16[1]:
184
+ return INT
185
+ if _INT32[0] <= lo and hi <= _INT32[1]:
186
+ return LONG
187
+ if -(2**63) <= lo and hi <= 2**63 - 1:
188
+ return LONG64
189
+ raise IdlSaveUnsupported(f"integer {lo if lo < 0 else hi} does not fit IDL LONG64")
190
+
191
+
192
+ def _code_of_dtype(dtype: np.dtype, where: str) -> int:
193
+ key = dtype.kind + str(dtype.itemsize) if dtype.kind != "b" else "b1"
194
+ code = _DTYPE_TO_CODE.get(key)
195
+ if code is None:
196
+ raise IdlSaveUnsupported(f"{where}: numpy dtype {dtype} has no IDL type")
197
+ return code
198
+
199
+
200
+ def _latin1(s: str, where: str) -> bytes:
201
+ try:
202
+ return s.encode("latin1")
203
+ except UnicodeEncodeError as exc:
204
+ raise IdlSaveUnsupported(f"{where}: string is not Latin-1: {s!r}") from exc
205
+
206
+
207
+ def _array_node(arr: np.ndarray, where: str) -> _Array:
208
+ if arr.size == 0:
209
+ raise IdlSaveUnsupported(f"{where}: zero-length array (IDL has none)")
210
+ if arr.ndim > 8:
211
+ raise IdlSaveUnsupported(f"{where}: {arr.ndim} dimensions (IDL allows 8)")
212
+ if arr.dtype.kind in ("U", "S"):
213
+ flat = np.array([str(x) if arr.dtype.kind == "U" else x.decode("latin1")
214
+ for x in arr.flatten(order="F")], dtype=object)
215
+ for s in flat:
216
+ _latin1(s, where)
217
+ return _Array(STRING, tuple(arr.shape), flat)
218
+ if arr.dtype == object:
219
+ items = arr.flatten(order="F").tolist()
220
+ if all(isinstance(x, str) for x in items):
221
+ for s in items:
222
+ _latin1(s, where)
223
+ return _Array(STRING, tuple(arr.shape), np.array(items, dtype=object))
224
+ raise IdlSaveUnsupported(f"{where}: object array that is not all strings")
225
+ code = _code_of_dtype(arr.dtype, where)
226
+ nbytes = arr.size * _SIZE[code]
227
+ if nbytes > _MAX_ARRAY_BYTES:
228
+ raise IdlSaveUnsupported(
229
+ f"{where}: {nbytes} bytes needs the 64-bit ARRSTART-18 descriptor, "
230
+ "not written by this port")
231
+ flat = np.asarray(arr).flatten(order="F")
232
+ if arr.dtype.kind == "b":
233
+ flat = flat.astype(np.uint8)
234
+ return _Array(code, tuple(arr.shape), flat)
235
+
236
+
237
+ def _node(value: Any, where: str) -> _Node:
238
+ """Python/numpy value -> the typed value model (module docstring rules)."""
239
+ if value is None:
240
+ raise IdlSaveUnsupported(f"{where}: None has no IDL value")
241
+ if isinstance(value, (_Scalar, _Array, _Struct)):
242
+ return value
243
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
244
+ return _Struct([(f.name.upper(), _node(getattr(value, f.name), f"{where}.{f.name}"))
245
+ for f in dataclasses.fields(value)])
246
+ if isinstance(value, Mapping):
247
+ return _Struct([(str(k).upper(), _node(v, f"{where}.{k}")) for k, v in value.items()])
248
+ if isinstance(value, str):
249
+ _latin1(value, where)
250
+ return _Scalar(STRING, value)
251
+ if isinstance(value, (bool, np.bool_)):
252
+ return _Scalar(BYTE, int(value))
253
+ if isinstance(value, np.generic):
254
+ code = _code_of_dtype(value.dtype, where)
255
+ return _Scalar(code, value)
256
+ if isinstance(value, int):
257
+ return _Scalar(_int_code(value, value), value)
258
+ if isinstance(value, float):
259
+ return _Scalar(DOUBLE, value)
260
+ if isinstance(value, np.ndarray):
261
+ if value.ndim == 0:
262
+ return _node(value[()], where)
263
+ return _array_node(value, where)
264
+ if isinstance(value, Sequence):
265
+ items = list(value)
266
+ if not items:
267
+ raise IdlSaveUnsupported(f"{where}: empty list (IDL has no zero-length array)")
268
+ if any(isinstance(x, (Mapping, list, tuple)) or dataclasses.is_dataclass(x)
269
+ for x in items):
270
+ raise IdlSaveUnsupported(f"{where}: nested list / array of structures")
271
+ if all(isinstance(x, str) for x in items):
272
+ return _array_node(np.array(items, dtype=object), where)
273
+ if all(isinstance(x, int) and not isinstance(x, bool) for x in items):
274
+ code = _int_code(min(items), max(items))
275
+ dt = {INT: np.int16, LONG: np.int32, LONG64: np.int64}[code]
276
+ return _array_node(np.array(items, dtype=dt), where)
277
+ if all(isinstance(x, (int, float)) and not isinstance(x, bool) for x in items):
278
+ return _array_node(np.array(items, dtype=np.float64), where)
279
+ return _array_node(np.asarray(items), where)
280
+ raise IdlSaveUnsupported(f"{where}: {type(value).__name__} has no IDL mapping")
281
+
282
+
283
+ # --- in-memory layout (the descriptor's tag offsets) -----------------------
284
+
285
+
286
+ def _size_align(node: _Node) -> tuple[int, int]:
287
+ if isinstance(node, _Struct):
288
+ size, align, _ = _struct_layout(node)
289
+ return size, align
290
+ n = int(np.prod(node.dims)) if isinstance(node, _Array) else 1
291
+ return _SIZE[node.code] * n, _ALIGN[node.code]
292
+
293
+
294
+ def _struct_layout(node: _Struct) -> tuple[int, int, list[int]]:
295
+ offset, max_align, offsets = 0, 1, []
296
+ for _, child in node.tags:
297
+ size, align = _size_align(child)
298
+ offset = (offset + align - 1) // align * align
299
+ offsets.append(offset)
300
+ offset += size
301
+ max_align = max(max_align, align)
302
+ size = (offset + max_align - 1) // max_align * max_align
303
+ return size, max_align, offsets
304
+
305
+
306
+ def struct_layout(value: Any) -> tuple[int, list[tuple[str, int]]]:
307
+ """``(size, [(TAG, offset), ...])`` of ``value`` as a 64-bit IDL
308
+ structure -- the offsets this writer puts in the descriptor."""
309
+ node = _node(value, "value")
310
+ if not isinstance(node, _Struct):
311
+ raise IdlSaveUnsupported("struct_layout: value is not a structure")
312
+ size, _, offsets = _struct_layout(node)
313
+ return size, [(name, off) for (name, _), off in zip(node.tags, offsets, strict=True)]
314
+
315
+
316
+ # --- encoding --------------------------------------------------------------
317
+
318
+
319
+ def _long(v: int) -> bytes:
320
+ return struct.pack(">l", v)
321
+
322
+
323
+ def _pad4(b: bytes) -> bytes:
324
+ return b + b"\x00" * (-len(b) % 4)
325
+
326
+
327
+ def _name(s: str) -> bytes:
328
+ """A record/descriptor STRING (``_read_string``): length, bytes, pad."""
329
+ raw = _latin1(s, "name")
330
+ return _long(len(raw)) + _pad4(raw)
331
+
332
+
333
+ def _string_data(s: str) -> bytes:
334
+ """A data STRING (``_read_string_data``): length twice, bytes, pad; an
335
+ empty string is a single LONG 0."""
336
+ raw = _latin1(s, "string")
337
+ if not raw:
338
+ return _long(0)
339
+ return _long(len(raw)) + _long(len(raw)) + _pad4(raw)
340
+
341
+
342
+ def _scalar_data(code: int, value: Any) -> bytes:
343
+ if code == BYTE:
344
+ return _long(1) + struct.pack(">B", int(value)) + b"\x00\x00\x00"
345
+ if code == INT:
346
+ return struct.pack(">i", int(np.int16(value)))
347
+ if code == UINT:
348
+ return struct.pack(">I", int(np.uint16(value)))
349
+ if code == STRING:
350
+ return _string_data(value)
351
+ return np.asarray(value, dtype=_WIRE[code]).reshape(1).tobytes()
352
+
353
+
354
+ def _array_data(node: _Array) -> bytes:
355
+ if node.code == STRING:
356
+ return b"".join(_string_data(s) for s in node.flat)
357
+ if node.code == BYTE:
358
+ raw = node.flat.astype(">u1").tobytes()
359
+ return _long(len(raw)) + _pad4(raw)
360
+ if node.code in (INT, UINT):
361
+ # widened to 4 bytes per element: INT sign-extends, UINT zero-extends
362
+ return node.flat.astype(_WIRE[node.code]).tobytes()
363
+ return _pad4(node.flat.astype(_WIRE[node.code]).tobytes())
364
+
365
+
366
+ def _data(node: _Node) -> bytes:
367
+ if isinstance(node, _Struct):
368
+ return b"".join(_data(child) for _, child in node.tags)
369
+ if isinstance(node, _Array):
370
+ return _array_data(node)
371
+ return _scalar_data(node.code, node.value)
372
+
373
+
374
+ def _arraydesc(code: int, dims: tuple[int, ...], elt_size: int) -> bytes:
375
+ n = int(np.prod(dims))
376
+ full = list(dims) + [1] * (8 - len(dims))
377
+ return b"".join(_long(v) for v in
378
+ (8, elt_size, elt_size * n, n, len(dims), 0, 0, 8, *full))
379
+
380
+
381
+ def _structdesc(node: _Struct) -> bytes:
382
+ _, _, offsets = _struct_layout(node)
383
+ out = [_long(9), _name(""), _long(_PREDEF), _long(len(node.tags)), _long(0)]
384
+ for (_, child), off in zip(node.tags, offsets, strict=True):
385
+ if isinstance(child, _Struct):
386
+ code, flags = STRUCT, _FLAG_STRUCT
387
+ elif isinstance(child, _Array):
388
+ code, flags = child.code, _FLAG_ARRAY
389
+ else:
390
+ code = child.code
391
+ flags = _FLAG_STRING if code == STRING else _FLAG_SCALAR
392
+ out.append(_long(off) + _long(code) + _long(flags))
393
+ out.extend(_name(name) for name, _ in node.tags)
394
+ for _, child in node.tags:
395
+ if isinstance(child, _Struct):
396
+ out.append(_arraydesc(STRUCT, (1,), _struct_layout(child)[0]))
397
+ elif isinstance(child, _Array):
398
+ out.append(_arraydesc(child.code, child.dims, _SIZE[child.code]))
399
+ for _, child in node.tags:
400
+ if isinstance(child, _Struct):
401
+ out.append(_structdesc(child))
402
+ return b"".join(out)
403
+
404
+
405
+ def _variable_body(name: str, node: _Node) -> bytes:
406
+ if isinstance(node, _Struct):
407
+ typedesc = (_long(STRUCT) + _long(_FLAG_STRUCT)
408
+ + _arraydesc(STRUCT, (1,), _struct_layout(node)[0])
409
+ + _structdesc(node))
410
+ elif isinstance(node, _Array):
411
+ typedesc = (_long(node.code) + _long(_FLAG_ARRAY)
412
+ + _arraydesc(node.code, node.dims, _SIZE[node.code]))
413
+ else:
414
+ typedesc = _long(node.code) + _long(
415
+ _FLAG_STRING if node.code == STRING else _FLAG_SCALAR)
416
+ return _name(name.upper()) + typedesc + _long(7) + _data(node)
417
+
418
+
419
+ def _timestamp_body(date: str, user: str, host: str) -> bytes:
420
+ return b"\x00" * 1024 + _name(date) + _name(user) + _name(host)
421
+
422
+
423
+ def _version_body() -> bytes:
424
+ # The layout reproduced is IDL 8.5's (format 12, measured); `release`
425
+ # names that layout, not the program that wrote the file -- the
426
+ # TIMESTAMP's user/host say who did.
427
+ os_name = "Win32" if platform.system() == "Windows" else platform.system().lower()
428
+ return _long(12) + _name("x86_64") + _name(os_name) + _name("8.5")
429
+
430
+
431
+ def write_idl_save(
432
+ path: str | Path,
433
+ variables: Mapping[str, Any],
434
+ *,
435
+ compress: bool = False,
436
+ timestamp: tuple[str, str, str] | None = None,
437
+ ) -> Path:
438
+ """``save, file=path, <variables>[, /compress]``.
439
+
440
+ ``variables`` maps each IDL variable name to its value (module docstring
441
+ for the type rules), written in mapping order. ``timestamp`` overrides
442
+ the ``(date, user, host)`` the ``TIMESTAMP`` record carries (default:
443
+ now in IDL's ``systime()`` form, this user, this host) -- tests pin it so
444
+ two writes of the same data are byte-identical."""
445
+ if not variables:
446
+ raise IdlSaveUnsupported("save: no variables")
447
+ if timestamp is None:
448
+ timestamp = (time.strftime("%a %b %d %H:%M:%S %Y"), getpass.getuser(),
449
+ socket.gethostname())
450
+ bodies: list[tuple[int, bytes]] = [
451
+ (10, _timestamp_body(*timestamp)),
452
+ (14, _version_body()),
453
+ ]
454
+ for name, value in variables.items():
455
+ bodies.append((2, _variable_body(name, _node(value, name))))
456
+
457
+ out = bytearray(b"SR" + (b"\x00\x06" if compress else b"\x00\x04"))
458
+ for rectype, body in bodies:
459
+ payload = zlib.compress(body) if compress else body
460
+ nextrec = len(out) + 16 + len(payload)
461
+ out += _long(rectype) + struct.pack(">II", nextrec & 0xFFFFFFFF, nextrec >> 32)
462
+ out += b"\x00" * 4 + payload
463
+ out += _long(6) + b"\x00" * 12
464
+ path = Path(path)
465
+ path.write_bytes(bytes(out))
466
+ return path
467
+
468
+
469
+ def _process_data_struct(data: Any) -> dict[str, Any]:
470
+ """``ProcessData`` -> the ``data`` struct in ``:678-687`` tag order. The
471
+ two port-tooling fields (``pbp_csv_path``/``pbp_ncdf_path``) are not IDL
472
+ tags and are not written."""
473
+ return {tag: getattr(data, tag) for tag in PROCESS_DATA_TAGS}
474
+
475
+
476
+ def save_process_data(path: str | Path, data: Any, *, compress: bool = True,
477
+ timestamp: tuple[str, str, str] | None = None) -> Path:
478
+ """``soda2_process_2d.pro:731``: ``save, file=fn_out, data, /compress``."""
479
+ return write_idl_save(path, {"data": _process_data_struct(data)},
480
+ compress=compress, timestamp=timestamp)