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,569 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """``IntArrAnalysis_time.m`` -- per-particle inter-arrival thresholds, and the file they go in.
3
+
4
+ The driver around :mod:`arrayprobe.intarr`'s bimodal fit: read a combined per-particle file,
5
+ split it into populations, fit each one, pick a threshold, and write the ``.cdf`` that
6
+ ``sizeDist`` accepts as its optional twelfth argument.
7
+
8
+ **This stage's output was never consumed by the ORACLES products this project validates
9
+ against.** The production call named a threshold file that does not exist, so ``sizeDist.m:70``
10
+ set ``iaThreshFile = 'NONE'`` and ``:874`` fell back to the per-probe constant. Porting the
11
+ stage completes the package and enables the time-dependent path for other campaigns; it changes
12
+ no number that can currently be checked against a reference product.
13
+
14
+
15
+ Source of record is the ORACLES-variant ``IntArrAnalysis_time.m`` (the lineage that processed
16
+ ORACLES), **not** the stock tree's differently-shaped ``IntArrAnalysis.m``.
17
+
18
+ **The remaining routines (author-directed: all three opt-in, default OFF, so the existing default
19
+ behaviour above is unchanged byte-for-byte):**
20
+
21
+ * The diagnostic contour plot -- :mod:`arrayprobe.intarr_plots`, imported lazily, never required
22
+ to import this module. Its time axis reproduces the NaN pre-10:00 timestamps
23
+ (``IntArrAnalysis_time.m:243-250`` -- ``num2str`` right-justifies a mixed-width time column, so
24
+ the ``< 100000`` branch reads a padding space as the hour digit and every pre-10:00:00
25
+ particle's axis value becomes NaN once the same file also has a particle at or after 10:00:00).
26
+ :func:`overlay_time_axis` below reproduces this by default (``fix_b8=False``); a separate,
27
+ also opt-in ``fix_b8=True`` gives the corrected axis. :func:`contour_time_axis` is the
28
+ source's *other*, width-aware time formula (``:258-269``), which is not B8-affected -- it
29
+ already skips the padding column, kept faithfully rather than "fixed" since it is not a bug.
30
+ * The ``.mat`` workspace dump -- :func:`write_mat_workspace`, ``scipy.io`` imported lazily.
31
+ * The two thresholds ``threshhold``/``threshhold_ww`` the source computes but never writes
32
+ (``:367`` writes only ``threshhold_ak``) -- already returned unconditionally by :func:`analyse`
33
+ below (every key in its dict, always; nothing here is gated on an option, because returning an
34
+ already-computed Python value writes nothing and changes no file). What is newly opt-in is
35
+ *persisting* them anywhere: :func:`write_extra_thresholds_sidecar` writes a JSON sidecar (never
36
+ a netCDF file -- the fidelity doctrine reserves "writes a variable MATLAB never wrote" for
37
+ ``enhancements_uiops/``, and this project only has authorisation to expose the values,
38
+ not to
39
+ add them to the ``.cdf``).
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import json
45
+
46
+ import numpy as np
47
+
48
+ from . import ncio
49
+ from .intarr import bimodal_model, fit_bimodal_intarr
50
+ from .matlab_compat import datenum, datestr
51
+
52
+ __all__ = [
53
+ "DEFAULT_THRESHOLD",
54
+ "HIST_BINS",
55
+ "CONTOUR_BINS",
56
+ "inter_arrival",
57
+ "population_size",
58
+ "block_thresholds",
59
+ "analyse",
60
+ "write_threshold_file",
61
+ "contour_data",
62
+ "overlay_time_axis",
63
+ "contour_time_axis",
64
+ "expand_tau_per_particle",
65
+ "write_extra_thresholds_sidecar",
66
+ "write_mat_workspace",
67
+ ]
68
+
69
+ #: ``:157``, ``:186-187`` -- the value every threshold in a block takes when the fit fails.
70
+ DEFAULT_THRESHOLD = 1.3494e-6
71
+
72
+ #: ``:106`` -- 35 edges, 34 bins, log-spaced over seven decades.
73
+ HIST_BINS = np.logspace(-7, 0, 35)
74
+
75
+ #: ``:107`` -- the source takes the log-width of the first bin and uses it for all of them.
76
+ _WIDTH = float(np.log(HIST_BINS[1]) - np.log(HIST_BINS[0]))
77
+
78
+ #: ``:220`` -- the *contour* plot's own, finer histogram: 70 edges, 69 bins, same seven-decade
79
+ #: log range. Deliberately different resolution from the fit's ``HIST_BINS``; both are the
80
+ #: source's own choice, not a port inconsistency.
81
+ CONTOUR_BINS = np.logspace(-7, 0, 70)
82
+
83
+ #: ``:272`` -- the contour fill levels, ``0.005:0.005:0.1`` in MATLAB colon notation (20 levels,
84
+ #: inclusive of both ends). Built from an integer count rather than ``np.arange`` so float steps
85
+ #: cannot silently drop or duplicate the last level.
86
+ CONTOUR_LEVELS = 0.005 * np.arange(1, 21)
87
+
88
+ #: ``:130`` -- initial guess for (tau1, tau2, fraction).
89
+ _BETA0 = (1e-2, 1e-6, 0.5)
90
+
91
+ #: ``:110-111`` -- anything slower than this is zeroed rather than dropped.
92
+ _MAX_INTER_ARRIVAL = 0.1
93
+
94
+
95
+ def inter_arrival(time_in_seconds):
96
+ """``:73-75``, ``:93``, ``:105-111`` -- the source's inter-arrival vector, in its own order.
97
+
98
+ The first particle gets 0, the rest are differences; then ``<= 0`` becomes NaN (which takes
99
+ that leading 0 with it), and anything above 0.1 s is set to **0, not dropped**. The two steps
100
+ are ordered as the source orders them: the ``< 0 -> 0`` line at ``:110`` is a no-op once the
101
+ NaN step has run, and is kept for transcription completeness.
102
+ """
103
+ t = np.asarray(time_in_seconds, dtype=float)
104
+ out = np.empty(t.size, dtype=float)
105
+ if t.size == 0:
106
+ return out
107
+ out[0] = 0.0
108
+ out[1:] = np.diff(t)
109
+ out[out <= 0] = np.nan # :93
110
+ out[out < 0] = 0.0 # :110, unreachable after the line above
111
+ out[out > _MAX_INTER_ARRIVAL] = 0.0 # :111
112
+ return out
113
+
114
+
115
+ def population_size(timehhmmss, n_blocks):
116
+ """``:112-119`` -- how many particles go into each bimodal fit.
117
+
118
+ ``ceil(N / n_blocks)`` unless the most crowded second holds at least that many, in which case
119
+ the block is that second's count rounded **up to the next quarter** of the base size. Coarse
120
+ by design; reproduced as written.
121
+ """
122
+ t = np.asarray(timehhmmss)
123
+ n = t.size
124
+ if n == 0 or n_blocks <= 0:
125
+ raise ValueError("need particles and a positive block count")
126
+ base = int(np.ceil(n / n_blocks))
127
+ values, counts = np.unique(t, return_counts=True)
128
+ busiest = int(counts.max()) # numel(find(t == mode(t)))
129
+ if busiest < base:
130
+ return base
131
+ quarter = base / 4
132
+ return int(quarter * np.ceil(busiest / quarter))
133
+
134
+
135
+ def block_thresholds(counts, *, beta0=_BETA0):
136
+ """``:139-190`` for one population: ``(threshold, threshold_ww, threshold_ak, tau)``.
137
+
138
+ ``counts`` is the raw histogram of the block's inter-arrival times over :data:`HIST_BINS`.
139
+ All three of the source's thresholds are returned; only ``threshold_ak`` is written to the
140
+ output file, as the source writes it (``:367``).
141
+ """
142
+ centres = HIST_BINS[:-1] + np.diff(HIST_BINS) / 2
143
+ h = np.asarray(counts, dtype=float)
144
+ if h.sum() == 0:
145
+ return DEFAULT_THRESHOLD, DEFAULT_THRESHOLD, DEFAULT_THRESHOLD, None
146
+
147
+ tau = fit_bimodal_intarr(centres, h, _WIDTH, beta0=beta0)
148
+ if np.isnan(tau).any(): # :156-158
149
+ return DEFAULT_THRESHOLD, DEFAULT_THRESHOLD, DEFAULT_THRESHOLD, tau
150
+
151
+ threshold = float(np.min(tau[:2]) * 2) # :159
152
+ hi, lo = float(np.max(tau[:2])), float(np.min(tau[:2])) # :170
153
+ fitted = bimodal_model(tau, centres)
154
+ between = (centres < hi) & (centres > lo) # :171
155
+
156
+ if not between.any(): # :173-177, Finlon's guard
157
+ left = np.flatnonzero(centres < hi)
158
+ right = np.flatnonzero(centres > lo)
159
+ if left.size == 0 or right.size == 0: # :183-188
160
+ return threshold, DEFAULT_THRESHOLD, DEFAULT_THRESHOLD, tau
161
+ pick = np.array([left[-1], right[0]])
162
+ new_dt = centres[pick]
163
+ i_fit = int(np.argmin(fitted[pick]))
164
+ i_obs = int(np.argmin(h[pick]))
165
+ else:
166
+ new_dt = centres[between]
167
+ i_fit = int(np.argmin(fitted[between]))
168
+ i_obs = int(np.argmin(h[between]))
169
+
170
+ return threshold, float(new_dt[i_fit]), float(new_dt[i_obs]), tau
171
+
172
+
173
+ def analyse(int_arr, timehhmmss, *, n_blocks=5, beta0=_BETA0, collect_histograms=False):
174
+ """Run the whole population loop. Returns a dict of per-particle arrays.
175
+
176
+ Keys: ``threshold``, ``threshold_ww``, ``threshold_ak`` (each one value per particle, constant
177
+ within a block), ``tau`` (one row per block), ``population_size``, ``block_starts``. All
178
+ three thresholds are always returned -- the source itself computes all three and writes only
179
+ ``threshold_ak`` (``:367``); returning the other two here writes nothing and changes no file,
180
+ so it needs no opt-in (see the module docstring's note on the remaining inter-arrival work).
181
+
182
+ ``collect_histograms=False`` (default) leaves this function's return value byte-for-byte
183
+ identical to a call without the option: no extra key appears and nothing above is computed
184
+ differently. ``collect_histograms=True`` additionally returns ``hist2dc``
185
+ -- ``:106,148`` -- the raw 34-bin histogram counts per block (one row per block), needed only by
186
+ :func:`write_mat_workspace`.
187
+ """
188
+ arr = np.asarray(int_arr, dtype=float)
189
+ n = arr.size
190
+ size = population_size(timehhmmss, n_blocks)
191
+ out = {k: np.empty(n, dtype=float) for k in ("threshold", "threshold_ww", "threshold_ak")}
192
+ taus, starts, hists = [], [], []
193
+ for start in range(0, n, size): # :139
194
+ end = min(start + size, n)
195
+ block = arr[start:end]
196
+ counts, _ = np.histogram(block[~np.isnan(block)], bins=HIST_BINS)
197
+ thr, ww, ak, tau = block_thresholds(counts, beta0=beta0)
198
+ out["threshold"][start:end] = thr
199
+ out["threshold_ww"][start:end] = ww
200
+ out["threshold_ak"][start:end] = ak
201
+ taus.append(tau if tau is not None else np.full(3, np.nan))
202
+ starts.append(start)
203
+ if collect_histograms:
204
+ hists.append(counts.astype(float))
205
+ out["tau"] = np.asarray(taus, dtype=float)
206
+ out["block_starts"] = np.asarray(starts, dtype=int)
207
+ out["population_size"] = size
208
+ if collect_histograms:
209
+ out["hist2dc"] = np.asarray(hists, dtype=float) # :106,148
210
+ return out
211
+
212
+
213
+ def write_threshold_file(filename, timehhmmss, threshold, *, probename, flight_date,
214
+ data_source, population_size, creation_time=None):
215
+ """``:336-368`` -- the file ``sizeDist`` reads as its twelfth argument.
216
+
217
+ Attribute names, order, units and variable names follow the source exactly; ``Creation Time``
218
+ is overridable so two runs can be compared byte for byte.
219
+ """
220
+ times = np.asarray(timehhmmss, dtype=float)
221
+ values = np.asarray(threshold, dtype=float)
222
+ if times.shape != values.shape:
223
+ raise ValueError(f"time and threshold must match: {times.shape} vs {values.shape}")
224
+
225
+ f = ncio.create(filename, "clobber")
226
+ dim = f.def_dim("particleTime", times.size)
227
+ g = ncio.NC_GLOBAL
228
+ f.put_att(g, "Software", "UIOOPS/IntArrAnalysis_revised")
229
+ f.put_att(g, "Institution", "Univ. Oklahoma, SoM")
230
+ f.put_att(g, "Creation Time",
231
+ creation_time if creation_time is not None
232
+ else datestr(None, "yyyy/mm/dd HH:MM:SS"))
233
+ f.put_att(g, "Description", "Contains inter-arrival threshold information for each particle "
234
+ "following Field et al. (2006)")
235
+ f.put_att(g, "Flight Date", str(flight_date))
236
+ f.put_att(g, "Data Source", str(data_source))
237
+ f.put_att(g, "Probe Type", str(probename))
238
+ f.put_att(g, "Population Size", f"{population_size} particles per distribution fit")
239
+
240
+ vid_time = f.def_var("particle_time", "double", dim)
241
+ f.put_att(vid_time, "units", "HHMMSS")
242
+ f.put_att(vid_time, "name", "Time")
243
+ vid_thr = f.def_var("threshold", "double", dim)
244
+ f.put_att(vid_thr, "units", "sec")
245
+ f.put_att(vid_thr, "name", "Inter-arrival time threshold in n-particle blocks")
246
+
247
+ f.end_def()
248
+ f.put_var(vid_time, times)
249
+ f.put_var(vid_thr, values)
250
+ f.close()
251
+ return filename
252
+
253
+
254
+ # --------------------------------------------------------------------------
255
+ # The interarrival remainder: the contour plot's data, the .mat dump, and the two
256
+ # unwritten thresholds' sidecar. All opt-in; nothing above this point changes.
257
+ # --------------------------------------------------------------------------
258
+
259
+ def _intarr_pre_clip(time_in_seconds):
260
+ """The source's own ``intarr`` variable's *final* value (``:73-75``, ``:93`` only).
261
+
262
+ Unlike ``int_arr`` -- which goes on to receive the ``:110-111`` clipping and is what
263
+ :func:`inter_arrival` returns -- the source never touches ``intarr`` again after the
264
+ ``<=0 -> NaN`` step at ``:91``, so what ends up in the workspace under that name is the
265
+ NaN-only-clipped inter-arrival vector, without the later ``>0.1 -> 0`` zeroing. Needed only
266
+ for :func:`write_mat_workspace`, which writes both under their own MATLAB names.
267
+ """
268
+ t = np.asarray(time_in_seconds, dtype=float)
269
+ out = np.empty(t.size, dtype=float)
270
+ if t.size == 0:
271
+ return out
272
+ out[0] = 0.0
273
+ out[1:] = np.diff(t)
274
+ out[out <= 0] = np.nan # :91
275
+ return out
276
+
277
+
278
+ def contour_data(int_arr, timehhmmss, date, size):
279
+ """``:220-236`` -- the contour plot's own, coarser-fit-but-finer-bin per-block histogram.
280
+
281
+ A second population loop over the *same* blocks :func:`analyse` uses (``size`` is its
282
+ ``population_size``), but histogrammed into :data:`CONTOUR_BINS` (69 bins, not 34) and
283
+ without any fitting -- the source only ever plots this one, it does not fit it.
284
+
285
+ Returns ``(hist2dc_contour, new_time2dc, new_date2dc)``. ``:235-236`` overwrites the *last*
286
+ block's own recorded start time/date with the sequence's very last particle's time/date --
287
+ reproduced here exactly, including on a single-block input.
288
+ """
289
+ arr = np.asarray(int_arr, dtype=float)
290
+ t = np.asarray(timehhmmss, dtype=float)
291
+ d = np.asarray(date, dtype=float)
292
+ n = arr.size
293
+ if n == 0 or size <= 0:
294
+ raise ValueError("need particles and a positive block size")
295
+ n_blocks = int(np.ceil(n / size))
296
+ hist = np.zeros((n_blocks, len(CONTOUR_BINS) - 1), dtype=float)
297
+ new_time = np.empty(n_blocks, dtype=float)
298
+ new_date = np.empty(n_blocks, dtype=float)
299
+ row = 0
300
+ for start in range(0, n, size): # :225
301
+ end = min(start + size, n)
302
+ block = arr[start:end]
303
+ counts, _ = np.histogram(block[~np.isnan(block)], bins=CONTOUR_BINS)
304
+ hist[row, :] = counts
305
+ new_time[row] = t[start]
306
+ new_date[row] = d[start]
307
+ row += 1
308
+ new_time[row - 1] = t[-1] # :235
309
+ new_date[row - 1] = d[-1] # :236
310
+ return hist, new_time, new_date
311
+
312
+
313
+ def _num2str_int_column(values):
314
+ """MATLAB ``num2str`` on a column vector of non-negative integer-valued doubles.
315
+
316
+ ``num2str`` on a numeric *column* right-justifies every row to one common width -- the
317
+ mechanism the NaN pre-10:00 timestamps turn on. ``timehhmmss``/``date`` values here are always
318
+ whole-number HHMMSS/YYYYMMDD doubles (read straight off netCDF), so ``str(int(round(v)))``
319
+ reproduces MATLAB's own default integer formatting exactly. Returns ``(rows, width)``.
320
+ """
321
+ strs = [str(int(round(v))) for v in np.asarray(values, dtype=float)]
322
+ width = max((len(s) for s in strs), default=0)
323
+ return [s.rjust(width) for s in strs], width
324
+
325
+
326
+ def _str2double(s):
327
+ """MATLAB ``str2double`` of one substring: NaN if all blank (the NaN pre-10:00 timestamps)."""
328
+ s = s.strip()
329
+ return float("nan") if not s else float(s)
330
+
331
+
332
+ def _time2datenum(date_value):
333
+ """The ORACLES-variant ``time2datenum.m``'s numeric-``datestring`` branch (``:174-181``), called
334
+ (as the source calls it, ``:246`` etc.) with a single argument -- no ``timestring``, so
335
+ ``HH=MI=SC=0`` and only the ``yyyymmdd`` decomposition of ``date_value`` matters.
336
+ """
337
+ yy = np.floor(date_value / 10000)
338
+ mm = np.floor((date_value - 10000 * yy) / 100)
339
+ dd = np.floor(date_value - 10000 * yy - 100 * mm)
340
+ return datenum(yy, mm, dd, 0, 0, 0)
341
+
342
+
343
+ def _time_of_day_fraction(hh, mi, sc):
344
+ """MATLAB ``datenum(0,0,0,HH,MI,SC)`` -- the source's own idiom at ``:246-267`` for adding a
345
+ time-of-day offset to a whole-day ``time2datenum`` value, called as written.
346
+
347
+ It replaces a local ``HH/24 + MI/1440 + SC/86400``, which differs from Octave's
348
+ ``(HH + (MI + SC/60)/60)/24`` by one ulp on about 40 % of instants; added to a whole-day
349
+ datenum of any real date the two give the same bits (``tests/test_datenum_octave_oracle.py``).
350
+ """
351
+ return datenum(0, 0, 0, hh, mi, sc)
352
+
353
+
354
+ def overlay_time_axis(timehhmmss, date, *, fix_b8=False):
355
+ """``:243-250`` -- the per-particle datenum axis for the threshold-overlay lines.
356
+
357
+ ``fix_b8=False`` (default, matching every real run of the source) reproduces the upstream
358
+ finding that a mixed-width time vector puts NaN into every pre-10:00 timestamp:
359
+ ``num2str`` right-justifies the whole ``timehhmmss`` column to one common width,
360
+ so in a file spanning 10:00:00 every row before it is left-padded with a space and the
361
+ ``< 100000`` branch reads that pad as the hour digit -- ``str2double`` of a blank is NaN.
362
+ ``fix_b8=True`` computes the same value directly from the integer,
363
+ never touching a string.
364
+ """
365
+ t = np.asarray(timehhmmss, dtype=float)
366
+ d = np.asarray(date, dtype=float)
367
+ if t.shape != d.shape:
368
+ raise ValueError(f"timehhmmss and date must match: {t.shape} vs {d.shape}")
369
+ n = t.size
370
+ out = np.empty(n, dtype=float)
371
+
372
+ if fix_b8:
373
+ hh = np.floor(t / 10000.0)
374
+ mi = np.floor(np.mod(t, 10000.0) / 100.0)
375
+ sc = np.mod(t, 100.0)
376
+ for k in range(n):
377
+ out[k] = _time2datenum(d[k]) + _time_of_day_fraction(hh[k], mi[k], sc[k])
378
+ return out
379
+
380
+ rows, _width = _num2str_int_column(t) # :243
381
+ for k in range(n): # :244-250
382
+ row = rows[k]
383
+ if t[k] < 100000:
384
+ hh = _str2double(row[0:1])
385
+ mi = _str2double(row[1:3])
386
+ sc = _str2double(row[3:5])
387
+ else:
388
+ hh = _str2double(row[0:2])
389
+ mi = _str2double(row[2:4])
390
+ sc = _str2double(row[4:6])
391
+ out[k] = _time2datenum(d[k]) + _time_of_day_fraction(hh, mi, sc)
392
+ return out
393
+
394
+
395
+ def contour_time_axis(new_time2dc, new_date2dc):
396
+ """``:258-269`` -- the contour plot's own per-block ``x`` axis.
397
+
398
+ A *different* formula from :func:`overlay_time_axis`, and -- unlike it -- not affected by that
399
+ NaN: it branches on ``size(y,2)`` (the char matrix's actual width) rather than always slicing
400
+ the same fixed columns, so the width-6 case correctly reads column 2 (a single digit) as the
401
+ hour rather than column 1 (the padding space). Kept faithfully rather than "fixed", since it
402
+ is not a bug -- the source got this one right.
403
+ """
404
+ t = np.asarray(new_time2dc, dtype=float)
405
+ d = np.asarray(new_date2dc, dtype=float)
406
+ if t.shape != d.shape:
407
+ raise ValueError(f"new_time2dc and new_date2dc must match: {t.shape} vs {d.shape}")
408
+ n = t.size
409
+ out = np.empty(n, dtype=float)
410
+ rows, width = _num2str_int_column(t) # :258
411
+ for k in range(n): # :259-269
412
+ row = rows[k]
413
+ if t[k] < 100000:
414
+ if width == 5:
415
+ hh = _str2double(row[0:1])
416
+ mi = _str2double(row[1:3])
417
+ sc = _str2double(row[3:5])
418
+ elif width == 6:
419
+ hh = _str2double(row[1:2])
420
+ mi = _str2double(row[2:4])
421
+ sc = _str2double(row[4:6])
422
+ else:
423
+ raise ValueError(
424
+ f"NEWtime2dc column width {width} has no branch in the source (:261-265 "
425
+ "only handle 5 or 6) -- read the .m before extending this")
426
+ else:
427
+ hh = _str2double(row[0:2])
428
+ mi = _str2double(row[2:4])
429
+ sc = _str2double(row[4:6])
430
+ out[k] = _time2datenum(d[k]) + _time_of_day_fraction(hh, mi, sc)
431
+ return out
432
+
433
+
434
+ def expand_tau_per_particle(tau_blocks, block_starts, population_size, n):
435
+ """``:162-164``'s ``tau_all(j,:) = tau_std`` -- broadcast each block's fitted ``tau`` to
436
+ every particle in that block, needed only for :func:`write_mat_workspace`'s ``tau_all``.
437
+
438
+ The inner ``for j`` loop runs unconditionally (both the NaN and non-NaN branches reach it),
439
+ so a block whose fit failed still broadcasts its ``[NaN, NaN, NaN]`` row to every one of its
440
+ particles, exactly like a successful block broadcasts its real ``tau``.
441
+ """
442
+ tau_blocks = np.asarray(tau_blocks, dtype=float)
443
+ out = np.empty((n, 3), dtype=float)
444
+ for row, start in enumerate(block_starts):
445
+ end = min(int(start) + population_size, n)
446
+ out[start:end, :] = tau_blocks[row]
447
+ return out
448
+
449
+
450
+ def write_extra_thresholds_sidecar(filename, timehhmmss, threshold, threshold_ww, *,
451
+ threshold_ak=None):
452
+ """Opt-in: persist the two thresholds the source computes but never writes (``:159``,
453
+ ``:189``) alongside the ``.cdf`` -- as a plain JSON sidecar, **never** a netCDF file.
454
+
455
+ ``threshold`` (``min(tau(1:2))*2``) and ``threshold_ww`` (the fitted-curve selection) sit
456
+ next to ``threshold_ak`` (the one value ``:363`` writes) purely for a user who wants to
457
+ compare the three techniques; :func:`analyse` already returns all three unconditionally
458
+ (see the module docstring), so this function only decides where the extra two get
459
+ *persisted*, and the fidelity doctrine's "an enhancement writes a variable MATLAB never
460
+ wrote" line draws that boundary at the ``.cdf`` file specifically, not at "on disk at all".
461
+ """
462
+ times = np.asarray(timehhmmss, dtype=float)
463
+ thr = np.asarray(threshold, dtype=float)
464
+ ww = np.asarray(threshold_ww, dtype=float)
465
+ if not (times.shape == thr.shape == ww.shape):
466
+ raise ValueError("timehhmmss, threshold and threshold_ww must all match shape")
467
+ payload = {
468
+ "particle_time": times.tolist(),
469
+ "threshold": thr.tolist(),
470
+ "threshold_ww": ww.tolist(),
471
+ }
472
+ if threshold_ak is not None:
473
+ ak = np.asarray(threshold_ak, dtype=float)
474
+ if ak.shape != times.shape:
475
+ raise ValueError("threshold_ak must match timehhmmss's shape")
476
+ payload["threshold_ak"] = ak.tolist()
477
+ with open(filename, "w", encoding="utf-8") as f:
478
+ json.dump(payload, f, indent=2)
479
+ return filename
480
+
481
+
482
+ def write_mat_workspace(filename, *, timehhmmss, date, time_in_seconds, dmax, probe_name,
483
+ date_string, infile, n_blocks=5, beta0=_BETA0):
484
+ """``:331`` -- ``save([directory_2, probeName, '_IntArrAnalysis.', dateString, '_',
485
+ startTime, '_', endTime, '.mat'])``, with no variable list: MATLAB saves the function's
486
+ *entire* local workspace at that line. ``scipy.io`` is imported lazily -- opt-in, like the
487
+ plots, so nothing in this module needs it merely to be imported.
488
+
489
+ Writes the named result variables a user opening the ``.mat`` would actually want back,
490
+ under their own MATLAB names, with MATLAB's own shapes (row vectors stay ``(1, N)``, matrices
491
+ stay ``(n_blocks, n_bins)``). **Deliberately excluded**, and named here rather than silently
492
+ dropped:
493
+
494
+ * loop scratch that is only ever a *last-iteration* leftover, an artifact of MATLAB script
495
+ scoping rather than a real result -- ``i``, ``j``, ``k``, ``h``, ``arr``, ``indicies``,
496
+ ``dt``, ``hfit``, ``tau1``, ``tau2``, ``newDT``, ``minFit``, ``indexFit``, ``minOriginal``,
497
+ ``indexOriginal``, ``y`` (redundant with ``NEWtime2dc`` in any case);
498
+ * ``bimodalfit``, a function handle, not data ``scipy.io.savemat`` can round-trip;
499
+ * ``ncid``, ``file`` -- an open netCDF handle and an OS ``dir()`` struct, meaningless once
500
+ the run has finished;
501
+ * the function's own parameters (``campaign``, ``filedate``, ``startTime``, ...), which the
502
+ source's own hardcoded "Inputs" block (``:33-40``) overwrites before first use, so what a
503
+ caller passed is never actually what ends up in the workspace under those names.
504
+
505
+ Every OTHER named quantity the source's own workspace holds at ``:331`` is included:
506
+ ``hist2dc``, ``NEWtime2dc``, ``NEWdate2dc`` (the *contour* loop's versions, since ``:231-236``
507
+ overwrite the fit loop's own same-named arrays), ``threshhold``, ``threshhold_ww``,
508
+ ``threshhold_ak``, ``tau_all``, ``hist2dc_contour``, ``histsum``, ``x``, ``time``, ``bins``
509
+ and ``binsCenter`` (the *contour* loop's 70-point versions -- ``:220`` reassigns ``bins``
510
+ after the fit loop, so that is what is left in the workspace), ``width`` (the *fit* loop's
511
+ 35-point value -- computed once at ``:119``, before ``:220``'s reassignment, and never
512
+ touched again), ``num_particles``, ``numparticles``, ``timehhmmss``, ``date``, ``int_arr``,
513
+ ``intarr``, ``Dmax``, ``n`` (the *contour* loop's final counter, since ``:224`` resets it),
514
+ ``dateString``, ``probeName``, ``infile``.
515
+ """
516
+ import scipy.io
517
+
518
+ times = np.asarray(timehhmmss, dtype=float)
519
+ dates = np.asarray(date, dtype=float)
520
+ n = times.size
521
+
522
+ int_arr = inter_arrival(time_in_seconds) # :55-72, the port's own name
523
+ intarr = _intarr_pre_clip(time_in_seconds) # :91's own final value
524
+
525
+ size = population_size(times, n_blocks)
526
+ result = analyse(int_arr, times, n_blocks=n_blocks, beta0=beta0, collect_histograms=True)
527
+ hist2dc_contour, new_time2dc, new_date2dc = contour_data(int_arr, times, dates, size)
528
+
529
+ tau_all = expand_tau_per_particle(result["tau"], result["block_starts"], size, n)
530
+
531
+ row_sums = hist2dc_contour.sum(axis=1, keepdims=True)
532
+ with np.errstate(divide="ignore", invalid="ignore"):
533
+ histsum = np.repeat(row_sums, hist2dc_contour.shape[1], axis=1) # :241
534
+
535
+ x_axis = contour_time_axis(new_time2dc, new_date2dc) # :258-269
536
+ time_axis = overlay_time_axis(times, dates) # :243-250, B8 reproduced
537
+
538
+ bins_contour = CONTOUR_BINS # :220, final `bins`
539
+ bins_center_contour = bins_contour[:-1] + np.diff(bins_contour) / 2 # :229, final `binsCenter`
540
+
541
+ variables = {
542
+ "hist2dc": result["hist2dc"],
543
+ "NEWtime2dc": new_time2dc.reshape(1, -1), # :136, row vector
544
+ "NEWdate2dc": new_date2dc.reshape(1, -1),
545
+ "threshhold": result["threshold"],
546
+ "threshhold_ww": result["threshold_ww"],
547
+ "threshhold_ak": result["threshold_ak"],
548
+ "tau_all": tau_all,
549
+ "hist2dc_contour": hist2dc_contour,
550
+ "histsum": histsum,
551
+ "x": x_axis.reshape(-1, 1), # :262 etc., column vector
552
+ "time": time_axis.reshape(1, -1), # :246 etc., `time(k)=...` row
553
+ "bins": bins_contour.reshape(1, -1),
554
+ "binsCenter": bins_center_contour.reshape(1, -1),
555
+ "width": np.asarray([[_WIDTH]], dtype=float),
556
+ "num_particles": np.asarray([[size]], dtype=float),
557
+ "numparticles": np.asarray([[size]], dtype=float),
558
+ "timehhmmss": times.reshape(-1, 1),
559
+ "date": dates.reshape(-1, 1),
560
+ "int_arr": int_arr.reshape(-1, 1),
561
+ "intarr": intarr.reshape(-1, 1),
562
+ "Dmax": np.asarray(dmax, dtype=float).reshape(-1, 1),
563
+ "n": np.asarray([[hist2dc_contour.shape[0] + 1]], dtype=float), # :224,234, post-loop n
564
+ "dateString": date_string,
565
+ "probeName": probe_name,
566
+ "infile": infile,
567
+ }
568
+ scipy.io.savemat(filename, variables)
569
+ return filename