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,149 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Reproduction report: compare a product against an archived product, cell by cell.
3
+
4
+ Read-only. Opens both files for reading, writes nothing to either, and lists every
5
+ differing cell (variable, index, both values), never a summary alone.
6
+ Where a ``.call`` sidecar sits beside a file, its engine and stamp are reported.
7
+
8
+ ``compare.py`` joins per-particle files on particle identity; a size-distribution
9
+ product has no particle axis, so this report compares shared variables cell by cell
10
+ on their stored shape. Two NaNs in the same cell count as equal.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import netCDF4
19
+ import numpy as np
20
+
21
+ from arrayprobe import provenance
22
+
23
+
24
+ def _call_stamp(path: Path) -> dict | None:
25
+ side = Path(str(path) + ".call")
26
+ if not side.exists():
27
+ side = path.with_suffix(".call")
28
+ if not side.exists():
29
+ return None
30
+ text = side.read_text(encoding="utf-8", errors="replace").strip()
31
+ # The engine is what the stamp records, or None: a stamp naming no engine is not v3.1.4.
32
+ return {"path": str(side), "engine": provenance.parse(text).engine, "stamp": text}
33
+
34
+
35
+ def _read(ds, name):
36
+ v = ds.variables[name]
37
+ v.set_auto_maskandscale(False)
38
+ return np.asarray(v[...])
39
+
40
+
41
+ def _scalar(x):
42
+ x = x.item() if hasattr(x, "item") else x
43
+ if isinstance(x, bytes):
44
+ return x.decode("latin-1")
45
+ if isinstance(x, float) and np.isnan(x):
46
+ return "NaN"
47
+ return x
48
+
49
+
50
+ def build_report(product, archived) -> dict:
51
+ """Compare every variable the two files share; return the report as a dict."""
52
+ product, archived = Path(product), Path(archived)
53
+ out: dict[str, Any] = {"product": str(product), "archived": str(archived),
54
+ "call": {"product": _call_stamp(product), "archived": _call_stamp(archived)},
55
+ "variables": [], "only_in_product": [], "only_in_archived": [],
56
+ "differing_cells": []}
57
+ with netCDF4.Dataset(str(product)) as a, netCDF4.Dataset(str(archived)) as b:
58
+ na, nb = set(a.variables), set(b.variables)
59
+ out["only_in_product"] = sorted(na - nb)
60
+ out["only_in_archived"] = sorted(nb - na)
61
+ for name in sorted(na & nb):
62
+ x, y = _read(a, name), _read(b, name)
63
+ row = {"name": name, "shape_product": list(x.shape),
64
+ "shape_archived": list(y.shape), "cells": 0, "exact": 0,
65
+ "differing": 0, "max_abs": 0.0, "max_rel": 0.0}
66
+ if x.shape != y.shape:
67
+ row["note"] = "shapes differ; not compared cell by cell"
68
+ out["variables"].append(row)
69
+ continue
70
+ if x.dtype.kind in "fiub" and y.dtype.kind in "fiub":
71
+ xf, yf = x.astype(np.float64), y.astype(np.float64)
72
+ eq = (xf == yf) | (np.isnan(xf) & np.isnan(yf))
73
+ d = np.abs(xf - yf)
74
+ d = np.where(eq, 0.0, d)
75
+ fin = np.isfinite(d)
76
+ if fin.any():
77
+ row["max_abs"] = float(d[fin].max())
78
+ with np.errstate(divide="ignore", invalid="ignore"):
79
+ r = d / np.abs(yf)
80
+ r = np.where(eq, 0.0, r)
81
+ rf = np.isfinite(r)
82
+ row["max_rel"] = float(r[rf].max()) if rf.any() else 0.0
83
+ if (~rf & ~eq).any():
84
+ row["max_rel"] = "inf"
85
+ else:
86
+ eq = x == y
87
+ eq = np.asarray(eq, dtype=bool).reshape(x.shape)
88
+ row["cells"] = int(eq.size)
89
+ row["exact"] = int(eq.sum())
90
+ row["differing"] = int(eq.size - eq.sum())
91
+ for pos in np.argwhere(~eq):
92
+ idx = tuple(int(i) for i in pos)
93
+ out["differing_cells"].append(
94
+ {"variable": name, "index": list(idx),
95
+ "product": _scalar(x[idx]), "archived": _scalar(y[idx])})
96
+ out["variables"].append(row)
97
+ out["cells"] = sum(v["cells"] for v in out["variables"])
98
+ out["exact"] = sum(v["exact"] for v in out["variables"])
99
+ out["n_differing"] = len(out["differing_cells"])
100
+ out["identical"] = (out["n_differing"] == 0 and not out["only_in_product"]
101
+ and not out["only_in_archived"]
102
+ and all("note" not in v for v in out["variables"]))
103
+ return out
104
+
105
+
106
+ def render_markdown(rep: dict) -> str:
107
+ """Render a :func:`build_report` dict as the Markdown reproduction report."""
108
+ lines = ["# Reproduction report", "",
109
+ f"- Product: `{rep['product']}`", f"- Archived: `{rep['archived']}`"]
110
+ for side in ("product", "archived"):
111
+ c = rep["call"][side]
112
+ lines.append(f"- {side} `.call`: " + (
113
+ f"engine={c['engine']}, stamp `{c['stamp']}`" if c else "no sidecar"))
114
+ verdict = "EXACT" if rep["identical"] else "NOT EXACT"
115
+ lines += ["", f"**{verdict}**: {rep['exact']} of {rep['cells']} cells equal; "
116
+ f"{rep['n_differing']} differing.", ""]
117
+ if rep["only_in_product"]:
118
+ lines.append("Only in product: " + ", ".join(rep["only_in_product"]))
119
+ if rep["only_in_archived"]:
120
+ lines.append("Only in archived: " + ", ".join(rep["only_in_archived"]))
121
+ lines += ["| variable | cells | exact | differing | max abs | max rel | note |",
122
+ "|---|---|---|---|---|---|---|"]
123
+ for v in rep["variables"]:
124
+ lines.append(f"| {v['name']} | {v['cells']} | {v['exact']} | {v['differing']} "
125
+ f"| {v['max_abs']} | {v['max_rel']} | {v.get('note', '')} |")
126
+ lines += ["", "## Every differing cell", ""]
127
+ if not rep["differing_cells"]:
128
+ lines.append("None.")
129
+ else:
130
+ lines += ["| variable | index | product | archived |", "|---|---|---|---|"]
131
+ for c in rep["differing_cells"]:
132
+ lines.append(f"| {c['variable']} | {tuple(c['index'])} "
133
+ f"| {c['product']} | {c['archived']} |")
134
+ return "\n".join(lines) + "\n"
135
+
136
+
137
+ def write_report(product, archived, out_md=None, out_json=None) -> dict:
138
+ """Build the report for a product against its archived twin and write the requested files.
139
+
140
+ ``out_md`` receives :func:`render_markdown`'s text, ``out_json`` the report dict; either may
141
+ be omitted. Returns the report dict.
142
+ """
143
+ rep = build_report(product, archived)
144
+ if out_md:
145
+ Path(out_md).write_text(render_markdown(rep), encoding="utf-8")
146
+ if out_json:
147
+ Path(out_json).write_text(json.dumps(rep, indent=1, default=str),
148
+ encoding="utf-8")
149
+ return rep
@@ -0,0 +1,135 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Label agreement for the triage server -- Track V phase 2, item 3.
3
+
4
+ **What the plan asked for:** *"re-show a fraction of already-reviewed particles, both to the same
5
+ reviewer later and to a second reviewer. Report Cohen's kappa. Until this exists, every accuracy
6
+ number in ``ml_accept_reject.py`` is measured against labels of unknown noise."*
7
+
8
+ Two halves:
9
+
10
+ * :func:`recheck_queue` writes a queue file of a seeded random fraction of the particles a
11
+ *person* has labelled (``source == "human"``; bulk or model labels are never re-checked as
12
+ though a person made them). The queue name starts with ``recheck-``, which the triage server
13
+ reads as "store these verdicts in ``<flight>.recheck.json`` and do not show the first label".
14
+ * :func:`agreement` pairs the first labels with the re-check labels and reports Cohen's kappa,
15
+ the observed and chance agreement, and the confusion matrix.
16
+
17
+ **This changes no computed number.** It chooses which particles a person sees again and
18
+ summarises what they said, beside ``review_sampling`` and ``triage_server``.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import random
25
+ from dataclasses import dataclass, field
26
+ from pathlib import Path
27
+
28
+ from .triage_server import RECHECK_PREFIX, _load_verdicts
29
+
30
+
31
+ @dataclass
32
+ class Agreement:
33
+ """Agreement between two passes of labels over the same particles: how many, the observed
34
+ and chance agreement, Cohen's kappa (``None`` when undefined) and the confusion matrix."""
35
+
36
+ n: int
37
+ observed: float
38
+ expected: float
39
+ kappa: float | None
40
+ labels: list[str]
41
+ confusion: dict[str, dict[str, int]] = field(default_factory=dict)
42
+ """``confusion[first][second]``: how many particles got ``first`` then ``second``."""
43
+
44
+
45
+ def cohen_kappa(first: list[str], second: list[str]) -> Agreement:
46
+ """Cohen's kappa for two label lists of equal length (Cohen 1960).
47
+
48
+ ``kappa = (p_o - p_e) / (1 - p_e)``. When both raters used a single label for every item,
49
+ ``p_e == 1`` and kappa is undefined: returned as ``None`` rather than a number that looks
50
+ like a finding.
51
+ """
52
+ if len(first) != len(second):
53
+ raise ValueError(f"paired label lists differ in length: {len(first)} != {len(second)}")
54
+ n = len(first)
55
+ labels = sorted(set(first) | set(second))
56
+ confusion = {a: {b: 0 for b in labels} for a in labels}
57
+ for a, b in zip(first, second, strict=True):
58
+ confusion[a][b] += 1
59
+ if n == 0:
60
+ return Agreement(0, float("nan"), float("nan"), None, labels, confusion)
61
+ p_o = sum(confusion[x][x] for x in labels) / n
62
+ p_e = sum((sum(confusion[x].values()) / n) * (sum(confusion[a][x] for a in labels) / n)
63
+ for x in labels)
64
+ kappa = None if p_e == 1.0 else (p_o - p_e) / (1.0 - p_e)
65
+ return Agreement(n, p_o, p_e, kappa, labels, confusion)
66
+
67
+
68
+ def human_labels(verdicts: dict) -> dict[str, str]:
69
+ """``particle_index -> verdict`` for the entries a person made."""
70
+ return {k: v["verdict"] for k, v in verdicts.items()
71
+ if isinstance(v, dict) and v.get("source") == "human" and "verdict" in v}
72
+
73
+
74
+ def recheck_queue(decoded_dir: Path, flight: str, out: Path, *, fraction: float = 0.2,
75
+ seed: int = 0, minimum: int = 1) -> dict:
76
+ """Write a re-check queue for ``flight`` to ``out`` and return what was written.
77
+
78
+ Draws ``max(minimum, round(fraction * n))`` of the ``n`` human-labelled particles (all of
79
+ them if fewer), in a seeded random order so the draw can be re-derived. The coverage block
80
+ (``_about``) records the seed, the fraction and how many were drawn of how many.
81
+ """
82
+ first = human_labels(_load_verdicts(Path(decoded_dir), flight))
83
+ pool = sorted(first, key=int)
84
+ k = min(len(pool), max(minimum, round(fraction * len(pool))))
85
+ drawn = random.Random(seed).sample(pool, k) if pool else []
86
+ name = f"{RECHECK_PREFIX}{flight}-seed{seed}"[:64]
87
+ data = {
88
+ name: [{"flight": flight, "particle_index": int(i), "note": "re-check"} for i in drawn],
89
+ "_about": {"what": "re-check of human-labelled particles (review_agreement)",
90
+ "flight": flight, "seed": seed, "fraction": fraction,
91
+ "drawn": k, "of_human_labelled": len(pool)},
92
+ }
93
+ Path(out).write_text(json.dumps(data, indent=1), encoding="utf-8")
94
+ return data
95
+
96
+
97
+ def agreement(decoded_dir: Path, flight: str) -> Agreement:
98
+ """Kappa between each re-checked particle's first human label and its re-check label."""
99
+ first = human_labels(_load_verdicts(Path(decoded_dir), flight))
100
+ second = human_labels(_load_verdicts(Path(decoded_dir), flight, recheck=True))
101
+ common = sorted(set(first) & set(second), key=int)
102
+ return cohen_kappa([first[i] for i in common], [second[i] for i in common])
103
+
104
+
105
+ def reviewer_labels(verdicts: dict, reviewer: str) -> dict[str, str]:
106
+ """``particle_index -> verdict`` for the human labels ``reviewer`` made.
107
+
108
+ Reads the current record and its ``history`` (where a superseded label moves, so a second
109
+ reviewer's click never erases the first's): for each particle, the latest label stored
110
+ under ``reviewer``. Records saved without a ``reviewer`` field match no reviewer.
111
+ """
112
+ out: dict[str, str] = {}
113
+ for k, v in verdicts.items():
114
+ if not isinstance(v, dict):
115
+ continue
116
+ entries = [*v.get("history", []), {x: y for x, y in v.items() if x != "history"}]
117
+ for e in entries: # oldest first, so a later label by the same reviewer wins
118
+ if (isinstance(e, dict) and e.get("reviewer") == reviewer
119
+ and e.get("source") == "human" and "verdict" in e):
120
+ out[k] = e["verdict"]
121
+ return out
122
+
123
+
124
+ def reviewer_agreement(first: dict, second: dict, reviewer_a: str,
125
+ reviewer_b: str) -> Agreement:
126
+ """Kappa between ``reviewer_a``'s labels in ``first`` and ``reviewer_b``'s in ``second``.
127
+
128
+ ``first`` and ``second`` are loaded verdict sidecars (``_load_verdicts`` or the parsed
129
+ JSON); pass the same one twice when both reviewers labelled into one store. Only the
130
+ particles both reviewers labelled are paired.
131
+ """
132
+ a = reviewer_labels(first, reviewer_a)
133
+ b = reviewer_labels(second, reviewer_b)
134
+ common = sorted(set(a) & set(b), key=int)
135
+ return cohen_kappa([a[i] for i in common], [b[i] for i in common])
@@ -0,0 +1,327 @@
1
+ # SPDX-License-Identifier: BSD-3-Clause
2
+ """Stratified review samples that state their own coverage.
3
+
4
+ **What the plan asked for:** *"stratified sampling as an object:
5
+ ``Sample(flight, by=[reject_code, size_bin, habit], n_per_stratum)`` writing a
6
+ queue file, so a labelled set can state its own coverage."*
7
+
8
+ **Why the last clause is the whole point.** A labelled set built by opening the
9
+ flight page and clicking through whatever looks interesting cannot say what it
10
+ covers, so an accuracy number computed from it cannot say what it is an accuracy
11
+ *over*. What this writes carries its strata, its per-stratum counts and the seed
12
+ that produced it in the same file as the particle list, so the coverage
13
+ statement is part of the artefact rather than something reconstructed afterwards
14
+ from memory.
15
+
16
+ **Under-filled strata are reported, never quietly dropped.** A stratum with
17
+ fewer particles than asked for takes what it has and says so; a stratum the
18
+ flight has none of is listed with a count of zero rather than omitted. Both are
19
+ findings about the flight -- "this flight has no particle over 1 mm" is exactly
20
+ what a reviewer needs before reading an accuracy number, and it is invisible if
21
+ empty strata simply do not appear in the file.
22
+
23
+ **This changes no computed number.** It selects which particles a person is
24
+ shown, in what order. That is why it sits in the port beside ``triage_server``
25
+ rather than in ``enhancements`` (visualisation and manual
26
+ labelling never change a computed number).
27
+
28
+ The file it writes is the shape ``triage_server._load_queue_file`` already
29
+ reads::
30
+
31
+ {"<queue name>": [{"flight": ..., "particle_index": ..., "note": ...}, ...]}
32
+
33
+ with the coverage under a reserved, underscore-prefixed key.
34
+
35
+ ``_load_queue_file`` skips underscore-prefixed keys by rule, so the coverage
36
+ block is not read as a queue -- found by the test that asserted the
37
+ server could read what this writes, which is why that test exists rather than a
38
+ comment saying the shapes match.
39
+ """
40
+ from __future__ import annotations
41
+
42
+ import json
43
+ import random
44
+ from dataclasses import dataclass
45
+ from pathlib import Path
46
+
47
+ import numpy as np
48
+
49
+ __all__ = [
50
+ "COVERAGE_KEY",
51
+ "SIZE_EDGES",
52
+ "STRATIFIERS",
53
+ "Sample",
54
+ "Stratum",
55
+ "full_axis",
56
+ "stratum_labels",
57
+ ]
58
+
59
+ #: Where the coverage statement lives in the queue file. Underscore-prefixed so
60
+ #: it can never collide with a queue name, and so a reader can skip it by a rule
61
+ #: rather than by knowing this particular string.
62
+ COVERAGE_KEY = "_coverage"
63
+
64
+ #: The strata this understands, and the ``proc`` variable each is read from.
65
+ #: A caller naming anything else is refused rather than quietly given one
66
+ #: stratum -- that failure would produce a "stratified" sample that is not one,
67
+ #: and nothing downstream could tell.
68
+ STRATIFIERS = {
69
+ "reject_code": "image_auto_reject",
70
+ "habit": "holroyd_habit",
71
+ "size_bin": "image_diam_minR",
72
+ "center_in": "image_center_in",
73
+ }
74
+
75
+ #: Size-bin edges in mm. Deliberately coarse: this spreads a reviewer's
76
+ #: attention across sizes, it is not a size distribution. Stratifying on the
77
+ #: 128 sizing bins would give about one particle per stratum and no coverage
78
+ #: statement worth having.
79
+ SIZE_EDGES = (0.0, 0.05, 0.1, 0.2, 0.4, 1.0, float("inf"))
80
+
81
+
82
+ def full_axis(name: str) -> list[str] | None:
83
+ """Every label a stratifier can take, or ``None`` when that is unknowable.
84
+
85
+ This is the difference between a coverage statement that can say *"this
86
+ flight has no particle above 1 mm"* and one that can only say what it
87
+ happened to see. ``size_bin`` has a closed vocabulary -- the edges are right
88
+ here -- so its axis is complete and an unrepresented bin appears with a
89
+ count of zero.
90
+
91
+ ``reject_code`` and ``habit`` do not: their vocabularies live in
92
+ ``calculate_reject_unified.m`` and ``holroyd.m``, and a code that no
93
+ version emits would be a permanently empty row in every coverage statement
94
+ ever written. For those the axis is what the flight shows, and
95
+ :meth:`Sample.coverage` says which kind each stratifier was.
96
+ """
97
+ if name == "size_bin":
98
+ out = []
99
+ for lo, hi in zip(SIZE_EDGES[:-1], SIZE_EDGES[1:], strict=True):
100
+ out.append(f"{lo:g}-{'inf' if hi == float('inf') else f'{hi:g}'}mm")
101
+ return out
102
+ return None
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class Stratum:
107
+ """One cell of the cross-product, and what it actually yielded.
108
+
109
+ ``available`` is what the flight holds; ``taken`` is what the sample got.
110
+ They differ whenever a stratum is thinner than ``n_per_stratum``, and that
111
+ difference is the coverage statement's most useful line.
112
+ """
113
+
114
+ key: tuple[str, ...]
115
+ available: int
116
+ taken: int
117
+ indices: tuple[int, ...] = ()
118
+
119
+ @property
120
+ def under_filled(self) -> bool:
121
+ """Did this stratum have less than was asked of it?"""
122
+ return self.taken < self.requested
123
+
124
+ #: Set by :class:`Sample` when it builds the stratum; kept as a field rather
125
+ #: than recomputed so a stratum read back from a file is still honest.
126
+ requested: int = 0
127
+
128
+ def as_dict(self) -> dict:
129
+ """The row as it is written into the queue file's coverage block.
130
+
131
+ ``requested`` travels with ``taken`` deliberately: without it a reader
132
+ cannot tell a stratum that was satisfied from one that was scraped
133
+ empty, which is the single most useful thing the coverage says.
134
+ """
135
+ return {
136
+ "stratum": list(self.key),
137
+ "available": self.available,
138
+ "requested": self.requested,
139
+ "taken": self.taken,
140
+ "under_filled": self.under_filled,
141
+ }
142
+
143
+
144
+ def stratum_labels(name: str, values: np.ndarray) -> np.ndarray:
145
+ """Turn one ``proc`` variable into per-particle stratum labels.
146
+
147
+ Kept separate from :class:`Sample` so the labelling can be tested on arrays
148
+ without a netCDF file anywhere near it.
149
+ """
150
+ values = np.asarray(values).reshape(-1)
151
+ if name == "size_bin":
152
+ idx = np.digitize(np.asarray(values, float), SIZE_EDGES) - 1
153
+ out = []
154
+ for i in idx:
155
+ if 0 <= i < len(SIZE_EDGES) - 1:
156
+ hi = SIZE_EDGES[i + 1]
157
+ out.append(f"{SIZE_EDGES[i]:g}-{'inf' if hi == float('inf') else f'{hi:g}'}mm")
158
+ else:
159
+ # Reaches here only for a NaN or a negative diameter. Labelled
160
+ # rather than dropped: a flight with such particles is saying
161
+ # something, and silence would hide it.
162
+ out.append("out-of-range")
163
+ return np.array(out)
164
+ if name in ("reject_code", "habit"):
165
+ # These are stored as character codes. A value outside printable ASCII
166
+ # is shown as its number rather than mangled into a control character.
167
+ return np.array([chr(int(v)) if 32 <= int(v) < 127 else f"#{int(v)}"
168
+ for v in values])
169
+ return np.array([str(int(v)) for v in values])
170
+
171
+
172
+ class Sample:
173
+ """A stratified draw over one flight's ``proc`` file.
174
+
175
+ ``by`` names strata from :data:`STRATIFIERS`; the sample is the cross-product
176
+ of their values, ``n_per_stratum`` particles from each, drawn with a seeded
177
+ RNG so the same arguments give the same queue on any machine.
178
+ """
179
+
180
+ def __init__(self, flight: str, proc_file, *, by, n_per_stratum: int,
181
+ seed: int = 0, only_accepted: bool = False):
182
+ unknown = [b for b in by if b not in STRATIFIERS]
183
+ if unknown:
184
+ raise ValueError(
185
+ f"unknown stratifier(s) {unknown}; known: {sorted(STRATIFIERS)}. "
186
+ "Refused rather than ignored -- a stratifier that silently did "
187
+ "nothing would produce a sample that is not stratified and "
188
+ "nothing downstream could tell.")
189
+ if not by:
190
+ raise ValueError("`by` must name at least one stratifier")
191
+ if n_per_stratum < 1:
192
+ raise ValueError("n_per_stratum must be at least 1")
193
+
194
+ self.flight = flight
195
+ self.proc_file = Path(proc_file)
196
+ self.by = list(by)
197
+ self.n_per_stratum = int(n_per_stratum)
198
+ self.seed = int(seed)
199
+ self.only_accepted = bool(only_accepted)
200
+ self.strata: list[Stratum] = []
201
+ self._build()
202
+
203
+ def _read(self):
204
+ import netCDF4
205
+
206
+ with netCDF4.Dataset(str(self.proc_file)) as ds:
207
+ ds.set_auto_maskandscale(False)
208
+ columns = {b: stratum_labels(b, ds.variables[STRATIFIERS[b]][:])
209
+ for b in self.by}
210
+ n = len(next(iter(columns.values())))
211
+ keep = np.ones(n, dtype=bool)
212
+ if self.only_accepted:
213
+ rej = np.asarray(ds.variables["image_auto_reject"][:]).reshape(-1)
214
+ from .render import is_accepted_code
215
+ keep = is_accepted_code(rej)
216
+ return columns, keep
217
+
218
+ def _build(self):
219
+ columns, keep = self._read()
220
+ n = len(keep)
221
+ rng = random.Random(self.seed)
222
+
223
+ # A stratifier with a closed vocabulary (`size_bin`) gets its full
224
+ # axis, so a bin this flight has nothing in appears with a count of
225
+ # zero -- "no particle above 1 mm" is a finding, and it is invisible if
226
+ # the row is simply absent. One with an open vocabulary
227
+ # (`reject_code`, `habit`) gets what the flight shows: a row for every
228
+ # code no version emits would be permanent noise. `coverage()` records
229
+ # which kind each was, so a reader is never left guessing whether an
230
+ # absent stratum was empty or unaskable.
231
+ axes = [full_axis(b) or sorted(set(columns[b].tolist())) for b in self.by]
232
+ members: dict[tuple, list[int]] = {}
233
+ for i in range(n):
234
+ if not keep[i]:
235
+ continue
236
+ members.setdefault(tuple(columns[b][i] for b in self.by), []).append(i)
237
+
238
+ def product(axes_):
239
+ out = [()]
240
+ for axis in axes_:
241
+ out = [prev + (v,) for prev in out for v in axis]
242
+ return out
243
+
244
+ for key in product(axes):
245
+ pool = members.get(key, [])
246
+ take = sorted(rng.sample(pool, min(self.n_per_stratum, len(pool))))
247
+ self.strata.append(Stratum(
248
+ key=key, available=len(pool), taken=len(take),
249
+ indices=tuple(take), requested=self.n_per_stratum))
250
+
251
+ # ------------------------------------------------------------------ output
252
+ @property
253
+ def queue_name(self) -> str:
254
+ """A default name carrying every argument that shaped the draw.
255
+
256
+ Flight, strata, per-stratum count and seed -- so two samples of one
257
+ flight cannot overwrite each other in a shared queue file, and so a
258
+ name alone says how to regenerate what it points at.
259
+ """
260
+ return f"{self.flight}-{'+'.join(self.by)}-n{self.n_per_stratum}-s{self.seed}"
261
+
262
+ def items(self) -> list[dict]:
263
+ """The queue entries, in stratum order then particle order."""
264
+ out = []
265
+ for stratum in self.strata:
266
+ note = ", ".join(f"{b}={v}" for b, v in zip(self.by, stratum.key, strict=True))
267
+ for idx in stratum.indices:
268
+ out.append({"flight": self.flight, "particle_index": int(idx),
269
+ "note": note})
270
+ return out
271
+
272
+ def coverage(self) -> dict:
273
+ """What this sample covers, in the terms a reader will need."""
274
+ filled = [s for s in self.strata if s.taken]
275
+ return {
276
+ "flight": self.flight,
277
+ "proc_file": self.proc_file.name,
278
+ "by": self.by,
279
+ "n_per_stratum": self.n_per_stratum,
280
+ "seed": self.seed,
281
+ "only_accepted": self.only_accepted,
282
+ "axes": {b: ("closed" if full_axis(b) else "observed") for b in self.by},
283
+ "n_strata": len(self.strata),
284
+ "n_strata_with_particles": len(filled),
285
+ "n_strata_empty": sum(1 for s in self.strata if s.available == 0),
286
+ "n_strata_under_filled": sum(1 for s in self.strata if s.under_filled),
287
+ "n_particles": sum(s.taken for s in self.strata),
288
+ "strata": [s.as_dict() for s in self.strata],
289
+ }
290
+
291
+ def write(self, path, *, queue_name: str | None = None) -> Path:
292
+ """Write (or add to) a queue file, coverage included.
293
+
294
+ Merges into an existing file rather than replacing it, because a
295
+ reviewer's other queues live there and losing them to a second sample
296
+ would be the labels-lost failure this tool's neighbours already exist to
297
+ prevent.
298
+ """
299
+ path = Path(path)
300
+ name = queue_name or self.queue_name
301
+ data = {}
302
+ if path.exists():
303
+ data = json.loads(path.read_text(encoding="utf-8"))
304
+ if not isinstance(data, dict):
305
+ raise ValueError(f"{path} is not a queue file (parsed as "
306
+ f"{type(data).__name__}); refusing to replace it")
307
+ data[name] = self.items()
308
+ coverage = data.setdefault(COVERAGE_KEY, {})
309
+ coverage[name] = self.coverage()
310
+ path.write_text(json.dumps(data, indent=1, sort_keys=True), encoding="utf-8")
311
+ return path
312
+
313
+ def summary(self) -> str:
314
+ """A human-readable coverage statement, for a log or a report."""
315
+ c = self.coverage()
316
+ lines = [
317
+ f"{c['n_particles']} particle(s) from {c['n_strata_with_particles']} "
318
+ f"of {c['n_strata']} strata ({' x '.join(self.by)}), "
319
+ f"{c['n_per_stratum']} requested each, seed {c['seed']}",
320
+ ]
321
+ if c["n_strata_empty"]:
322
+ lines.append(f" {c['n_strata_empty']} stratum/strata this flight has "
323
+ f"none of -- listed with a count of zero, not dropped")
324
+ if c["n_strata_under_filled"]:
325
+ lines.append(f" {c['n_strata_under_filled']} stratum/strata thinner "
326
+ f"than {c['n_per_stratum']}; the sample took all of each")
327
+ return "\n".join(lines)