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
+ """Put two probes' sizeDist-layout products on a common size grid and time axis.
3
+
4
+ The helpers here compare two optical array probes (for example a CIP and a 2D-S)
5
+ with statistics that survive mostly-empty 1 Hz data:
6
+
7
+ - :func:`load_sd` reads one or more sizeDist outputs, converting ``conc_minR``
8
+ to number concentration per bin the way ``combine_sizedist.m`` does;
9
+ - :func:`rebin_weights` and :func:`rebin` apportion each native bin onto a
10
+ common grid by the fraction of its width inside each common bin;
11
+ - :func:`align` keeps the seconds both products carry;
12
+ - :func:`scatter_stats` reports Spearman and Pearson-of-log1p on every finite
13
+ pair and an RMA slope on a count-gated subset, never a raw Pearson;
14
+ - :func:`coincidence_vs_lag` scans the conditional detection probability over
15
+ a range of time lags, separating a clock offset from Poisson thinning.
16
+
17
+ Nothing here changes a processing output; it reads products and returns plain
18
+ dicts and arrays. scipy is imported lazily, inside the function
19
+ that needs it.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import math
25
+
26
+ import netCDF4
27
+ import numpy as np
28
+
29
+ #: An example common grid [um]: 55-105 um, then 100-um bins with edges 105, 205, ..., 1005 um.
30
+ #: Every edge is an edge of a 10-um bin ladder, so a probe processed onto that ladder rebins as
31
+ #: a pure sum. Callers may pass their own edges.
32
+ COMMON_EDGES_UM = np.array([55.0] + [105.0 + 100.0 * k for k in range(10)])
33
+
34
+ #: Minimum counts per second (a, b) for the dense 1 Hz subset the RMA slope is fitted on.
35
+ DEFAULT_COUNT_GATE = (20.0, 5.0)
36
+ #: Minimum summed counts per averaging window (a, b) for the window-mean RMA subset.
37
+ DEFAULT_COUNT_GATE_WINDOW = (100.0, 20.0)
38
+ #: Averaging window [s] and the minimum number of its seconds finite on both sides.
39
+ DEFAULT_WINDOW_S = 300
40
+ DEFAULT_MIN_COVER = 270
41
+ #: The +- lag magnitudes [s] added to the dense 1 s scan of :func:`build_lag_list`.
42
+ _LAG_COARSE_STEPS = (45, 60, 90, 120, 180, 300, 450, 600)
43
+
44
+
45
+ # --------------------------------------------------------------------------- readers
46
+ def _by_dims(var, want: tuple[str, str]) -> np.ndarray:
47
+ """Return ``var`` as a ``(time, bin)`` float array whatever its on-disk order."""
48
+ arr = np.asarray(var[:], dtype=np.float64)
49
+ dims = var.dimensions
50
+ if dims == want[::-1]:
51
+ arr = arr.T
52
+ elif dims != want:
53
+ raise ValueError(f"{var.name}: dims {dims}, expected {want} in some order")
54
+ return arr
55
+
56
+
57
+
58
+ def zero_empty_rows(x: np.ndarray, n_tot: np.ndarray) -> np.ndarray:
59
+ """A NaN bin in a second whose total ``n_tot`` is finite is an empty bin, so it is 0.
60
+
61
+ A product can write every bin of a zero-particle second as NaN. Reading those
62
+ as missing would drop every empty second and bias a ratio toward the seconds
63
+ one probe happened to fill, so they are zero. A second whose total is itself
64
+ NaN (a gap) stays missing.
65
+ """
66
+ out = x.copy()
67
+ valid = np.isfinite(n_tot)[:, None] & np.isnan(out)
68
+ out[valid] = 0.0
69
+ return out
70
+
71
+
72
+ _zero_empty_rows = zero_empty_rows
73
+
74
+
75
+ def load_sd(paths) -> dict:
76
+ """One or more sizeDist outputs, concatenated in time order.
77
+
78
+ ``conc_minR`` [cm-4] -> cm-3 per bin as ``combine_sizedist.m:47-50`` does.
79
+ A repeated second keeps its first occurrence (``combine_sizedist.m:84-91``
80
+ drops the second of each adjacent duplicate).
81
+ """
82
+ uts, nds, cts = [], [], []
83
+ bmin = bmax = None
84
+ for p in paths:
85
+ with netCDF4.Dataset(p) as d:
86
+ d.set_auto_mask(False)
87
+ hhmmss = np.asarray(d["time"][:], dtype=np.int64)
88
+ tdim = d["time"].dimensions[0]
89
+ bdim = d["bin_min"].dimensions[0]
90
+ dd = np.asarray(d["bin_dD"][:], dtype=np.float64)
91
+ n_tot = np.asarray(d["n"][:], dtype=np.float64)
92
+ conc = _by_dims(d["conc_minR"], (tdim, bdim))
93
+ nd = _zero_empty_rows(conc / 10.0 * dd[None, :], n_tot)
94
+ ct = _zero_empty_rows(_by_dims(d["count"], (tdim, bdim)), n_tot)
95
+ bmin = np.asarray(d["bin_min"][:], dtype=np.float64) * 1000.0
96
+ bmax = np.asarray(d["bin_max"][:], dtype=np.float64) * 1000.0
97
+ ut = (hhmmss // 10000) * 3600 + ((hhmmss // 100) % 100) * 60 + hhmmss % 100
98
+ uts.append(ut)
99
+ nds.append(nd)
100
+ cts.append(ct)
101
+ ut = np.concatenate(uts)
102
+ nd = np.concatenate(nds)
103
+ ct = np.concatenate(cts)
104
+ order = np.argsort(ut, kind="stable")
105
+ ut, nd, ct = ut[order], nd[order], ct[order]
106
+ keep = np.ones(len(ut), dtype=bool)
107
+ keep[1:] = np.diff(ut) != 0
108
+ return {"ut": ut[keep], "bmin": bmin, "bmax": bmax, "nd": nd[keep], "counts": ct[keep]}
109
+
110
+
111
+ # --------------------------------------------------------------------------- common grid
112
+ def rebin_weights(bmin, bmax, edges, shift_um: float = 0.0) -> np.ndarray:
113
+ """``(n_fine, n_coarse)`` fraction of each fine bin's width inside each coarse bin."""
114
+ lo = np.asarray(bmin, dtype=np.float64) + shift_um
115
+ hi = np.asarray(bmax, dtype=np.float64) + shift_um
116
+ e0, e1 = edges[:-1], edges[1:]
117
+ overlap = np.clip(np.minimum(hi[:, None], e1[None, :]) - np.maximum(lo[:, None], e0[None, :]),
118
+ 0.0, None)
119
+ width = (hi - lo)[:, None]
120
+ return overlap / width
121
+
122
+
123
+ def rebin(x: np.ndarray, w: np.ndarray) -> np.ndarray:
124
+ """``(time, fine) @ (fine, coarse)`` with NaN kept where every contributor is NaN."""
125
+ finite = np.isfinite(x)
126
+ out = np.where(finite, x, 0.0) @ w
127
+ any_finite = (finite.astype(np.float64) @ (w > 0)) > 0
128
+ return np.where(any_finite, out, np.nan)
129
+
130
+
131
+ def align(ut_a, xa, ut_b, xb):
132
+ """Rows of ``xa`` and ``xb`` on the seconds both carry."""
133
+ common, ia, ib = np.intersect1d(ut_a, ut_b, return_indices=True)
134
+ return common, xa[ia], xb[ib]
135
+
136
+
137
+ def poisson_ratio_ci(r, c_num, c_den, z=1.96):
138
+ """95 % (default ``z``) log-normal interval on a ratio of two Poisson count totals."""
139
+ if not (c_num > 0 and c_den > 0 and math.isfinite(r) and r > 0):
140
+ return (None, None)
141
+ s = math.sqrt(1.0 / c_num + 1.0 / c_den)
142
+ return (r * math.exp(-z * s), r * math.exp(z * s))
143
+
144
+
145
+ # --------------------------------------------------------------------------- small stats helpers
146
+ def row_total(x: np.ndarray, mask: np.ndarray | None = None) -> np.ndarray:
147
+ """Per-second sum across common bins; NaN only where every (unmasked) bin is NaN (a gap).
148
+ ``mask`` (bool, one per bin column) selects the bin columns summed; ``mask=None`` sums
149
+ every bin."""
150
+ if mask is not None:
151
+ x = x[:, mask]
152
+ return np.where(np.isfinite(x).any(axis=1), np.nansum(x, axis=1), np.nan)
153
+
154
+
155
+
156
+ _row_total = row_total
157
+
158
+
159
+ def _spearman(x, y):
160
+ """Spearman rho, or ``None`` when undefined. scipy is imported lazily."""
161
+ from scipy.stats import spearmanr
162
+ r = spearmanr(x, y)[0]
163
+ r = float(r)
164
+ return r if math.isfinite(r) else None
165
+
166
+
167
+ def _wilson_ci(k: int, n: int, z: float = 1.959964) -> tuple:
168
+ if n == 0:
169
+ return (None, None)
170
+ phat = k / n
171
+ denom = 1.0 + z * z / n
172
+ centre = phat + z * z / (2 * n)
173
+ half = z * math.sqrt(phat * (1 - phat) / n + z * z / (4 * n * n))
174
+ return ((centre - half) / denom, (centre + half) / denom)
175
+
176
+
177
+
178
+
179
+ # --------------------------------------------------------------------------- coincidence vs lag
180
+ def build_lag_list(window: int) -> list[int]:
181
+ """Every 1 s in [-30, 30], then the coarse +-magnitudes up to ``window``."""
182
+ lags = set(range(-min(30, window), min(30, window) + 1))
183
+ for m in _LAG_COARSE_STEPS:
184
+ if m <= window:
185
+ lags.add(m)
186
+ lags.add(-m)
187
+ return sorted(lags)
188
+
189
+
190
+ def coincidence_vs_lag(ut_a, c_a, ut_b, c_b, gate_a, gate_b, lags) -> dict:
191
+ """P(other probe sees anything at t+L | this probe is dense at t), both directions, over a
192
+ lag scan -- the discriminator between a clock offset (peak away from 0) and Poisson
193
+ thinning of a shared cloud (peak at |L|<=1 s, symmetric decay back to the unconditional
194
+ rate). Strength is reported on log1p Pearson and Spearman, never raw Pearson: on
195
+ mostly-zero counts raw Pearson reports the leverage of a few dense seconds.
196
+ """
197
+ ut_a = np.asarray(ut_a)
198
+ c_a = np.asarray(c_a, dtype=np.float64)
199
+ ut_b = np.asarray(ut_b)
200
+ c_b = np.asarray(c_b, dtype=np.float64)
201
+
202
+ common0, a0, b0 = align(ut_a, c_a, ut_b, c_b)
203
+ ok0 = np.isfinite(a0) & np.isfinite(b0)
204
+ uncond_a = float(np.mean(a0[ok0] > 0)) if ok0.any() else None
205
+ uncond_b = float(np.mean(b0[ok0] > 0)) if ok0.any() else None
206
+
207
+ out_lags: list[int] = []
208
+ p_b_given_a: list = []
209
+ p_a_given_b: list = []
210
+ wilson_b_given_a: list = []
211
+ wilson_a_given_b: list = []
212
+ n_b_given_a: list = []
213
+ n_a_given_b: list = []
214
+ pearson_log1p: list = []
215
+ spearman: list = []
216
+
217
+ for lag in lags:
218
+ _, at, bshift = align(ut_a, c_a, ut_b - lag, c_b) # b(t+L) beside a(t)
219
+ ok = np.isfinite(at) & np.isfinite(bshift)
220
+ dense = ok & (at >= gate_a)
221
+ nb = int(dense.sum())
222
+ kb = int((bshift[dense] > 0).sum()) if nb else 0
223
+ p_b_given_a.append(kb / nb if nb else None)
224
+ wilson_b_given_a.append(list(_wilson_ci(kb, nb)))
225
+ n_b_given_a.append(nb)
226
+
227
+ _, bt, ashift = align(ut_b, c_b, ut_a - lag, c_a) # a(t+L) beside b(t)
228
+ ok2 = np.isfinite(bt) & np.isfinite(ashift)
229
+ dense2 = ok2 & (bt >= gate_b)
230
+ na = int(dense2.sum())
231
+ ka = int((ashift[dense2] > 0).sum()) if na else 0
232
+ p_a_given_b.append(ka / na if na else None)
233
+ wilson_a_given_b.append(list(_wilson_ci(ka, na)))
234
+ n_a_given_b.append(na)
235
+
236
+ if ok.sum() >= 2 and np.std(at[ok]) > 0 and np.std(bshift[ok]) > 0:
237
+ l1a, l1b = np.log1p(at[ok]), np.log1p(bshift[ok])
238
+ pearson_log1p.append(float(np.corrcoef(l1a, l1b)[0, 1]))
239
+ spearman.append(_spearman(at[ok], bshift[ok]))
240
+ else:
241
+ pearson_log1p.append(None)
242
+ spearman.append(None)
243
+ out_lags.append(int(lag))
244
+
245
+ peak_idx = None
246
+ valid_p = [(i, v) for i, v in enumerate(p_b_given_a) if v is not None]
247
+ if valid_p:
248
+ peak_idx = max(valid_p, key=lambda iv: (iv[1], -abs(out_lags[iv[0]])))[0]
249
+ peak_lag = out_lags[peak_idx] if peak_idx is not None else None
250
+ peak_value = p_b_given_a[peak_idx] if peak_idx is not None else None
251
+
252
+ half_width = None
253
+ if peak_idx is not None and uncond_b is not None and peak_value is not None:
254
+ half_level = uncond_b + 0.5 * (peak_value - uncond_b)
255
+ assert peak_lag is not None # set from out_lags whenever peak_idx is
256
+ widths = []
257
+ for step in (1, -1):
258
+ i = peak_idx
259
+ while 0 <= i + step < len(out_lags):
260
+ i += step
261
+ v = p_b_given_a[i]
262
+ if v is not None and v <= half_level:
263
+ widths.append(abs(out_lags[i] - peak_lag))
264
+ break
265
+ if widths:
266
+ half_width = float(np.mean(widths))
267
+
268
+ return {
269
+ "lags_s": out_lags, "gate_a": gate_a, "gate_b": gate_b,
270
+ "p_b_given_a": p_b_given_a, "wilson_b_given_a": wilson_b_given_a,
271
+ "n_b_given_a": n_b_given_a,
272
+ "p_a_given_b": p_a_given_b, "wilson_a_given_b": wilson_a_given_b,
273
+ "n_a_given_b": n_a_given_b,
274
+ "pearson_log1p": pearson_log1p, "spearman": spearman,
275
+ "unconditional_a": uncond_a, "unconditional_b": uncond_b,
276
+ "peak_lag_s": peak_lag, "peak_value": peak_value, "half_width_s": half_width,
277
+ "n_overlap_lag0": int(len(common0)),
278
+ }
279
+
280
+
281
+
282
+ # --------------------------------------------------------------------------- window means
283
+ NO_DATA_REASON = ("no finite value in any kept second of this window for this bin "
284
+ "(the chain's size ladder does not cover it, or every second is a gap there)")
285
+
286
+
287
+ def _window_bins(ut, nd, counts, window, min_cover, both_finite_mask) -> dict:
288
+ """One product's fixed-UTC ``window``-s means.
289
+
290
+ Called once per side of a pair with the *same* ``both_finite_mask`` -- computed by the caller
291
+ from both chains at once as ``isfinite(tot_a) & isfinite(tot_b)`` -- so the two calls that make
292
+ up one pair bin identical seconds on identical edges; this function has no way to pick its own.
293
+ Zero-particle seconds are already zeros (:func:`zero_empty_rows`); a bin is kept
294
+ when >= ``min_cover`` of its ``window`` seconds are finite on both sides.
295
+ """
296
+ ut = np.asarray(ut)
297
+ if len(ut) == 0:
298
+ return {"window_s": window, "min_cover": min_cover, "bins": []}
299
+ edge0 = int(np.floor(ut.min() / window))
300
+ edge1 = int(np.floor(ut.max() / window))
301
+ out = []
302
+ for b in range(edge0, edge1 + 1):
303
+ t0 = b * window
304
+ in_bin = (ut >= t0) & (ut < t0 + window)
305
+ valid = in_bin & both_finite_mask
306
+ n_valid = int(valid.sum())
307
+ row = {"t0": int(t0), "n_valid": n_valid, "n_window": int(in_bin.sum()),
308
+ "kept": n_valid >= max(min_cover, 1)}
309
+ if row["kept"]:
310
+ # A bin column with no finite value in any kept second has no mean: written as
311
+ # JSON null, with the bins named and the reason stated, never a fabricated 0 and
312
+ # never a NaN (which the allow_nan=False JSON write refuses). The usual cause is a
313
+ # chain whose own size ladder does not reach that common bin at all.
314
+ sub = nd[valid, :]
315
+ n_fin = np.isfinite(sub).sum(axis=0)
316
+ sums = np.nansum(sub, axis=0)
317
+ row["mean_N"] = [float(sums[j] / n_fin[j]) if n_fin[j] else None
318
+ for j in range(sub.shape[1])]
319
+ empty = [int(j) for j in np.flatnonzero(n_fin == 0)]
320
+ if empty:
321
+ row["mean_N_no_data_bins"] = empty
322
+ row["mean_N_no_data_reason"] = NO_DATA_REASON
323
+ row["sum_C"] = [float(v) for v in np.nansum(counts[valid, :], axis=0)]
324
+ tot = np.nansum(nd[valid, :], axis=1)
325
+ row["zero_frac"] = float(np.mean(tot <= 0.0))
326
+ out.append(row)
327
+ return {"window_s": window, "min_cover": min_cover, "bins": out}
328
+
329
+
330
+ def _combine_windows(fm_a: dict, fm_b: dict) -> dict:
331
+ """Zip two single-side :func:`_window_bins` results (identical edges by construction)."""
332
+ bins = []
333
+ for ba, bb in zip(fm_a["bins"], fm_b["bins"], strict=True):
334
+ row = {"t0": ba["t0"], "n_valid": ba["n_valid"], "n_window": ba["n_window"],
335
+ "kept": ba["kept"]}
336
+ if row["kept"]:
337
+ row["mean_N_a"], row["mean_N_b"] = ba["mean_N"], bb["mean_N"]
338
+ row["sum_C_a"], row["sum_C_b"] = ba["sum_C"], bb["sum_C"]
339
+ row["zero_frac_a"], row["zero_frac_b"] = ba["zero_frac"], bb["zero_frac"]
340
+ for side, src in (("a", ba), ("b", bb)):
341
+ if "mean_N_no_data_bins" in src:
342
+ row[f"mean_N_{side}_no_data_bins"] = src["mean_N_no_data_bins"]
343
+ row[f"mean_N_{side}_no_data_reason"] = src["mean_N_no_data_reason"]
344
+ bins.append(row)
345
+ return {"window_s": fm_a["window_s"], "min_cover": fm_a["min_cover"], "bins": bins}
346
+
347
+
348
+
349
+ # --------------------------------------------------------------------------- scatter statistics
350
+ def scatter_stats(x, y, gate: tuple, gate_x=None, gate_y=None) -> dict:
351
+ """Spearman + Pearson-of-log on every finite pair, RMA slope on the count-gated subset only
352
+ (never raw Pearson).
353
+
354
+ ``gate_x``/``gate_y`` default to ``x``/``y`` themselves (the 1 Hz layer's own reporting gate
355
+ is on the counts it also correlates). The window-mean layer correlates *mean N* but gates on
356
+ *summed counts* -- two different arrays over the same kept bins -- so its caller passes the
357
+ counts here explicitly; reusing ``x``/``y`` for both would gate a concentration (order
358
+ 0.01-tens of cm-3) against a counts threshold that it can almost never cross.
359
+
360
+ RMA (reduced major axis / standardised major axis), not OLS: both axes carry Poisson error of
361
+ comparable size here, and OLS of y on x is attenuated toward zero by x's own error.
362
+ ``slope = sign(r) * std(log10 y) / std(log10 x)``.
363
+ """
364
+ x = np.asarray(x, dtype=np.float64)
365
+ y = np.asarray(y, dtype=np.float64)
366
+ gvx = x if gate_x is None else np.asarray(gate_x, dtype=np.float64)
367
+ gvy = y if gate_y is None else np.asarray(gate_y, dtype=np.float64)
368
+ ok = np.isfinite(x) & np.isfinite(y)
369
+ n = int(ok.sum())
370
+ out: dict = {"n": n, "gate": [float(gate[0]), float(gate[1])],
371
+ "spearman": None, "pearson_log1p": None, "ratio_of_sums": None,
372
+ "n_gated": 0, "pearson_log_gated": None,
373
+ "rma_slope_log10": None, "rma_intercept_log10": None,
374
+ "median_ratio_gated": None}
375
+ if n == 0:
376
+ return out
377
+ xf, yf = x[ok], y[ok]
378
+ out["frac_both_zero"] = float(np.mean((xf == 0) & (yf == 0)))
379
+ out["frac_x_zero"] = float(np.mean(xf == 0))
380
+ out["frac_y_zero"] = float(np.mean(yf == 0))
381
+ out["sum_x"] = float(np.sum(xf))
382
+ out["sum_y"] = float(np.sum(yf))
383
+ if out["sum_x"] > 0:
384
+ out["ratio_of_sums"] = float(out["sum_y"] / out["sum_x"])
385
+ if n >= 2 and np.std(xf) > 0 and np.std(yf) > 0:
386
+ out["spearman"] = _spearman(xf, yf)
387
+ lx, ly = np.log1p(xf), np.log1p(yf)
388
+ if n >= 2 and np.std(lx) > 0 and np.std(ly) > 0:
389
+ out["pearson_log1p"] = float(np.corrcoef(lx, ly)[0, 1])
390
+
391
+ gx, gy = gate
392
+ ok_gate = ok & np.isfinite(gvx) & np.isfinite(gvy)
393
+ gated = ok_gate.copy()
394
+ gated[ok_gate] = (gvx[ok_gate] >= gx) & (gvy[ok_gate] >= gy)
395
+ xg_all, yg_all = x[gated], y[gated]
396
+ pos = (xg_all > 0) & (yg_all > 0)
397
+ xg, yg = np.log10(xg_all[pos]), np.log10(yg_all[pos])
398
+ ng = int(len(xg))
399
+ out["n_gated"] = int(gated.sum())
400
+ out["n_gated_positive"] = ng
401
+ if ng >= 2 and np.std(xg) > 0 and np.std(yg) > 0:
402
+ r = float(np.corrcoef(xg, yg)[0, 1])
403
+ sx, sy = float(np.std(xg, ddof=1)), float(np.std(yg, ddof=1))
404
+ slope = math.copysign(sy / sx, r) if r != 0 else sy / sx
405
+ out["pearson_log_gated"] = r
406
+ out["rma_slope_log10"] = float(slope)
407
+ out["rma_intercept_log10"] = float(np.mean(yg) - slope * np.mean(xg))
408
+ out["median_ratio_gated"] = float(np.median(yg_all[pos] / xg_all[pos]))
409
+ return out
410
+
411
+
412
+ # --------------------------------------------------------------------------- per-bin totals
413
+ def bin_stats(nd_a, ct_a, nd_b, ct_b, sel) -> list[dict]:
414
+ """Per-common-bin totals and the ratio ``R_b_over_a = sum N_b / sum N_a`` over the selected
415
+ seconds where both products are finite in that bin, with a Poisson 95 % interval."""
416
+ rows = []
417
+ for j in range(nd_a.shape[1]):
418
+ ok = sel & np.isfinite(nd_a[:, j]) & np.isfinite(nd_b[:, j])
419
+ s2, sc = float(np.sum(nd_a[ok, j])), float(np.sum(nd_b[ok, j]))
420
+ c2, cc = float(np.nansum(ct_a[ok, j])), float(np.nansum(ct_b[ok, j]))
421
+ r = sc / s2 if s2 > 0 else float("nan")
422
+ lo, hi = poisson_ratio_ci(r, cc, c2)
423
+ rows.append({"n_seconds": int(ok.sum()), "counts_a": c2, "counts_b": cc,
424
+ "sumN_a_cm3s": s2, "sumN_b_cm3s": sc,
425
+ "R_b_over_a": r if math.isfinite(r) else None,
426
+ "R_ci95": [lo, hi]})
427
+ return rows
428
+
429
+
430
+ def window_means(ut, nd_a, ct_a, nd_b, ct_b, *, window_s: int = DEFAULT_WINDOW_S,
431
+ min_cover: int = DEFAULT_MIN_COVER, both_finite) -> dict:
432
+ """Fixed-UTC ``window_s``-second means of both products, binned on identical seconds.
433
+
434
+ ``both_finite`` is the per-second mask of seconds finite on both sides; a window is kept when
435
+ at least ``min_cover`` of its seconds are in it. Each kept row carries ``mean_N_a``/``mean_N_b``
436
+ (per common bin), ``sum_C_a``/``sum_C_b`` (summed counts) and ``zero_frac_a``/``zero_frac_b``.
437
+ """
438
+ fm_a = _window_bins(ut, nd_a, ct_a, window_s, min_cover, both_finite)
439
+ fm_b = _window_bins(ut, nd_b, ct_b, window_s, min_cover, both_finite)
440
+ return _combine_windows(fm_a, fm_b)
441
+
442
+
443
+ # --------------------------------------------------------------------------- size distributions
444
+ def size_distributions(chain: dict, edges=COMMON_EDGES_UM) -> dict:
445
+ """Period-integrated dN/dD [cm-3 um-1] on the product's own native grid and on ``edges``: the
446
+ sum over seconds of N per bin, divided by the count of finite seconds and by the bin width."""
447
+ nd = chain["nd"]
448
+ finite = np.isfinite(nd)
449
+ n_seconds = int(finite.any(axis=1).sum())
450
+ bmin = np.asarray(chain["bmin"], dtype=np.float64)
451
+ bmax = np.asarray(chain["bmax"], dtype=np.float64)
452
+ width = bmax - bmin
453
+ counted = finite.sum(axis=0)
454
+ summed = np.nansum(nd, axis=0)
455
+ with np.errstate(invalid="ignore", divide="ignore"):
456
+ dndd_native = np.where(counted > 0, summed / np.maximum(counted, 1) / width, np.nan)
457
+ bin_mid = (bmin + bmax) / 2.0
458
+
459
+ w = rebin_weights(bmin, bmax, edges)
460
+ nd_c = rebin(nd, w)
461
+ finite_c = np.isfinite(nd_c)
462
+ width_c = np.diff(edges)
463
+ counted_c = finite_c.sum(axis=0)
464
+ summed_c = np.nansum(nd_c, axis=0)
465
+ with np.errstate(invalid="ignore", divide="ignore"):
466
+ dndd_common = np.where(counted_c > 0, summed_c / np.maximum(counted_c, 1) / width_c,
467
+ np.nan)
468
+
469
+ return {
470
+ "n_seconds": n_seconds,
471
+ "native": {"bin_min_um": [float(v) for v in bmin], "bin_max_um": [float(v) for v in bmax],
472
+ "bin_mid_um": [float(v) for v in bin_mid],
473
+ "dNdD_cm3_um": [float(v) if np.isfinite(v) else None for v in dndd_native]},
474
+ "common": {"edges_um": [float(e) for e in edges],
475
+ "dNdD_cm3_um": [float(v) if np.isfinite(v) else None for v in dndd_common]},
476
+ }
477
+
478
+
479
+ # --------------------------------------------------------------------------- exclusions
480
+ def _exclusion_mask(edges, exclude_from_totals) -> np.ndarray:
481
+ """``True`` for every common bin of ``edges`` except those whose lower edge matches the lower
482
+ edge of an ``(lo_um, hi_um)`` entry of ``exclude_from_totals`` (within 0.5 um)."""
483
+ edges = np.asarray(edges, dtype=np.float64)
484
+ mask = np.ones(max(len(edges) - 1, 0), dtype=bool)
485
+ for lo, _hi in exclude_from_totals or ():
486
+ for j in range(len(edges) - 1):
487
+ if abs(float(edges[j]) - float(lo)) <= 0.5:
488
+ mask[j] = False
489
+ break
490
+ return mask
491
+
492
+
493
+ def _comparable_sum(values, mask) -> float:
494
+ """Sum of ``values`` where ``mask`` is truthy, leaving out ``None`` bins; NaN when no included
495
+ bin has data. ``mask=None`` sums everything."""
496
+ if not values:
497
+ return 0.0
498
+ if mask is None:
499
+ mask = [True] * len(values)
500
+ have = [v for v, m in zip(values, mask, strict=True) if m and v is not None]
501
+ return float(sum(have)) if have else float("nan")
502
+
503
+
504
+ # --------------------------------------------------------------------------- orchestration
505
+ def compare_pair(a: dict, b: dict, *, edges=COMMON_EDGES_UM, edge_shift_um: float = 12.5,
506
+ exclude_from_totals=None, window_s: int = DEFAULT_WINDOW_S,
507
+ min_cover: int = DEFAULT_MIN_COVER, count_gate: tuple = DEFAULT_COUNT_GATE,
508
+ count_gate_window: tuple = DEFAULT_COUNT_GATE_WINDOW, lags=None,
509
+ gate_a: float = 20.0, gate_b: float = 5.0) -> dict:
510
+ """Compare two products ``a`` and ``b`` (each a :func:`load_sd` dict) on the ``edges`` grid.
511
+
512
+ Returns the per-bin ratios ``N_b / N_a`` with a Poisson interval and an edge-shift band
513
+ (``b`` rebinned with its edges moved by -/+ ``edge_shift_um``), ``window_s`` means, scatter
514
+ statistics at 1 Hz and on the window means (count-gated, never raw Pearson), the
515
+ coincidence-versus-lag curve and both size distributions. ``exclude_from_totals`` is a list of
516
+ ``(lo_um, hi_um)`` common bins left out of every aggregate; each still appears in ``bins``,
517
+ with ``comparable=False``. ``lags=None`` means :func:`build_lag_list` ``(600)``.
518
+ """
519
+ lags = build_lag_list(600) if lags is None else lags
520
+ wa = rebin_weights(a["bmin"], a["bmax"], edges)
521
+ wb = rebin_weights(b["bmin"], b["bmax"], edges)
522
+ nd_a_full, ct_a_full = rebin(a["nd"], wa), rebin(a["counts"], wa)
523
+ nd_b_full, ct_b_full = rebin(b["nd"], wb), rebin(b["counts"], wb)
524
+
525
+ common_ut, nd_a, nd_b = align(a["ut"], nd_a_full, b["ut"], nd_b_full)
526
+ _, ct_a, ct_b = align(a["ut"], ct_a_full, b["ut"], ct_b_full)
527
+ keep = np.ones(len(common_ut), dtype=bool)
528
+
529
+ mask = _exclusion_mask(edges, exclude_from_totals)
530
+ tot_a, tot_b = row_total(nd_a, mask), row_total(nd_b, mask)
531
+ ctot_a, ctot_b = row_total(ct_a, mask), row_total(ct_b, mask)
532
+ both_finite = np.isfinite(tot_a) & np.isfinite(tot_b) & keep
533
+
534
+ rows = bin_stats(nd_a, ct_a, nd_b, ct_b, keep)
535
+ sens: dict[str, list] = {}
536
+ for sh in (-edge_shift_um, edge_shift_um):
537
+ wb_s = rebin_weights(b["bmin"], b["bmax"], edges, shift_um=sh)
538
+ _, _, nd_b_s = align(a["ut"], nd_a_full, b["ut"], rebin(b["nd"], wb_s))
539
+ _, _, ct_b_s = align(a["ut"], ct_a_full, b["ut"], rebin(b["counts"], wb_s))
540
+ sens[f"{sh:+g}"] = [r["R_b_over_a"] for r in bin_stats(nd_a, ct_a, nd_b_s, ct_b_s, keep)]
541
+ for k, r in enumerate(rows):
542
+ r["bin_um"] = [float(edges[k]), float(edges[k + 1])]
543
+ r["R_edge_shift"] = {s: v[k] for s, v in sens.items()}
544
+ r["comparable"] = bool(mask[k])
545
+
546
+ win = window_means(common_ut, nd_a, ct_a, nd_b, ct_b, window_s=window_s,
547
+ min_cover=min_cover, both_finite=both_finite)
548
+ kept = [w for w in win["bins"] if w.get("kept")]
549
+ sc_w = scatter_stats(np.array([_comparable_sum(w["mean_N_a"], mask) for w in kept]),
550
+ np.array([_comparable_sum(w["mean_N_b"], mask) for w in kept]),
551
+ gate=count_gate_window,
552
+ gate_x=np.array([_comparable_sum(w["sum_C_a"], mask) for w in kept]),
553
+ gate_y=np.array([_comparable_sum(w["sum_C_b"], mask) for w in kept]))
554
+ sc1 = scatter_stats(np.where(keep, ctot_a, np.nan), np.where(keep, ctot_b, np.nan),
555
+ gate=count_gate)
556
+ coinc = coincidence_vs_lag(a["ut"], row_total(ct_a_full), b["ut"], row_total(ct_b_full),
557
+ gate_a, gate_b, lags)
558
+ return {
559
+ "overlap_seconds": int(len(common_ut)), "both_finite_seconds": int(both_finite.sum()),
560
+ "bins": rows, "windows": win, "scatter_1hz": sc1, "scatter_window": sc_w,
561
+ "coincidence": coinc,
562
+ "size_distributions": {"a": size_distributions(a, edges),
563
+ "b": size_distributions(b, edges)},
564
+ "count_gate": list(count_gate), "count_gate_window": list(count_gate_window),
565
+ "edges_um": [float(e) for e in edges],
566
+ "excluded_from_totals_um": [[float(lo), float(hi)]
567
+ for lo, hi in (exclude_from_totals or ())],
568
+ }
569
+