mintfig 0.2.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 (47) hide show
  1. mintfig/__init__.py +162 -0
  2. mintfig/_explain/__init__.py +1 -0
  3. mintfig/_explain/change.py +392 -0
  4. mintfig/_explain/compare.py +1308 -0
  5. mintfig/_explain/compare_grouped.py +472 -0
  6. mintfig/_explain/core.py +2005 -0
  7. mintfig/_explain/distribution.py +1268 -0
  8. mintfig/_explain/flow.py +508 -0
  9. mintfig/_explain/layout.py +2012 -0
  10. mintfig/_explain/matrix.py +623 -0
  11. mintfig/_explain/relate.py +1318 -0
  12. mintfig/_explain/timeline.py +595 -0
  13. mintfig/_explain/trend.py +2557 -0
  14. mintfig/_explain/waterfall.py +459 -0
  15. mintfig/_table.py +691 -0
  16. mintfig/_tabular.py +738 -0
  17. mintfig/annotations.py +1165 -0
  18. mintfig/assets/AGENTS_SNIPPET.md +11 -0
  19. mintfig/assets/SKILL.md +143 -0
  20. mintfig/assets/__init__.py +1 -0
  21. mintfig/assets/references/publication.md +79 -0
  22. mintfig/assets/references/scientific_and_recipes.md +213 -0
  23. mintfig/audit.py +179 -0
  24. mintfig/brief.py +518 -0
  25. mintfig/bundle.py +333 -0
  26. mintfig/cli.py +1300 -0
  27. mintfig/edit.py +347 -0
  28. mintfig/epistemic.py +1083 -0
  29. mintfig/explainer.py +194 -0
  30. mintfig/export.py +247 -0
  31. mintfig/inspect_data.py +583 -0
  32. mintfig/interactive.py +1028 -0
  33. mintfig/palettes.py +233 -0
  34. mintfig/plate.py +784 -0
  35. mintfig/preflight.py +2398 -0
  36. mintfig/proof.py +627 -0
  37. mintfig/runner.py +403 -0
  38. mintfig/skill.py +167 -0
  39. mintfig/specs.py +291 -0
  40. mintfig/style.py +151 -0
  41. mintfig/terminal.py +785 -0
  42. mintfig/themes.py +660 -0
  43. mintfig-0.2.0.dist-info/METADATA +239 -0
  44. mintfig-0.2.0.dist-info/RECORD +47 -0
  45. mintfig-0.2.0.dist-info/WHEEL +4 -0
  46. mintfig-0.2.0.dist-info/entry_points.txt +2 -0
  47. mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
mintfig/epistemic.py ADDED
@@ -0,0 +1,1083 @@
1
+ """Epistemic / slant auditing and four-level semantic narratives for ``mint.explain``.
2
+
3
+ Implements:
4
+ - Four-level semantic narrative (Lundgard & Satyanarayan, IEEE VIS 2021):
5
+ :func:`build_narrative` produces structured L1 (encoded construction), L2
6
+ (statistical facts), L3 (perceptual/pattern facts), L4 (domain takeaway),
7
+ and a compact reader-first ``summary`` string.
8
+ - Tightly scoped epistemic / slant audit (Kong, Liu & Karahalios, CHI 2018):
9
+ :func:`audit_epistemic` emits advisory ``severity="warning"`` issues only for
10
+ two high-precision failure modes (``claim_overstates_uncertainty`` and
11
+ ``claim_number_mismatch``) with near-zero false positives.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ import numbers
18
+ import re
19
+ from collections.abc import Mapping, Sequence
20
+ from typing import Any
21
+
22
+ # --------------------------------------------------------------------------- #
23
+ # Panel accessors (work with both Panel instances and plain dict specs/summaries)
24
+ # --------------------------------------------------------------------------- #
25
+
26
+
27
+ def _pget(panel: Any, key: str, default: Any = None) -> Any:
28
+ if isinstance(panel, Mapping):
29
+ return panel.get(key, default)
30
+ return getattr(panel, key, default)
31
+
32
+
33
+ def _pspec(panel: Any) -> Mapping[str, Any]:
34
+ spec = _pget(panel, "spec")
35
+ if isinstance(spec, Mapping):
36
+ return spec
37
+ if isinstance(panel, Mapping):
38
+ return panel
39
+ return {}
40
+
41
+
42
+ def _pfacts(panel: Any) -> list[str]:
43
+ facts = _pget(panel, "facts") or []
44
+ return [str(f) for f in facts if isinstance(f, str) and f.strip()]
45
+
46
+
47
+ def _is_finite_number(value: Any) -> bool:
48
+ if isinstance(value, bool):
49
+ return False
50
+ if isinstance(value, numbers.Real):
51
+ return math.isfinite(float(value))
52
+ # Support numpy scalar types without importing numpy
53
+ cls_name = type(value).__module__
54
+ if cls_name.startswith("numpy") and not isinstance(value, (str, bytes)):
55
+ try:
56
+ fval = float(value)
57
+ return math.isfinite(fval)
58
+ except (TypeError, ValueError):
59
+ return False
60
+ return False
61
+
62
+
63
+ # --------------------------------------------------------------------------- #
64
+ # Part 1: Four-Level Semantic Narrative (Lundgard & Satyanarayan, VIS 2021)
65
+ # --------------------------------------------------------------------------- #
66
+
67
+ # Patterns classifying computed panel facts into L3 (perceptual/cognitive patterns)
68
+ # vs L2 (concrete statistical facts).
69
+ _L3_PATTERN_RE = re.compile(
70
+ r"(?:"
71
+ r"\N{RIGHTWARDS ARROW}|" # trajectory / before->after shift
72
+ r"\bbefore\s+.+\bfrom it on\b|"
73
+ r"\bcrosses?\b|"
74
+ r"\bstay(?:s)?\s+(?:above|below)\b|"
75
+ r"\bPareto frontier\b|"
76
+ r"\bleads\s+\d+\s+of\s+\d+|"
77
+ r"\bleader\b|"
78
+ r"\bnext highest\b|"
79
+ r"\bnext lowest\b|"
80
+ r"\brank\s+1\s+of\b|"
81
+ r"\bfar from the rest\b|"
82
+ r"\bpeak bin\b|"
83
+ r"\boverlaps?\b|"
84
+ r"\bdoes not overlap\b|"
85
+ r"\bevery\s+.+\s+value\s+is\s+(?:above|below)\b|"
86
+ r"\ball but\s+\d+\s+of\s+\d+\s+.+\s+lie\s+(?:above|below)\b|"
87
+ r"\bPearson r\s*=|"
88
+ r"\br\s*=\s*[\-\N{MINUS SIGN}]?\d|"
89
+ r"\bfitted line\b|"
90
+ r"\blog\N{SUBSCRIPT ONE}\N{SUBSCRIPT ZERO}\s+slope\b|"
91
+ r"y\s*\N{PROPORTIONAL TO}\s*x|"
92
+ r"\bpooled across groups\b|"
93
+ r"\bstrongest off-diagonal\b|"
94
+ r"\blargest off-diagonal\b|"
95
+ r"\blargest change:|"
96
+ r"\blargest\s+.+\s+gain:|"
97
+ r"\blargest\s+(?:positive\s+driver|negative\s+drag|drop):|"
98
+ r"\blongest\s+stage:|"
99
+ r"\blinear\s+fit\s+slope\b|"
100
+ r"\bpeak\s+\d+\s+stages\s+overlapping\b|"
101
+ r"\b\d+\s+up,\s+\d+\s+down\b|"
102
+ r"\bchange(?:s)?\s+by\s+.+\s+from first to last\b|"
103
+ r"\bend at\s+.+\s+their first values\b|"
104
+ r"\bpeak within\s+.+\s+of their own medians\b|"
105
+ r"\btop\s+\d+\s+together:|"
106
+ r"\btogether:\s+\d+(?:\.\d+)?%"
107
+ r")",
108
+ re.IGNORECASE,
109
+ )
110
+
111
+ # Metadata/housekeeping facts that belong in L2 but are skipped in the compact summary
112
+ # when higher-signal facts exist.
113
+ _META_FACT_RE = re.compile(
114
+ r"^(?:"
115
+ r"intervals read as\b|"
116
+ r"bands read as\b|"
117
+ r"binned into\b|"
118
+ r"\d+\s+(?:rows|categories)\s*\N{MULTIPLICATION SIGN}\s*\d+\s+(?:columns|series)$|"
119
+ r"diagonal is\b|"
120
+ r"\d+\s+empty cell|"
121
+ r"\d+\s+of\s+\d+\s+cells empty"
122
+ r")",
123
+ re.IGNORECASE,
124
+ )
125
+
126
+
127
+ def _label_has_unit(label: str, unit: str) -> bool:
128
+ u = unit.strip()
129
+ if not u:
130
+ return True
131
+ return bool(re.search(rf"[(\[]\s*{re.escape(u)}\s*[)\]]\s*$", label.strip()))
132
+
133
+
134
+ def _table_columns(spec: Mapping[str, Any]) -> list[str]:
135
+ cols = spec.get("columns")
136
+ if isinstance(cols, Sequence) and not isinstance(cols, (str, bytes)):
137
+ return [str(c) for c in cols if str(c).strip()]
138
+ rows = spec.get("rows")
139
+ if isinstance(rows, Mapping):
140
+ return [str(k) for k in rows]
141
+ if isinstance(rows, Sequence) and not isinstance(rows, (str, bytes)) and rows:
142
+ first = rows[0]
143
+ if isinstance(first, Mapping):
144
+ return [str(k) for k in first]
145
+ return []
146
+
147
+
148
+ def _describe_panel_l1(panel: Any) -> str:
149
+ kind = str(_pget(panel, "kind", "panel") or "panel")
150
+ label = _pget(panel, "label")
151
+ unit = _pget(panel, "unit")
152
+ spec = _pspec(panel)
153
+
154
+ parts: list[str] = []
155
+ if kind == "table":
156
+ cols = _table_columns(spec)
157
+ if cols:
158
+ shown = cols[:4]
159
+ if len(cols) > 4:
160
+ shown.append(f"+{len(cols) - 4} more")
161
+ parts.append(", ".join(shown))
162
+ elif label:
163
+ parts.append(str(label))
164
+ elif kind == "relate":
165
+ x_label = spec.get("x_label")
166
+ y_label = spec.get("y_label") or label
167
+ if x_label and y_label:
168
+ parts.append(f"{x_label} vs {y_label}")
169
+ elif y_label:
170
+ parts.append(str(y_label))
171
+ elif x_label:
172
+ parts.append(str(x_label))
173
+ if spec.get("log_x") and spec.get("log_y"):
174
+ parts.append("log-log")
175
+ elif spec.get("log_x"):
176
+ parts.append("log x")
177
+ elif spec.get("log_y"):
178
+ parts.append("log y")
179
+ if spec.get("frontier"):
180
+ parts.append("Pareto frontier")
181
+ elif kind == "trend":
182
+ if label:
183
+ parts.append(str(label))
184
+ if unit and not _label_has_unit(str(label), str(unit)):
185
+ parts.append(str(unit))
186
+ elif unit:
187
+ parts.append(str(unit))
188
+ x_label = spec.get("x_label")
189
+ if x_label:
190
+ if parts:
191
+ parts[-1] = f"{parts[-1]} vs {x_label}"
192
+ else:
193
+ parts.append(str(x_label))
194
+ if spec.get("log") and spec.get("log_x"):
195
+ parts.append("log-log")
196
+ elif spec.get("log"):
197
+ parts.append("log y")
198
+ elif spec.get("log_x"):
199
+ parts.append("log x")
200
+ if spec.get("facet"):
201
+ parts.append("faceted")
202
+ elif kind == "matrix":
203
+ if label:
204
+ parts.append(str(label))
205
+ if unit and (not label or not _label_has_unit(str(label), str(unit))):
206
+ parts.append(str(unit))
207
+ rows = spec.get("rows")
208
+ cols = spec.get("cols")
209
+ if isinstance(rows, Sequence) and isinstance(cols, Sequence):
210
+ parts.append(f"{len(rows)}\N{MULTIPLICATION SIGN}{len(cols)}")
211
+ tri = spec.get("triangle")
212
+ if isinstance(tri, str) and tri:
213
+ parts.append(f"{tri} triangle")
214
+ elif kind == "change":
215
+ if label:
216
+ parts.append(str(label))
217
+ if unit and (not label or not _label_has_unit(str(label), str(unit))):
218
+ parts.append(str(unit))
219
+ pair_labels = spec.get("labels")
220
+ if (
221
+ isinstance(pair_labels, Sequence)
222
+ and not isinstance(pair_labels, (str, bytes))
223
+ and len(pair_labels) == 2
224
+ ):
225
+ parts.append(f"{pair_labels[0]} \N{RIGHTWARDS ARROW} {pair_labels[1]}")
226
+ elif kind == "distribution":
227
+ if label:
228
+ parts.append(str(label))
229
+ if unit and (not label or not _label_has_unit(str(label), str(unit))):
230
+ parts.append(str(unit))
231
+ if spec.get("bins") is not None:
232
+ parts.append("histogram")
233
+ if spec.get("log"):
234
+ parts.append("log scale")
235
+ elif kind == "waterfall":
236
+ if label:
237
+ parts.append(str(label))
238
+ if unit and (not label or not _label_has_unit(str(label), str(unit))):
239
+ parts.append(str(unit))
240
+ steps = spec.get("steps")
241
+ if isinstance(steps, Mapping):
242
+ parts.append(f"{len(steps)} steps")
243
+ elif kind == "timeline":
244
+ x_label = spec.get("x_label") or label
245
+ tl_unit = unit or spec.get("unit")
246
+ if x_label:
247
+ parts.append(str(x_label))
248
+ if tl_unit and (not x_label or not _label_has_unit(str(x_label), str(tl_unit))):
249
+ parts.append(str(tl_unit))
250
+ spans = spec.get("spans")
251
+ if isinstance(spans, Sequence) and not isinstance(spans, (str, bytes)):
252
+ parts.append(f"{len(spans)} stages")
253
+ elif kind == "flow":
254
+ if label:
255
+ parts.append(str(label))
256
+ if unit and (not label or not _label_has_unit(str(label), str(unit))):
257
+ parts.append(str(unit))
258
+ stages = spec.get("stages")
259
+ if isinstance(stages, Sequence) and not isinstance(stages, (str, bytes)):
260
+ parts.append(f"{len(stages)} stages")
261
+ elif kind == "custom":
262
+ desc = _pget(panel, "describe")
263
+ if label:
264
+ parts.append(str(label))
265
+ if unit and (not label or not _label_has_unit(str(label), str(unit))):
266
+ parts.append(str(unit))
267
+ if not parts and desc:
268
+ parts.append(str(desc))
269
+ else:
270
+ # compare, share, or unknown future form
271
+ if label:
272
+ parts.append(str(label))
273
+ if unit and (not label or not _label_has_unit(str(label), str(unit))):
274
+ parts.append(str(unit))
275
+ if spec.get("log"):
276
+ parts.append("log scale")
277
+
278
+ if not parts:
279
+ desc = _pget(panel, "describe")
280
+ if desc:
281
+ parts.append(str(desc))
282
+ return f"{kind} ({', '.join(parts)})" if parts else kind
283
+
284
+
285
+ def build_narrative(
286
+ takeaway: str,
287
+ panels: Mapping[str, Any],
288
+ *,
289
+ subtitle: str | None = None,
290
+ source: str | None = None,
291
+ ) -> dict[str, Any]:
292
+ """Build a four-level semantic narrative (Lundgard & Satyanarayan, IEEE VIS 2021).
293
+
294
+ Returns a dict with keys:
295
+ - ``"L1"``: concise structural construction summary (panel count, kinds, labels/units)
296
+ - ``"L2"``: ``list[str]`` of concrete statistical facts (extrema, ranges, CIs, counts, deltas)
297
+ - ``"L3"``: ``list[str]`` of perceptual/pattern facts (trends, crossings, shifts, leaders,
298
+ Pareto frontier, correlations, overlap/clusters)
299
+ - ``"L4"``: domain takeaway sentence (+ subtitle scope if present)
300
+ - ``"summary"``: compact reader-first string prioritizing L4 + top L3/L2 facts
301
+ """
302
+ n_panels = len(panels)
303
+ panel_noun = "panel" if n_panels == 1 else "panels"
304
+ l1_descs = [_describe_panel_l1(p) for p in panels.values()]
305
+ l1 = f"{n_panels} {panel_noun}: {'; '.join(l1_descs)}" if l1_descs else "0 panels"
306
+
307
+ l2: list[str] = []
308
+ l3: list[str] = []
309
+ multi = n_panels > 1
310
+ for key, panel in panels.items():
311
+ prefix = f"[{key}] " if multi else ""
312
+ for fact in _pfacts(panel):
313
+ tagged = f"{prefix}{fact}"
314
+ if _L3_PATTERN_RE.search(fact):
315
+ l3.append(tagged)
316
+ else:
317
+ l2.append(tagged)
318
+
319
+ clean_takeaway = " ".join(str(takeaway).split()).strip()
320
+ l4_parts: list[str] = []
321
+ if clean_takeaway:
322
+ l4_parts.append(clean_takeaway.rstrip(".") + ".")
323
+ if subtitle and str(subtitle).strip():
324
+ clean_sub = " ".join(str(subtitle).split()).strip()
325
+ l4_parts.append(clean_sub.rstrip(".") + ".")
326
+ l4 = " ".join(l4_parts)
327
+
328
+ # Compact reader-first summary: L4 + up to 3 high-signal facts (L3 first, then L2) + source.
329
+ summary_parts: list[str] = []
330
+ if l4:
331
+ summary_parts.append(l4)
332
+
333
+ def _strip_prefix(text: str) -> str:
334
+ return re.sub(r"^\[[^\]]+\]\s*", "", text)
335
+
336
+ top_l3 = [f for f in l3 if not _META_FACT_RE.search(_strip_prefix(f))][:2]
337
+ top_l2 = [f for f in l2 if not _META_FACT_RE.search(_strip_prefix(f))][:2]
338
+ highlights = [*top_l3, *top_l2][:3]
339
+ if not highlights:
340
+ highlights = (l3 + l2)[:2]
341
+ for fact in highlights:
342
+ summary_parts.append(fact.rstrip(".") + ".")
343
+ if source and str(source).strip():
344
+ clean_src = " ".join(str(source).split()).strip().rstrip(".")
345
+ summary_parts.append(f"Source: {clean_src}.")
346
+
347
+ return {
348
+ "L1": l1,
349
+ "L2": l2,
350
+ "L3": l3,
351
+ "L4": l4,
352
+ "summary": " ".join(summary_parts),
353
+ }
354
+
355
+
356
+ # --------------------------------------------------------------------------- #
357
+ # Part 2: Tightly Scoped Epistemic / Slant Audit (Kong et al., CHI 2018)
358
+ # --------------------------------------------------------------------------- #
359
+
360
+
361
+ def _advisory(
362
+ rule: str,
363
+ message: str,
364
+ fix_hint: str,
365
+ *,
366
+ panel: str | None = None,
367
+ ) -> dict[str, Any]:
368
+ return {
369
+ "rule": rule,
370
+ "severity": "warning",
371
+ "panel": panel,
372
+ "message": message,
373
+ "fix_hint": fix_hint,
374
+ }
375
+
376
+
377
+ # Tight allowlist of explicit strong certainty / significance claims.
378
+ _STRONG_CERTAINTY_RE = re.compile(
379
+ r"\b("
380
+ r"statistically\s+significant|"
381
+ r"proves|proven|disproves|disproven|"
382
+ r"conclusively|conclusive|"
383
+ r"unambiguously|unambiguous|"
384
+ r"decisively|decisive|"
385
+ r"definitively|definitive|"
386
+ r"clearly\s+(?:beats?|outperforms?|hurts?|lower|higher|better|worse|exceeds?|leads?|wins?|reduces?|increases?|improves?|cuts?|drops?)|"
387
+ r"outside\s+(?:seed\s+)?noise|"
388
+ r"beyond\s+(?:seed\s+)?noise|"
389
+ r"beyond\s+doubt"
390
+ r")\b",
391
+ re.IGNORECASE,
392
+ )
393
+
394
+ _OVERLAP_WORD_RE = re.compile(r"\boverlaps?\b", re.IGNORECASE)
395
+ _OVERLAP_NEGATED_RE = re.compile(
396
+ r"\b(?:no|not|never|non|do\s+not|does\s+not|did\s+not|without)\s+overlaps?\b"
397
+ r"|\bclear\s+of\b"
398
+ r"|\boutside\b",
399
+ re.IGNORECASE,
400
+ )
401
+ _SMALL_N_CAUTION_RE = re.compile(
402
+ r"\b(?:rough\s+estimate|small\s+n|quartiles\s+are\s+not\s+meaningful)\b",
403
+ re.IGNORECASE,
404
+ )
405
+
406
+
407
+ def _fact_has_conflicting_uncertainty(fact: str) -> str | None:
408
+ """Return a concise reason string if ``fact`` reports overlapping intervals or small-n caution."""
409
+ if _SMALL_N_CAUTION_RE.search(fact):
410
+ return "small-n rough estimate"
411
+ for clause in fact.split(";"):
412
+ if _OVERLAP_WORD_RE.search(clause) and not _OVERLAP_NEGATED_RE.search(clause):
413
+ return "overlapping intervals"
414
+ return None
415
+
416
+
417
+ def _check_overstates_uncertainty(
418
+ takeaway: str,
419
+ panels: Mapping[str, Any],
420
+ ) -> list[dict[str, Any]]:
421
+ match = _STRONG_CERTAINTY_RE.search(takeaway)
422
+ if match is None:
423
+ return []
424
+ phrase = match.group(0)
425
+
426
+ conflicts: list[tuple[str, str, str]] = []
427
+ for key, panel in panels.items():
428
+ for fact in _pfacts(panel):
429
+ reason = _fact_has_conflicting_uncertainty(fact)
430
+ if reason is not None:
431
+ conflicts.append((str(key), reason, fact))
432
+ break
433
+
434
+ if not conflicts:
435
+ return []
436
+
437
+ reasons = list(dict.fromkeys(r for _, r, _ in conflicts))
438
+ panel_keys = [k for k, _, _ in conflicts]
439
+ panel_ref = panel_keys[0] if len(panel_keys) == 1 else None
440
+ sample_fact = conflicts[0][2]
441
+ reason_text = " and ".join(reasons)
442
+ return [
443
+ _advisory(
444
+ "claim_overstates_uncertainty",
445
+ f"Takeaway uses strong certainty wording ({phrase!r}), while panel facts indicate "
446
+ f"{reason_text} ({sample_fact}).",
447
+ "Hedge the takeaway wording to match the overlapping intervals or small n "
448
+ "(e.g. 'tends to', 'suggests', or state the observed difference directly), "
449
+ "or report the formal statistical test and p-value in note=.",
450
+ panel=panel_ref,
451
+ )
452
+ ]
453
+
454
+
455
+ # Hedge markers in takeaway: if present, skip claim_number_mismatch completely.
456
+ _HEDGE_RE = re.compile(
457
+ r"[~≈]"
458
+ r"|\b(?:about|approx\.?|approximately|roughly|nearly|around|almost|over|under)\b",
459
+ re.IGNORECASE,
460
+ )
461
+
462
+ # Change verbs: used only to avoid bogus 2-item 50/50 share matching on relative-drop claims.
463
+ _CHANGE_CLAIM_RE = re.compile(
464
+ r"\b(?:drop(?:s|ped)?|cut(?:s)?|fell|fall(?:s)?|decline(?:s|d)?|decreas(?:e|es|ed)|"
465
+ r"reduc(?:e|es|ed|tion)|less|lower|below|gain(?:s|ed)?|rise(?:s)?|rose|"
466
+ r"increas(?:e|es|ed)|higher|more|above|faster|slower|up|down)\b",
467
+ re.IGNORECASE,
468
+ )
469
+
470
+ # Explicit percentage claim (excludes confidence/interval level descriptors like "95% CI").
471
+ _PCT_CLAIM_RE = re.compile(
472
+ r"(?<![A-Za-z0-9_.~≈<>≤≥±/])"
473
+ r"(?P<num>\d+(?:,\d{3})*(?:\.\d+)?)\s*%"
474
+ r"(?!\s*(?:CI\b|confidence\b|credible\b|prediction\b|interval\b|quantile\b|percentile\b|IQR\b))",
475
+ re.IGNORECASE,
476
+ )
477
+
478
+ # Explicit fold/ratio claim ("4x", "2.3×") with value > 1.2 (excludes "10×10", "GPT-4x", "v2x").
479
+ _FOLD_CLAIM_RE = re.compile(
480
+ r"(?<![A-Za-z0-9_.~≈<>≤≥±/])"
481
+ r"(?<![A-Za-z]-)"
482
+ r"(?P<num>\d+(?:,\d{3})*(?:\.\d+)?)\s*[x\N{MULTIPLICATION SIGN}]"
483
+ r"(?![A-Za-z0-9_])",
484
+ re.IGNORECASE,
485
+ )
486
+
487
+ _SUP_TRANS = str.maketrans("⁰¹²³⁴⁵⁶⁷⁸⁹⁻⁺", "0123456789-+")
488
+ _FACT_SCI_RE = re.compile(
489
+ r"[\-\N{MINUS SIGN}+]?(\d+(?:,\d{3})*(?:\.\d+)?)\s*\N{MULTIPLICATION SIGN}\s*10([⁻⁺]?[⁰¹²³⁴⁵⁶⁷⁸⁹]+)"
490
+ )
491
+ _FACT_NUM_RE = re.compile(
492
+ r"(?<![A-Za-z_])[\-\N{MINUS SIGN}+]?(\d+(?:,\d{3})*(?:\.\d+)?)(?:[eE]([+\-]?\d+))?"
493
+ )
494
+
495
+
496
+ def _parse_fact_numbers(facts: Sequence[str]) -> list[float]:
497
+ out: list[float] = []
498
+ for text in facts:
499
+ cleaned = text
500
+ for m in _FACT_SCI_RE.finditer(text):
501
+ try:
502
+ mant = float(m.group(1).replace(",", ""))
503
+ exp = int(m.group(2).translate(_SUP_TRANS))
504
+ val = mant * (10.0**exp)
505
+ if math.isfinite(val):
506
+ out.append(abs(val))
507
+ except ValueError:
508
+ pass
509
+ cleaned = _FACT_SCI_RE.sub(" ", cleaned)
510
+ for m in _FACT_NUM_RE.finditer(cleaned):
511
+ try:
512
+ num_str = m.group(1).replace(",", "")
513
+ if m.group(2):
514
+ num_str = f"{num_str}e{m.group(2)}"
515
+ val = float(num_str)
516
+ if math.isfinite(val):
517
+ out.append(abs(val))
518
+ except ValueError:
519
+ pass
520
+ return out
521
+
522
+
523
+ def _dedup_sample(values: Sequence[float], limit: int = 80) -> list[float]:
524
+ """Deduplicate finite numbers and downsample evenly if very large."""
525
+ uniq = sorted({round(v, 10) for v in values if math.isfinite(v)})
526
+ if len(uniq) <= limit:
527
+ return uniq
528
+ # Always preserve extremes + evenly spaced quantiles
529
+ idxs = [round(i * (len(uniq) - 1) / (limit - 1)) for i in range(limit)]
530
+ return [uniq[i] for i in dict.fromkeys(idxs)]
531
+
532
+
533
+ def _extract_numeric_seq(obj: Any) -> list[float]:
534
+ if isinstance(obj, Sequence) and not isinstance(obj, (str, bytes)):
535
+ return [float(v) for v in obj if _is_finite_number(v)]
536
+ return []
537
+
538
+
539
+ def _stats_summary(vals: Sequence[float]) -> list[float]:
540
+ if not vals:
541
+ return []
542
+ s = sorted(vals)
543
+ n = len(s)
544
+ mid = s[n // 2] if n % 2 else 0.5 * (s[n // 2 - 1] + s[n // 2])
545
+ mean = sum(s) / n
546
+ out = [s[0], s[-1], mid, mean]
547
+ if n >= 4:
548
+ out.extend([s[n // 4], s[(3 * n) // 4]])
549
+ return out
550
+
551
+
552
+ def _collect_panel_groups(
553
+ panel: Any,
554
+ ) -> tuple[list[float], list[list[float]], list[list[float]], list[float]]:
555
+ """Return ``(direct_values, metric_groups, ratio_only_groups, share_candidates)``.
556
+
557
+ - ``direct_values``: all individual finite magnitudes from spec + parsed facts.
558
+ - ``metric_groups``: same-unit numeric groups from panel data (for pairwise diffs,
559
+ percentage changes, sums, and ratios).
560
+ - ``ratio_only_groups``: auxiliary numeric sets (parsed fact numbers such as fitted
561
+ slopes, and numeric x axes) used for fold/ratio matching without conflating mixed
562
+ units into bogus percentage-change pairs.
563
+ - ``share_candidates``: explicit percentage shares (0..100) for share/part-to-whole
564
+ panels and reference-threshold splits.
565
+ """
566
+ kind = str(_pget(panel, "kind", "") or "")
567
+ spec = _pspec(panel)
568
+ direct: list[float] = []
569
+ groups: list[list[float]] = []
570
+ ratio_groups: list[list[float]] = []
571
+ shares: list[float] = []
572
+
573
+ fact_nums = _parse_fact_numbers(_pfacts(panel))
574
+ direct.extend(fact_nums)
575
+ if fact_nums:
576
+ ratio_groups.append(_dedup_sample(fact_nums, limit=60))
577
+
578
+ # Reference value if present
579
+ ref = spec.get("reference")
580
+ ref_val: float | None = None
581
+ if _is_finite_number(ref):
582
+ ref_val = float(ref)
583
+ direct.append(abs(ref_val))
584
+ elif (
585
+ isinstance(ref, Sequence)
586
+ and not isinstance(ref, (str, bytes))
587
+ and ref
588
+ and _is_finite_number(ref[0])
589
+ ):
590
+ ref_val = float(ref[0])
591
+ direct.append(abs(ref_val))
592
+
593
+ if kind == "compare":
594
+ vals = spec.get("values")
595
+ boost = spec.get("boost")
596
+ if isinstance(vals, Mapping):
597
+ # Single-series or grouped compare
598
+ flat: list[float] = []
599
+ for k, v in vals.items():
600
+ if _is_finite_number(v):
601
+ fv = float(v)
602
+ flat.append(fv)
603
+ direct.append(abs(fv))
604
+ if isinstance(boost, Mapping) and _is_finite_number(boost.get(k)):
605
+ bv = float(boost[k])
606
+ direct.append(abs(bv))
607
+ direct.append(abs(fv + bv))
608
+ flat.append(fv + bv)
609
+ elif isinstance(v, Mapping):
610
+ sub = [float(sv) for sv in v.values() if _is_finite_number(sv)]
611
+ if sub:
612
+ groups.append(sub)
613
+ flat.extend(sub)
614
+ direct.extend(abs(sv) for sv in sub)
615
+ if flat:
616
+ groups.append(flat)
617
+ # Also collect error bounds
618
+ err = spec.get("error")
619
+ if isinstance(err, Mapping):
620
+ for ev in err.values():
621
+ if _is_finite_number(ev):
622
+ direct.append(abs(float(ev)))
623
+ elif isinstance(ev, Sequence) and not isinstance(ev, (str, bytes)):
624
+ direct.extend(abs(float(x)) for x in ev if _is_finite_number(x))
625
+
626
+ elif kind == "share":
627
+ parts = spec.get("parts")
628
+ if isinstance(parts, Mapping):
629
+ pvals = [float(v) for v in parts.values() if _is_finite_number(v) and float(v) >= 0]
630
+ if pvals:
631
+ total = sum(pvals)
632
+ direct.extend(pvals)
633
+ direct.append(total)
634
+ groups.append(pvals)
635
+ if total > 0:
636
+ for v in pvals:
637
+ shares.append(100.0 * v / total)
638
+ desc = sorted(pvals, reverse=True)
639
+ running = 0.0
640
+ for v in desc:
641
+ running += v
642
+ shares.append(100.0 * running / total)
643
+ hl = spec.get("highlight")
644
+ hl_list = [hl] if isinstance(hl, str) else (list(hl) if isinstance(hl, Sequence) else [])
645
+ hl_sum = sum(
646
+ float(parts[k])
647
+ for k in hl_list
648
+ if k in parts and _is_finite_number(parts[k])
649
+ )
650
+ if hl_sum > 0:
651
+ shares.append(100.0 * hl_sum / total)
652
+
653
+ elif kind == "change":
654
+ before = spec.get("before")
655
+ after = spec.get("after")
656
+ if isinstance(before, Mapping) and isinstance(after, Mapping):
657
+ all_v: list[float] = []
658
+ for k in before:
659
+ bv, av = before.get(k), after.get(k)
660
+ if _is_finite_number(bv) and _is_finite_number(av):
661
+ fb, fa = float(bv), float(av)
662
+ groups.append([fb, fa])
663
+ all_v.extend([fb, fa])
664
+ direct.extend([abs(fb), abs(fa), abs(fa - fb)])
665
+ if all_v:
666
+ groups.append(all_v)
667
+
668
+ elif kind == "trend":
669
+ series = spec.get("series")
670
+ all_ends: list[float] = []
671
+ if isinstance(series, Mapping):
672
+ for seq in series.values():
673
+ nums = _extract_numeric_seq(seq)
674
+ if nums:
675
+ stats = _stats_summary(nums)
676
+ sample = _dedup_sample([*nums, *stats], limit=40)
677
+ groups.append(sample)
678
+ direct.extend(abs(v) for v in sample)
679
+ all_ends.extend([nums[0], nums[-1]])
680
+ points = spec.get("points")
681
+ if isinstance(points, Mapping):
682
+ for x_groups in points.values():
683
+ if isinstance(x_groups, Sequence) and not isinstance(x_groups, (str, bytes)):
684
+ means: list[float] = []
685
+ for bucket in x_groups:
686
+ bnums = _extract_numeric_seq(bucket)
687
+ if bnums:
688
+ means.append(sum(bnums) / len(bnums))
689
+ if means:
690
+ groups.append(means)
691
+ direct.extend(abs(v) for v in means)
692
+ all_ends.extend([means[0], means[-1]])
693
+ if all_ends:
694
+ groups.append(all_ends)
695
+ xs = _extract_numeric_seq(spec.get("x"))
696
+ if xs:
697
+ x_sample = _dedup_sample(xs, limit=30)
698
+ direct.extend(abs(v) for v in x_sample)
699
+ ratio_groups.append(x_sample)
700
+ band = spec.get("band")
701
+ if isinstance(band, Mapping):
702
+ for bv in band.values():
703
+ if _is_finite_number(bv):
704
+ direct.append(abs(float(bv)))
705
+ elif isinstance(bv, Sequence) and not isinstance(bv, (str, bytes)):
706
+ for item in bv:
707
+ if _is_finite_number(item):
708
+ direct.append(abs(float(item)))
709
+ else:
710
+ direct.extend(abs(v) for v in _extract_numeric_seq(item))
711
+
712
+ elif kind == "distribution":
713
+ grp_map = spec.get("groups")
714
+ if isinstance(grp_map, Mapping):
715
+ centers: list[float] = []
716
+ for seq in grp_map.values():
717
+ nums = _extract_numeric_seq(seq)
718
+ if nums:
719
+ stats = _stats_summary(nums)
720
+ direct.extend(abs(v) for v in stats)
721
+ centers.extend(stats)
722
+ groups.append(_dedup_sample([*nums, *stats], limit=40))
723
+ if ref_val is not None:
724
+ above_pct = 100.0 * sum(1 for v in nums if v > ref_val) / len(nums)
725
+ below_pct = 100.0 * sum(1 for v in nums if v < ref_val) / len(nums)
726
+ shares.extend([above_pct, below_pct])
727
+ if centers:
728
+ groups.append(centers)
729
+
730
+ elif kind == "relate":
731
+ xs = _extract_numeric_seq(spec.get("x"))
732
+ ys = _extract_numeric_seq(spec.get("y"))
733
+ for arr in (xs, ys):
734
+ if arr:
735
+ sample = _dedup_sample([*arr, *_stats_summary(arr)], limit=45)
736
+ groups.append(sample)
737
+ direct.extend(abs(v) for v in sample)
738
+
739
+ elif kind == "matrix":
740
+ mat = spec.get("values")
741
+ if isinstance(mat, Sequence) and not isinstance(mat, (str, bytes)):
742
+ flat_m: list[float] = []
743
+ for row in mat:
744
+ rnums = _extract_numeric_seq(row)
745
+ if rnums:
746
+ flat_m.extend(rnums)
747
+ direct.append(abs(sum(rnums) / len(rnums)))
748
+ if flat_m:
749
+ sample = _dedup_sample(flat_m, limit=50)
750
+ groups.append(sample)
751
+ direct.extend(abs(v) for v in sample)
752
+
753
+ elif kind == "table":
754
+ rows = spec.get("rows")
755
+ col_buckets: dict[str, list[float]] = {}
756
+ if isinstance(rows, Sequence) and not isinstance(rows, (str, bytes)):
757
+ for row in rows:
758
+ if isinstance(row, Mapping):
759
+ for ck, cv in row.items():
760
+ if _is_finite_number(cv):
761
+ col_buckets.setdefault(str(ck), []).append(float(cv))
762
+ elif isinstance(row, Sequence) and not isinstance(row, (str, bytes)):
763
+ for idx, cv in enumerate(row):
764
+ if _is_finite_number(cv):
765
+ col_buckets.setdefault(str(idx), []).append(float(cv))
766
+ elif isinstance(rows, Mapping):
767
+ for ck, seq in rows.items():
768
+ nums = _extract_numeric_seq(seq)
769
+ if nums:
770
+ col_buckets[str(ck)] = nums
771
+ for col_nums in col_buckets.values():
772
+ groups.append(col_nums)
773
+ direct.extend(abs(v) for v in col_nums)
774
+
775
+ elif kind == "waterfall":
776
+ steps = spec.get("steps")
777
+ if isinstance(steps, Mapping):
778
+ s_val = 0.0
779
+ start_raw = spec.get("start")
780
+ if _is_finite_number(start_raw):
781
+ s_val = float(start_raw)
782
+ direct.append(abs(s_val))
783
+ elif (
784
+ isinstance(start_raw, Sequence)
785
+ and not isinstance(start_raw, (str, bytes))
786
+ and len(start_raw) == 2
787
+ and _is_finite_number(start_raw[1])
788
+ ):
789
+ s_val = float(start_raw[1])
790
+ direct.append(abs(s_val))
791
+ deltas = [float(v) for v in steps.values() if _is_finite_number(v)]
792
+ if deltas:
793
+ running = s_val
794
+ levels = [s_val] if start_raw is not None else [0.0]
795
+ for d in deltas:
796
+ running += d
797
+ levels.append(running)
798
+ direct.append(abs(d))
799
+ direct.append(abs(running))
800
+ net = sum(deltas)
801
+ direct.extend([abs(net), abs(running)])
802
+ groups.append([abs(d) for d in deltas])
803
+ groups.append(levels)
804
+ pos_sum = sum(d for d in deltas if d > 0)
805
+ neg_sum = sum(-d for d in deltas if d < 0)
806
+ abs_sum = sum(abs(d) for d in deltas)
807
+ for denom in (abs(net), pos_sum, neg_sum, abs_sum, abs(s_val)):
808
+ if denom > 0:
809
+ for d in deltas:
810
+ shares.append(100.0 * abs(d) / denom)
811
+ shares.append(100.0 * abs(net) / denom)
812
+
813
+ elif kind == "timeline":
814
+ spans = spec.get("spans")
815
+ if isinstance(spans, Sequence) and not isinstance(spans, (str, bytes)):
816
+ starts: list[float] = []
817
+ ends: list[float] = []
818
+ durs: list[float] = []
819
+ by_group: dict[str, float] = {}
820
+ for item in spans:
821
+ if (
822
+ isinstance(item, Sequence)
823
+ and not isinstance(item, (str, bytes))
824
+ and len(item) >= 3
825
+ and _is_finite_number(item[1])
826
+ and _is_finite_number(item[2])
827
+ ):
828
+ sv, ev = float(item[1]), float(item[2])
829
+ dv = max(0.0, ev - sv)
830
+ starts.append(sv)
831
+ ends.append(ev)
832
+ durs.append(dv)
833
+ direct.extend([abs(sv), abs(ev), dv])
834
+ if len(item) >= 4 and item[3] is not None:
835
+ gk = str(item[3])
836
+ by_group[gk] = by_group.get(gk, 0.0) + dv
837
+ if durs:
838
+ wall = max(ends) - min(starts)
839
+ total_w = sum(durs)
840
+ direct.extend([wall, total_w, *by_group.values()])
841
+ groups.append([*durs, wall, total_w])
842
+ if by_group:
843
+ groups.append(list(by_group.values()))
844
+ for denom in (wall, total_w):
845
+ if denom > 0:
846
+ for d in durs:
847
+ shares.append(100.0 * d / denom)
848
+ for gd in by_group.values():
849
+ shares.append(100.0 * gd / denom)
850
+
851
+ elif kind == "flow":
852
+ stages = spec.get("stages")
853
+ if isinstance(stages, Sequence) and not isinstance(stages, (str, bytes)):
854
+ fvals: list[float] = []
855
+ for st in stages:
856
+ if (
857
+ isinstance(st, Sequence)
858
+ and not isinstance(st, (str, bytes))
859
+ and len(st) >= 2
860
+ and _is_finite_number(st[1])
861
+ ):
862
+ fvals.append(float(st[1]))
863
+ if fvals:
864
+ direct.extend(abs(v) for v in fvals)
865
+ groups.append(fvals)
866
+ start_v = fvals[0]
867
+ if start_v > 0:
868
+ for v in fvals:
869
+ shares.append(100.0 * v / start_v)
870
+ shares.append(100.0 * abs(start_v - v) / start_v)
871
+ for idx_s in range(1, len(fvals)):
872
+ prev_v = fvals[idx_s - 1]
873
+ drop_v = abs(prev_v - fvals[idx_s])
874
+ direct.append(drop_v)
875
+ if prev_v > 0:
876
+ shares.append(100.0 * drop_v / prev_v)
877
+ shares.append(100.0 * fvals[idx_s] / prev_v)
878
+
879
+ return direct, groups, ratio_groups, shares
880
+
881
+
882
+ def _approx_match(claim: float, candidate: float) -> bool:
883
+ if not math.isfinite(candidate) or candidate < 0:
884
+ return False
885
+ return abs(claim - candidate) <= 1.0 or (
886
+ candidate > 0 and abs(claim - candidate) / candidate <= 0.15
887
+ )
888
+
889
+
890
+ def _matches_any_derivation(
891
+ claim: float,
892
+ *,
893
+ claim_kind: str,
894
+ takeaway: str,
895
+ all_direct: Sequence[float],
896
+ all_groups: Sequence[Sequence[float]],
897
+ all_ratio_groups: Sequence[Sequence[float]],
898
+ all_shares: Sequence[float],
899
+ compare_share_groups: Sequence[Sequence[float]],
900
+ ) -> bool:
901
+ # 1. Direct values + 100x / 0.01x / 1000x / 0.001x scaled values
902
+ for v in all_direct:
903
+ if _approx_match(claim, v):
904
+ return True
905
+ for scale in (100.0, 0.01, 1000.0, 0.001):
906
+ if _approx_match(claim, v * scale):
907
+ return True
908
+
909
+ # 2. Explicit share candidates (from share panels & distribution reference splits)
910
+ if claim_kind == "percent":
911
+ for s in all_shares:
912
+ if _approx_match(claim, s):
913
+ return True
914
+ # Allow a/total on compare panels with >= 3 positive values when not a change claim
915
+ if not _CHANGE_CLAIM_RE.search(takeaway):
916
+ for grp in compare_share_groups:
917
+ pos = [v for v in grp if v > 0]
918
+ if len(pos) >= 3:
919
+ total = sum(pos)
920
+ if total > 0:
921
+ for v in pos:
922
+ if _approx_match(claim, 100.0 * v / total):
923
+ return True
924
+
925
+ # 3. Same-unit group sums, pairwise differences, percentage changes, and ratios
926
+ for grp in all_groups:
927
+ nums = list(grp)
928
+ if not nums:
929
+ continue
930
+ grp_sum = abs(sum(nums))
931
+ if _approx_match(claim, grp_sum):
932
+ return True
933
+ if len(nums) < 2:
934
+ continue
935
+ pos = [abs(v) for v in nums if abs(v) > 0]
936
+ if len(pos) >= 2 and _approx_match(claim, max(pos) / min(pos)):
937
+ return True
938
+ for i in range(len(nums)):
939
+ a = nums[i]
940
+ for j in range(i + 1, len(nums)):
941
+ b = nums[j]
942
+ diff = abs(a - b)
943
+ if _approx_match(claim, diff):
944
+ return True
945
+ if claim_kind == "percent":
946
+ # Fraction-to-percent point delta (e.g. 0.08 -> 8%)
947
+ if diff <= 1.0 and _approx_match(claim, diff * 100.0):
948
+ return True
949
+ # Percentage change relative to either endpoint
950
+ if abs(b) > 0 and _approx_match(claim, 100.0 * diff / abs(b)):
951
+ return True
952
+ if abs(a) > 0 and _approx_match(claim, 100.0 * diff / abs(a)):
953
+ return True
954
+ else:
955
+ aa, ab = abs(a), abs(b)
956
+ if aa > 0 and ab > 0:
957
+ ratio = max(aa, ab) / min(aa, ab)
958
+ if _approx_match(claim, ratio):
959
+ return True
960
+
961
+ # 4. Auxiliary ratio-only groups (e.g. fitted slopes parsed from facts, log-x doses)
962
+ if claim_kind == "fold":
963
+ for grp in all_ratio_groups:
964
+ pos = [abs(v) for v in grp if abs(v) > 0]
965
+ if len(pos) < 2:
966
+ continue
967
+ if _approx_match(claim, max(pos) / min(pos)):
968
+ return True
969
+ for i in range(len(pos)):
970
+ for j in range(i + 1, len(pos)):
971
+ ratio = max(pos[i], pos[j]) / min(pos[i], pos[j])
972
+ if _approx_match(claim, ratio):
973
+ return True
974
+ return False
975
+
976
+
977
+ def _check_number_mismatch(
978
+ takeaway: str,
979
+ panels: Mapping[str, Any],
980
+ ) -> list[dict[str, Any]]:
981
+ if not panels:
982
+ return []
983
+ # Skip completely if any panel is custom or takeaway is hedged
984
+ if any(str(_pget(p, "kind", "")) == "custom" for p in panels.values()):
985
+ return []
986
+ if _HEDGE_RE.search(takeaway):
987
+ return []
988
+
989
+ claims: list[tuple[str, float, str]] = []
990
+ for m in _PCT_CLAIM_RE.finditer(takeaway):
991
+ val = float(m.group("num").replace(",", ""))
992
+ if math.isfinite(val):
993
+ claims.append(("percent", val, m.group(0).strip()))
994
+ for m in _FOLD_CLAIM_RE.finditer(takeaway):
995
+ val = float(m.group("num").replace(",", ""))
996
+ if math.isfinite(val) and val > 1.2:
997
+ claims.append(("fold", val, m.group(0).strip()))
998
+
999
+ if not claims:
1000
+ return []
1001
+
1002
+ all_direct: list[float] = []
1003
+ all_groups: list[list[float]] = []
1004
+ all_ratio_groups: list[list[float]] = []
1005
+ all_shares: list[float] = []
1006
+ compare_share_groups: list[list[float]] = []
1007
+
1008
+ for panel in panels.values():
1009
+ direct, groups, ratio_groups, shares = _collect_panel_groups(panel)
1010
+ all_direct.extend(direct)
1011
+ all_groups.extend(groups)
1012
+ all_ratio_groups.extend(ratio_groups)
1013
+ all_shares.extend(shares)
1014
+ if str(_pget(panel, "kind", "")) == "compare":
1015
+ vals = _pspec(panel).get("values")
1016
+ if isinstance(vals, Mapping):
1017
+ flat = [float(v) for v in vals.values() if _is_finite_number(v)]
1018
+ if flat:
1019
+ compare_share_groups.append(flat)
1020
+
1021
+ # Require actual numeric evidence in the panels before flagging anything
1022
+ if not all_direct and not all_groups:
1023
+ return []
1024
+
1025
+ # Cross-panel ratios (e.g. dose IC50 in panel a vs toxicity in panel b)
1026
+ if len(panels) > 1 and all_direct:
1027
+ all_ratio_groups.append(_dedup_sample(all_direct, limit=60))
1028
+
1029
+ mismatched: list[str] = []
1030
+ for claim_kind, val, raw in claims:
1031
+ if (
1032
+ not _matches_any_derivation(
1033
+ val,
1034
+ claim_kind=claim_kind,
1035
+ takeaway=takeaway,
1036
+ all_direct=all_direct,
1037
+ all_groups=all_groups,
1038
+ all_ratio_groups=all_ratio_groups,
1039
+ all_shares=all_shares,
1040
+ compare_share_groups=compare_share_groups,
1041
+ )
1042
+ and raw not in mismatched
1043
+ ):
1044
+ mismatched.append(raw)
1045
+
1046
+ if not mismatched:
1047
+ return []
1048
+
1049
+ listed = ", ".join(repr(m) for m in mismatched[:3])
1050
+ return [
1051
+ _advisory(
1052
+ "claim_number_mismatch",
1053
+ f"Takeaway cites {listed}, which does not match any value, difference, "
1054
+ "percentage change, share, or ratio computed from the panel data.",
1055
+ "Verify the number in the takeaway against summary['panels'][...]['facts'], "
1056
+ "or qualify approximate figures with '~' / 'about' and explain external baselines in note=.",
1057
+ panel=None,
1058
+ )
1059
+ ]
1060
+
1061
+
1062
+ def audit_epistemic(takeaway: str, panels: Mapping[str, Any]) -> list[dict[str, Any]]:
1063
+ """Run tightly scoped advisory epistemic checks on ``takeaway`` vs ``panels``.
1064
+
1065
+ Emits ``severity="warning"`` issues only (never errors, never blocks ``ship``)
1066
+ for:
1067
+ - ``claim_overstates_uncertainty``: strong certainty wording in ``takeaway``
1068
+ paired with overlapping intervals or small-n rough-estimate warnings in panel facts.
1069
+ - ``claim_number_mismatch``: explicit unhedged percentage or fold (>1.2x) claim in
1070
+ ``takeaway`` that matches no plausible derivation from the panel data or facts.
1071
+ """
1072
+ if not isinstance(takeaway, str) or not takeaway.strip() or not panels:
1073
+ return []
1074
+ issues: list[dict[str, Any]] = []
1075
+ issues.extend(_check_overstates_uncertainty(takeaway, panels))
1076
+ issues.extend(_check_number_mismatch(takeaway, panels))
1077
+ return issues
1078
+
1079
+
1080
+ __all__ = [
1081
+ "audit_epistemic",
1082
+ "build_narrative",
1083
+ ]