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
arrayprobe/matio.py ADDED
@@ -0,0 +1,410 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Reading the MATLAB ``.mat`` sidecars the UIOOPS processing chain leaves behind.
3
+
4
+ UIOOPS itself writes netCDF, but the ORACLES production chain hangs two MATLAB
5
+ ``save`` files off the side of it, and the port has to read at least one of them
6
+ to reproduce the reference product:
7
+
8
+ * ``diode.<date><time>[.<orientation>].mat`` -- the stuck-diode mask that
9
+ ``find_shadow_diodes.m:104`` writes and the production ``imgProc_sm.m:289``
10
+ loads. See :mod:`arrayprobe.masks`.
11
+
12
+ That is the whole requirement: a handful of small, flat, real numeric and char
13
+ arrays. No cells, no structs, no objects, no sparse, no complex -- MATLAB's
14
+ ``save`` of a workspace containing three plain variables.
15
+
16
+ **Why this is not ``scipy.io.loadmat``.** SciPy would do the job in one line,
17
+ and it is already declared in the ``arrayprobe[extra]`` extra. Pulling it into
18
+ the *runtime* requirements to read three hundred bytes would make a 30 MB
19
+ numerical stack a hard dependency of ``import arrayprobe``, which is a poor
20
+ trade for a package whose reason to exist is that it runs where the heavyweight
21
+ alternative does not. The subset below is small enough to read in one sitting
22
+ and is checked against Octave's own ``load`` on the real ORACLES files
23
+ (``tests/test_matio.py``), so the shortcut is measured rather than assumed.
24
+
25
+ Anything outside the supported subset raises :class:`UnsupportedMatFeature`
26
+ naming what it found. A reader that guessed would be worse than one that stops:
27
+ these files decide which photodiodes get re-illuminated before every downstream
28
+ size and habit calculation.
29
+
30
+ Format reference: *MAT-File Format*, MathWorks, the Level 5 chapter. Both the
31
+ uncompressed (v5/``-v6``) and zlib-wrapped (v7) containers are handled; v7.3 is
32
+ HDF5 and is rejected explicitly, since a v7.3 file would otherwise look like a
33
+ corrupt v5 one.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import zlib
39
+ from dataclasses import dataclass
40
+ from pathlib import Path
41
+
42
+ import numpy as np
43
+
44
+ __all__ = [
45
+ "UnsupportedMatFeature",
46
+ "MatFileError",
47
+ "MatFile",
48
+ "loadmat",
49
+ "savemat",
50
+ ]
51
+
52
+
53
+ class MatFileError(ValueError):
54
+ """The file is not a readable Level 5 MAT-file."""
55
+
56
+
57
+ class UnsupportedMatFeature(MatFileError):
58
+ """A Level 5 MAT-file feature this reader deliberately does not handle."""
59
+
60
+
61
+ # -- Data types (Table 1-1) -------------------------------------------------
62
+
63
+ _MI_INT8 = 1
64
+ _MI_UINT8 = 2
65
+ _MI_INT16 = 3
66
+ _MI_UINT16 = 4
67
+ _MI_INT32 = 5
68
+ _MI_UINT32 = 6
69
+ _MI_SINGLE = 7
70
+ _MI_DOUBLE = 9
71
+ _MI_INT64 = 12
72
+ _MI_UINT64 = 13
73
+ _MI_MATRIX = 14
74
+ _MI_COMPRESSED = 15
75
+ _MI_UTF8 = 16
76
+ _MI_UTF16 = 17
77
+ _MI_UTF32 = 18
78
+
79
+ _MI_NAMES = {
80
+ _MI_INT8: "miINT8", _MI_UINT8: "miUINT8", _MI_INT16: "miINT16",
81
+ _MI_UINT16: "miUINT16", _MI_INT32: "miINT32", _MI_UINT32: "miUINT32",
82
+ _MI_SINGLE: "miSINGLE", _MI_DOUBLE: "miDOUBLE", _MI_INT64: "miINT64",
83
+ _MI_UINT64: "miUINT64", _MI_MATRIX: "miMATRIX",
84
+ _MI_COMPRESSED: "miCOMPRESSED", _MI_UTF8: "miUTF8", _MI_UTF16: "miUTF16",
85
+ _MI_UTF32: "miUTF32",
86
+ }
87
+
88
+ #: Storage type -> numpy dtype *code*, resolved against the file's byte order.
89
+ _MI_DTYPE = {
90
+ _MI_INT8: "i1", _MI_UINT8: "u1", _MI_INT16: "i2", _MI_UINT16: "u2",
91
+ _MI_INT32: "i4", _MI_UINT32: "u4", _MI_SINGLE: "f4", _MI_DOUBLE: "f8",
92
+ _MI_INT64: "i8", _MI_UINT64: "u8",
93
+ # The UTF types carry character data; treat them as their code units and
94
+ # let the char branch decode.
95
+ _MI_UTF8: "u1", _MI_UTF16: "u2", _MI_UTF32: "u4",
96
+ }
97
+
98
+ # -- Array classes (Table 1-3) ----------------------------------------------
99
+
100
+ _MX_CELL = 1
101
+ _MX_STRUCT = 2
102
+ _MX_OBJECT = 3
103
+ _MX_CHAR = 4
104
+ _MX_SPARSE = 5
105
+ _MX_DOUBLE = 6
106
+ _MX_SINGLE = 7
107
+ _MX_INT8 = 8
108
+ _MX_UINT8 = 9
109
+ _MX_INT16 = 10
110
+ _MX_UINT16 = 11
111
+ _MX_INT32 = 12
112
+ _MX_UINT32 = 13
113
+ _MX_INT64 = 14
114
+ _MX_UINT64 = 15
115
+
116
+ _MX_NAMES = {
117
+ _MX_CELL: "cell", _MX_STRUCT: "struct", _MX_OBJECT: "object",
118
+ _MX_CHAR: "char", _MX_SPARSE: "sparse", _MX_DOUBLE: "double",
119
+ _MX_SINGLE: "single", _MX_INT8: "int8", _MX_UINT8: "uint8",
120
+ _MX_INT16: "int16", _MX_UINT16: "uint16", _MX_INT32: "int32",
121
+ _MX_UINT32: "uint32", _MX_INT64: "int64", _MX_UINT64: "uint64",
122
+ }
123
+
124
+ #: The class a value is *presented* as, independent of how it was stored.
125
+ #: MATLAB compresses on write -- a double array whose values all fit in int8 is
126
+ #: stored as miINT8 and must still come back as float64, or a mask of diode
127
+ #: numbers would arrive as int8 and silently wrap at 127.
128
+ _MX_NUMERIC_DTYPE = {
129
+ _MX_DOUBLE: np.float64, _MX_SINGLE: np.float32,
130
+ _MX_INT8: np.int8, _MX_UINT8: np.uint8,
131
+ _MX_INT16: np.int16, _MX_UINT16: np.uint16,
132
+ _MX_INT32: np.int32, _MX_UINT32: np.uint32,
133
+ _MX_INT64: np.int64, _MX_UINT64: np.uint64,
134
+ }
135
+
136
+ _FLAG_COMPLEX = 0x0800
137
+ _FLAG_LOGICAL = 0x0200
138
+
139
+ _HEADER_LEN = 128
140
+
141
+
142
+ @dataclass(frozen=True)
143
+ class MatFile:
144
+ """A loaded MAT-file: its variables plus the header MATLAB stamped on it."""
145
+
146
+ variables: dict[str, np.ndarray | str]
147
+ header: str
148
+ """The 116-byte descriptive text, e.g. ``'MATLAB 5.0 MAT-file, Platform:
149
+ GLNXA64, Created on: Tue Oct 31 21:09:47 2017'``. Kept because it is the
150
+ only provenance a ``save`` file carries -- platform and creation time -- and
151
+ for the ORACLES masks it is what establishes them as 2017 Linux output of
152
+ record rather than something regenerated later."""
153
+
154
+ version: int
155
+ byte_order: str
156
+ """``'<'`` or ``'>'``."""
157
+
158
+ def __getitem__(self, name: str):
159
+ return self.variables[name]
160
+
161
+ def __contains__(self, name: str) -> bool:
162
+ return name in self.variables
163
+
164
+ def keys(self):
165
+ """The variable names in the file, in the order MATLAB wrote them.
166
+
167
+ MAT-file elements are stored sequentially, so this is write order and
168
+ not sorted -- ``dict`` preserves it. That matters for a ``diode.*.mat``
169
+ mask, where the ORACLES files carry one variable and a second name
170
+ appearing would be the signal that the file is not what it claims.
171
+ """
172
+ return self.variables.keys()
173
+
174
+
175
+ def loadmat(path) -> MatFile:
176
+ """Read a Level 5 (v5/v6/v7) MAT-file.
177
+
178
+ Returns a :class:`MatFile`. Numeric arrays come back in MATLAB's shape and
179
+ presented class; char arrays come back as :class:`str` when they are a
180
+ single row (which is every char variable UIOOPS writes) and as an array of
181
+ rows otherwise.
182
+ """
183
+ raw = Path(path).read_bytes()
184
+ if len(raw) < _HEADER_LEN:
185
+ raise MatFileError(
186
+ f"{path}: {len(raw)} bytes is shorter than the 128-byte Level 5 header"
187
+ )
188
+
189
+ if raw[:8] == b"\x89HDF\r\n\x1a\n":
190
+ raise UnsupportedMatFeature(
191
+ f"{path} is a MAT-file v7.3, which is HDF5, not Level 5. Re-save it "
192
+ "with `save(..., '-v7')` or read it with h5py."
193
+ )
194
+
195
+ endian_tag = raw[126:128]
196
+ if endian_tag == b"IM":
197
+ order = "<"
198
+ elif endian_tag == b"MI":
199
+ order = ">"
200
+ else:
201
+ raise MatFileError(
202
+ f"{path}: bytes 126-127 are {endian_tag!r}, expected b'IM' or b'MI'. "
203
+ "This is not a Level 5 MAT-file."
204
+ )
205
+
206
+ header = raw[:116].rstrip(b"\x00 ").decode("latin-1")
207
+ version = int(np.frombuffer(raw[124:126], dtype=order + "u2")[0])
208
+
209
+ variables: dict[str, np.ndarray | str] = {}
210
+ for mi_type, payload in _iter_elements(raw[_HEADER_LEN:], order):
211
+ if mi_type == _MI_COMPRESSED:
212
+ inner = zlib.decompress(payload)
213
+ for inner_type, inner_payload in _iter_elements(inner, order):
214
+ _collect(inner_type, inner_payload, order, variables)
215
+ else:
216
+ _collect(mi_type, payload, order, variables)
217
+
218
+ return MatFile(variables=variables, header=header, version=version,
219
+ byte_order=order)
220
+
221
+
222
+ #: numpy dtype -> (mxClass, miType) for the subset :func:`savemat` writes.
223
+ _SAVE_CLASSES = {
224
+ np.dtype(np.float64): (_MX_DOUBLE, _MI_DOUBLE),
225
+ np.dtype(np.int32): (_MX_INT32, _MI_INT32),
226
+ }
227
+
228
+
229
+ def _element(mi_type: int, payload: bytes) -> bytes:
230
+ """One tagged data element, padded to the 8-byte boundary Level 5 requires."""
231
+ tag = np.array([mi_type, len(payload)], dtype="<u4").tobytes()
232
+ pad = (-len(payload)) % 8
233
+ return tag + payload + b"\x00" * pad
234
+
235
+
236
+ def _matrix_element(name: str, value) -> bytes:
237
+ if isinstance(value, str):
238
+ mx_class, mi_type = _MX_CHAR, _MI_UINT16
239
+ dims = (1, len(value)) if value else (0, 0)
240
+ data = np.array([ord(ch) for ch in value], dtype="<u2").tobytes()
241
+ else:
242
+ arr = np.asarray(value)
243
+ if arr.dtype not in _SAVE_CLASSES:
244
+ raise UnsupportedMatFeature(
245
+ f"savemat writes double and int32 arrays and char rows only; "
246
+ f"{name!r} is {arr.dtype}")
247
+ mx_class, mi_type = _SAVE_CLASSES[arr.dtype]
248
+ if arr.ndim == 0:
249
+ arr = arr.reshape(1, 1)
250
+ elif arr.ndim == 1:
251
+ arr = arr.reshape(-1, 1) # MATLAB has no 1-D arrays; a column
252
+ dims = arr.shape
253
+ data = arr.astype(arr.dtype.newbyteorder("<")).tobytes(order="F")
254
+ flags = np.array([mx_class, 0], dtype="<u4").tobytes()
255
+ body = (_element(_MI_UINT32, flags)
256
+ + _element(_MI_INT32, np.array(dims, dtype="<i4").tobytes())
257
+ + _element(_MI_INT8, name.encode("latin-1"))
258
+ + _element(mi_type, data))
259
+ return _element(_MI_MATRIX, body)
260
+
261
+
262
+ def savemat(path, variables: dict, *, header_text: str | None = None) -> Path:
263
+ """Write a Level 5 MAT-file, uncompressed (MATLAB's ``-v6`` container).
264
+
265
+ The write side of the one requirement this module has: ``find_shadow_diodes.m``'s
266
+ ``save([path ...])`` (``:103-107``), which saves the whole workspace --
267
+ ``a``, ``date``, ``orientation``, ``path``, ``shadow_diode``, ``time``.
268
+ Variables are written in the order given; MATLAB's bare ``save`` writes
269
+ them in ``who`` order, which is alphabetical, and the caller passes them so.
270
+
271
+ Supports exactly what that file holds: double and int32 arrays (1-D taken
272
+ as a column, the shape ``find`` and ``ncread`` return) and single-row char.
273
+ MATLAB's default ``save`` is ``-v7`` (zlib-compressed); the container is
274
+ not a computed number, :func:`loadmat` and MATLAB's ``load`` read both, and
275
+ the 116-byte header text carries a creation time in any case, so no
276
+ ``.mat`` file is byte-reproducible across two ``save`` calls.
277
+ """
278
+ path = Path(path)
279
+ if header_text is None:
280
+ import time as _time
281
+ header_text = ("MATLAB 5.0 MAT-file, Platform: arrayprobe, Created on: "
282
+ + _time.strftime("%a %b %d %H:%M:%S %Y"))
283
+ text = header_text.encode("latin-1")[:116].ljust(116, b" ")
284
+ header = text + b"\x00" * 8 + np.array([0x0100], dtype="<u2").tobytes() + b"IM"
285
+ body = b"".join(_matrix_element(k, v) for k, v in variables.items())
286
+ path.write_bytes(header + body)
287
+ return path
288
+
289
+
290
+ def _collect(mi_type, payload, order, variables):
291
+ if mi_type != _MI_MATRIX:
292
+ # Level 5 permits only miMATRIX (and miCOMPRESSED wrapping one) at the
293
+ # top level. Anything else means the parse has lost alignment, and
294
+ # continuing would invent variables.
295
+ raise MatFileError(
296
+ f"top-level element is {_MI_NAMES.get(mi_type, mi_type)}, "
297
+ "expected miMATRIX"
298
+ )
299
+ name, value = _read_matrix(payload, order)
300
+ variables[name] = value
301
+
302
+
303
+ def _iter_elements(buf, order):
304
+ """Yield ``(type, payload)`` for each data element, honouring 8-byte padding."""
305
+ pos = 0
306
+ n = len(buf)
307
+ u4 = np.dtype(order + "u4")
308
+ while pos + 8 <= n:
309
+ first = int(np.frombuffer(buf, dtype=u4, count=1, offset=pos)[0])
310
+ if first == 0:
311
+ # A zero type tag is not a legal element; it is the zero padding
312
+ # that follows the last one. Stop rather than inventing a variable.
313
+ break
314
+ # Small Data Element Format: if the upper two bytes of the first word
315
+ # are non-zero they hold the byte count and the lower two the type, and
316
+ # the payload is the next four bytes. Missing this is the classic way
317
+ # a hand-rolled reader desynchronises.
318
+ if first >> 16:
319
+ nbytes = first >> 16
320
+ mi_type = first & 0xFFFF
321
+ payload = buf[pos + 4:pos + 4 + nbytes]
322
+ pos += 8
323
+ else:
324
+ mi_type = first
325
+ nbytes = int(np.frombuffer(buf, dtype=u4, count=1, offset=pos + 4)[0])
326
+ payload = buf[pos + 8:pos + 8 + nbytes]
327
+ if len(payload) < nbytes:
328
+ raise MatFileError(
329
+ f"element of type {_MI_NAMES.get(mi_type, mi_type)} declares "
330
+ f"{nbytes} bytes but only {len(payload)} remain"
331
+ )
332
+ pos += 8 + nbytes
333
+ # Every element is padded out to an 8-byte boundary EXCEPT
334
+ # miCOMPRESSED, which the format leaves unpadded. Padding a
335
+ # compressed element anyway walks the cursor two bytes past the
336
+ # start of the next one, and the parse then reads a garbage tag --
337
+ # which is exactly how this reader failed first time round.
338
+ if mi_type != _MI_COMPRESSED and pos % 8:
339
+ pos += 8 - (pos % 8)
340
+ yield mi_type, payload
341
+ # Trailing bytes shorter than a tag are padding, not an error.
342
+
343
+
344
+ def _read_matrix(payload, order):
345
+ """Parse one miMATRIX element into ``(name, value)``."""
346
+ subs = list(_iter_elements(payload, order))
347
+ if len(subs) < 3:
348
+ raise MatFileError(
349
+ f"miMATRIX has {len(subs)} subelements; expected at least "
350
+ "array flags, dimensions and name"
351
+ )
352
+
353
+ flags_words = _as_array(subs[0], order)
354
+ flags = int(flags_words[0])
355
+ mx_class = flags & 0xFF
356
+
357
+ if mx_class in (_MX_CELL, _MX_STRUCT, _MX_OBJECT, _MX_SPARSE):
358
+ raise UnsupportedMatFeature(
359
+ f"{_MX_NAMES[mx_class]} arrays are not supported. The UIOPS sidecars "
360
+ "this reader exists for contain only flat numeric and char arrays; "
361
+ "guessing at a container type would be worse than stopping."
362
+ )
363
+ if flags & _FLAG_COMPLEX:
364
+ raise UnsupportedMatFeature("complex arrays are not supported")
365
+
366
+ dims = tuple(int(d) for d in _as_array(subs[1], order))
367
+ name_bytes = _as_array(subs[2], order).astype(np.uint8).tobytes()
368
+ name = name_bytes.decode("latin-1")
369
+
370
+ if len(subs) < 4:
371
+ # An empty array still carries a (possibly zero-length) data element in
372
+ # every file MATLAB writes; treat its absence as empty rather than an
373
+ # error, since `shadow_diode = []` is a case that genuinely occurs.
374
+ data = np.zeros(0, dtype=np.uint8)
375
+ else:
376
+ data = _as_array(subs[3], order)
377
+
378
+ if mx_class == _MX_CHAR:
379
+ return name, _to_char(data, dims)
380
+
381
+ dtype = _MX_NUMERIC_DTYPE.get(mx_class)
382
+ if dtype is None:
383
+ raise UnsupportedMatFeature(f"array class {mx_class} is not supported")
384
+ if flags & _FLAG_LOGICAL:
385
+ dtype = np.bool_
386
+
387
+ # MATLAB stores column-major; reshape in Fortran order so the array keeps
388
+ # the shape and element order it had in the workspace.
389
+ return name, np.asarray(data, dtype=dtype).reshape(dims, order="F")
390
+
391
+
392
+ def _as_array(element, order):
393
+ mi_type, payload = element
394
+ code = _MI_DTYPE.get(mi_type)
395
+ if code is None:
396
+ raise UnsupportedMatFeature(
397
+ f"data element type {_MI_NAMES.get(mi_type, mi_type)} is not supported"
398
+ )
399
+ return np.frombuffer(payload, dtype=np.dtype(order + code))
400
+
401
+
402
+ def _to_char(data, dims):
403
+ """Char arrays: one row comes back as ``str``, several as an array of rows."""
404
+ codes = np.asarray(data).astype(np.uint32).reshape(dims, order="F")
405
+ if codes.ndim <= 1 or (codes.ndim == 2 and codes.shape[0] <= 1):
406
+ return "".join(chr(int(c)) for c in codes.ravel(order="F"))
407
+ return np.array(
408
+ ["".join(chr(int(c)) for c in row) for row in codes],
409
+ dtype=object,
410
+ )
@@ -0,0 +1,13 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ import sys as _sys
3
+ import typing as _typing
4
+
5
+ from arrayprobe_uiops import matlab_compat as _impl
6
+
7
+ # Static view for type checkers only: the alias below replaces this module at run time,
8
+ # so mypy would otherwise see an empty module. No run-time effect.
9
+ if _typing.TYPE_CHECKING:
10
+ from arrayprobe_uiops.matlab_compat import * # noqa: F403
11
+ from arrayprobe_uiops.matlab_compat import msum # noqa: F401 -- not in its __all__
12
+
13
+ _sys.modules[__name__] = _impl
arrayprobe/ncio.py ADDED
@@ -0,0 +1,26 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Alias of :mod:`arrayprobe_uiops.ncio`, the MATLAB ``netcdf.*`` layer both engines write through.
3
+
4
+ The module moved to the v3.5 engine on 2026-10-03 (code both engines share lives
5
+ there, so deleting this package breaks nothing else; the author approved the netCDF layer joining
6
+ the shared set although it imports netCDF4). This file keeps ``from arrayprobe import ncio``
7
+ working for the v3.1.4 callers and computes nothing.
8
+
9
+ The star import gives static readers (mypy, ruff) the public names; the ``sys.modules`` line
10
+ then makes ``arrayprobe.ncio`` the *same module object*, so a patch, ``__file__`` and the
11
+ private helpers (``_quiet_netcdf4_setitem``, ``_c_order``) all resolve to the real module rather
12
+ than to a copy of its namespace.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import sys
18
+
19
+ from arrayprobe_uiops import ncio as _impl
20
+ from arrayprobe_uiops.ncio import * # noqa: F401,F403
21
+ from arrayprobe_uiops.ncio import __all__ # noqa: F401
22
+ from arrayprobe_uiops.ncio import ( # noqa: F401 (private, for attributed_export)
23
+ _quiet_netcdf4_setitem as _quiet_netcdf4_setitem,
24
+ )
25
+
26
+ sys.modules[__name__] = _impl
arrayprobe/particle.py ADDED
@@ -0,0 +1,55 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """The canonical in-memory particle image, and the MATLAB char matrix it replaces.
3
+
4
+ UIOOPS carries a particle as a MATLAB **char matrix** ``c`` of shape
5
+ ``(n_slices, diodenum)`` whose entries are the characters ``'0'`` and ``'1'``.
6
+ The encoding is the one photodiodes actually report and is the opposite of the
7
+ intuitive reading:
8
+
9
+ * ``'0'`` -- the diode was **shadowed**: particle present.
10
+ * ``'1'`` -- the diode was lit: no particle.
11
+
12
+ Every ported routine that touches an image agrees on that, because MATLAB spells
13
+ it out at each site (``holroyd.m:139``, ``calculate_reject_unified.m:386``,
14
+ ``imgProc_sm.m:801`` ``sum(c=='0',1)``, ``CGAL_minR.cpp:63`` comparing to 48).
15
+
16
+ The plan's canonical representation is a boolean array, ``True`` = shadowed, and
17
+ :func:`shadow_mask` is the one place that conversion happens. It accepts the
18
+ char matrix too, so a call site can pass whichever form it is holding without
19
+ each module inventing its own coercion.
20
+
21
+ **Why the char matrix cannot simply be dropped.** Two ported routines do
22
+ *bit* arithmetic on it -- ``calculate_reject_unified.m:465-491`` packs sixteen
23
+ characters at a time through ``bin2dec`` -- and there the polarity inverts once
24
+ more: ``bin2dec`` reads ``'1'`` as a set bit, so the packed integers have bits
25
+ set where the particle is **absent**. :func:`as_char` exists so that layer can
26
+ be read against the MATLAB line by line; the packing itself lives with its only
27
+ caller, as :func:`arrayprobe.reject._pack`, because it needs that module's
28
+ 1-based window arguments and its out-of-range behaviour.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import numpy as np
34
+
35
+ from arrayprobe_uiops.particle import ( # noqa: F401 -- shared leaf
36
+ _SHADOWED_ORD,
37
+ LIT,
38
+ SHADOWED,
39
+ shadow_mask,
40
+ )
41
+
42
+ __all__ = ["SHADOWED", "LIT", "shadow_mask", "as_char"]
43
+
44
+
45
+ def as_char(shadow) -> np.ndarray:
46
+ """The MATLAB char matrix for a boolean shadow array -- the fidelity view.
47
+
48
+ Inverse of :func:`shadow_mask` for boolean input. Serves to read ported code
49
+ against the MATLAB it came from, and by tests that need to hand a literal
50
+ ``'0'``/``'1'`` matrix to a routine.
51
+ """
52
+ shadow = np.asarray(shadow, dtype=bool)
53
+ return np.where(shadow, SHADOWED, LIT)
54
+
55
+
@@ -0,0 +1,12 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ import sys as _sys
3
+ import typing as _typing
4
+
5
+ from arrayprobe_uiops import particle_perimeter as _impl
6
+
7
+ # Static view for type checkers only: the alias below replaces this module at run time,
8
+ # so mypy would otherwise see an empty module. No run-time effect.
9
+ if _typing.TYPE_CHECKING:
10
+ from arrayprobe_uiops.particle_perimeter import * # noqa: F403
11
+
12
+ _sys.modules[__name__] = _impl
arrayprobe/products.py ADDED
@@ -0,0 +1,78 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Open a product file as an :class:`xarray.Dataset`, read exactly as written.
3
+
4
+ Every netCDF file this package writes (decoded images, ``proc`` particle files, ``sd`` size
5
+ distributions, combined flight files) opens the same way for analysis. :func:`open_product` sets
6
+ the decode choices once, so a notebook or script does not repeat them::
7
+
8
+ import arrayprobe as ap
9
+
10
+ sd = ap.open_product("sd.nc") # raw values, as the file stores them
11
+ sd["conc_minR"].isel(Time=slice(0, 5))
12
+ sd["time"].attrs["units"] # 'HHMMSS': a clock reading, not CF time
13
+
14
+ It reads and computes nothing. Attributes are returned verbatim, including names with spaces
15
+ (``'Creation Time'``, ``'SA Method'``) and the two spellings ``Units`` and ``units`` that
16
+ different stages write; nothing is renamed or added.
17
+
18
+ ``xarray`` is optional: install it with ``pip install arrayprobe[zarr]`` (the extra that already
19
+ carries it) or ``pip install xarray``. Importing this module needs neither.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from os import PathLike
25
+
26
+ #: The extra whose requirements include xarray.
27
+ XARRAY_EXTRA = "zarr"
28
+
29
+ #: The decode modes :func:`open_product` accepts.
30
+ DECODE_MODES = ("raw", "cf")
31
+
32
+
33
+ def open_product(path: str | PathLike[str], *, decode: str = "raw", load: bool = True):
34
+ """Open the netCDF product at ``path`` and return an ``xarray.Dataset``.
35
+
36
+ ``decode`` chooses how values are read:
37
+
38
+ ``"raw"`` (default)
39
+ The stored values, untouched: no ``_FillValue`` masking, no ``scale_factor`` /
40
+ ``add_offset``, and integer variables keep their integer dtype. This is MATLAB's
41
+ ``netcdf.getVar`` view and the one every comparison against an archived product uses.
42
+ ``"cf"``
43
+ Masking and scaling applied (fill values become NaN, packed integers are unpacked to
44
+ floating point): MATLAB's ``ncread`` view.
45
+
46
+ In both modes times are not decoded: the products store clock readings such as ``HHMMSS``
47
+ and ``YYYYMMDD`` that are not CF time, so ``time`` stays the number in the file. Coordinate
48
+ attributes are not interpreted, and attributes are carried verbatim.
49
+
50
+ With ``load=True`` (default) the values are read into memory and the file is closed before
51
+ returning, so the Dataset stays usable after the file is moved or rewritten and no handle is
52
+ left open. ``load=False`` returns a lazily read Dataset whose file stays open until
53
+ ``ds.close()``.
54
+
55
+ Raises ``ImportError`` naming the extra when xarray is not installed, and ``ValueError``
56
+ for an unknown ``decode``.
57
+ """
58
+ if decode not in DECODE_MODES:
59
+ raise ValueError(f"decode must be one of {DECODE_MODES}, not {decode!r}")
60
+ try:
61
+ import xarray as xr # lazy: optional, not a core dependency
62
+ except ImportError as exc:
63
+ raise ImportError(
64
+ f"open_product needs xarray, which is not installed ({exc}). Install it with "
65
+ f"`pip install arrayprobe[{XARRAY_EXTRA}]` or `pip install xarray`; reading a "
66
+ f"product with netCDF4 directly needs neither.") from exc
67
+ ds = xr.open_dataset(
68
+ path,
69
+ engine="netcdf4",
70
+ mask_and_scale=(decode == "cf"),
71
+ decode_times=False,
72
+ decode_timedelta=False,
73
+ decode_coords=False,
74
+ )
75
+ if not load:
76
+ return ds
77
+ with ds:
78
+ return ds.load()