File size: 29,234 Bytes
356ffbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
"""Build every output of sample-stability from raw sources and the extraction sheets.

    uv run python scripts/build.py            # uses cached raw files; fetches what is missing
    uv run python scripts/build.py --offline  # fails instead of fetching

Inputs
  extraction/<PMCID>.csv                 hand-curated rows (see extraction/EXTRACTION_PROTOCOL.md)
  extraction/excluded_*.csv              papers read and excluded, with the reason
  extraction/fasting_state.csv           fasting state per source, with the supporting text
  _raw/europepmc/fulltext/<PMCID>.xml    Europe PMC full text (fetched by fetch_fulltext.py)
  _raw/europepmc/core/<PMCID>.json       Europe PMC core metadata (licence, OA flag)
  _raw/crossref/<doi>.json               Crossref work record for each DOI
  _raw/lifefrom-release-1/markers.csv    LifeFrom marker list, release 1 (join key marker_slug)

Raw files live in a sibling directory, ../_raw/ (next to this repository), and are not distributed.

Quotes from sources not licensed CC BY or CC0 are blank in the distributed sheets (licence). For those
rows the quote check cannot run; the build says how many rows it skipped. Every other check runs.

Outputs
  data/stability_findings.csv, data/summary.csv, data/sources.csv, web/sample-stability.json
"""
from __future__ import annotations

import csv
import difflib
import html
import json
import re
import sys
import time
import unicodedata
import urllib.parse
import urllib.request
from collections import defaultdict
from pathlib import Path

HERE = Path(__file__).resolve().parent
REL = HERE.parent
RAW = REL.parent / "_raw"
sys.path.insert(0, str(HERE))
import fetch_fulltext  # noqa: E402

VERSION = "1.0.0"
ACCESS_DATE = "2026-11-25"
OFFLINE = "--offline" in sys.argv
UA = "LifeFrom-Open-build/1.0 (dataset build script)"
QUOTE_LICENCES = {"cc by", "cc0"}
CPD_SOURCES = {"PMC13067896"}

# LifeFrom markers whose definition names a specimen or a fasting state. Rows for the same measurand
# in another matrix get a specimen-neutral analyte_key and keep the marker only as related_marker_slug.
#   slug: (neutral analyte_key, neutral name, matrices that match the marker, needs fasting)
MARKER_SCOPE = {
    "albumin-serum": ("albumin", "Albumin", {"serum"}, False),
    "calcium-total": ("calcium-total", "Calcium, total", {"serum"}, False),
    "chloride-serum": ("chloride", "Chloride", {"serum"}, False),
    "creatinine-serum": ("creatinine", "Creatinine", {"serum"}, False),
    "cystatin-c": ("cystatin-c", "Cystatin C", {"serum"}, False),
    "folate-serum": ("folate", "Folate (serum/plasma)", {"serum"}, False),
    "magnesium-serum": ("magnesium", "Magnesium", {"serum"}, False),
    "phosphorus-serum": ("phosphate", "Phosphate (inorganic phosphorus)", {"serum"}, False),
    "potassium-serum": ("potassium", "Potassium", {"serum"}, False),
    "serum-iron": ("iron", "Iron", {"serum"}, False),
    "sodium-serum": ("sodium", "Sodium", {"serum"}, False),
    "total-protein": ("total-protein", "Total protein", {"serum"}, False),
    "urea": ("urea", "Urea", {"serum"}, False),
    "uric-acid": ("uric-acid", "Uric acid", {"serum"}, False),
    "homocysteine": ("homocysteine", "Homocysteine", {"plasma"}, False),
    "lactate-serum": ("lactate", "Lactate", {"serum", "plasma"}, False),
    "selenium": ("selenium", "Selenium", {"serum", "plasma"}, False),
    "zinc": ("zinc", "Zinc", {"serum", "plasma"}, False),
    "glucose-fasting": ("glucose", "Glucose", {"serum", "plasma"}, True),
    "fasting-insulin": ("insulin", "Insulin", {"serum", "plasma"}, True),
}


def measured_matrix(specimen: str, condition: str) -> str:
    """The matrix actually analysed. Whole blood held before centrifugation is measured in serum or plasma."""
    if specimen in ("serum", "whole-blood-clotted", "capillary-serum"):
        return "serum"
    if specimen.startswith("plasma-") or specimen == "capillary-plasma-li-heparin":
        return "plasma"
    if specimen.startswith("whole-blood-") or specimen == "capillary-whole-blood-edta":
        return "plasma" if condition == "delayed-centrifugation" else "whole-blood"
    return specimen  # dbs, urine, other  # leukocyte cell population data (NE-SFL, LY-X, ...)

SPECIMENS = {
    "serum", "plasma-li-heparin", "plasma-edta", "plasma-citrate", "plasma-fluoride",
    "whole-blood-edta", "whole-blood-heparin", "whole-blood-clotted", "whole-blood-fluoride",
    "whole-blood-citrate", "dbs", "capillary-serum", "capillary-plasma-li-heparin",
    "capillary-whole-blood-edta", "urine", "other",
}
PROCESSING = {"uncentrifuged", "centrifuged-on-gel", "centrifuged-on-cells", "separated", "dried", "not-stated"}
CONDITIONS = {"storage", "freeze-thaw", "delayed-centrifugation"}
TEMPS = {"RT", "2-8C", "-20C", "-80C", "other"}
RESULTS = {"stable-to-max", "unstable-after", "unstable-at-first", "stated-limit"}
CRITERIA = {"pct-deviation", "desirable-bias-bv", "rcv", "total-allowable-error", "stat-significance",
            "clinical-limit", "other"}

UNIT_HOURS = {
    "min": 1 / 60, "mins": 1 / 60, "minute": 1 / 60, "minutes": 1 / 60,
    "h": 1, "hr": 1, "hrs": 1, "hour": 1, "hours": 1,
    "day": 24, "days": 24, "d": 24,
    "week": 168, "weeks": 168, "wk": 168,
    "month": 730.5, "months": 730.5,  # 30.4375 days
    "year": 8766, "years": 8766,  # 365.25 days
}


def parse_duration(s: str) -> tuple[str, float | None]:
    """Return (kind, value): kind 'hours' or 'cycles'. Raises ValueError if it cannot parse."""
    s = s.strip()
    m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*(cycles?)", s)
    if m:
        return "cycles", float(m.group(1))
    m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([A-Za-z]+)", s)
    if not m or m.group(2).lower() not in UNIT_HOURS:
        raise ValueError(f"cannot parse duration {s!r}")
    return "hours", round(float(m.group(1)) * UNIT_HOURS[m.group(2).lower()], 4)


def norm(s: str) -> str:
    s = unicodedata.normalize("NFKC", html.unescape(s))
    s = s.replace("−", "-").replace("–", "-").replace("—", "-")
    return " ".join(s.split()).lower()


def get_json(url: str, cache: Path) -> dict | None:
    if cache.exists():
        return json.loads(cache.read_text())
    if OFFLINE:
        raise SystemExit(f"offline and not cached: {url}")
    req = urllib.request.Request(url, headers={"User-Agent": UA})
    for attempt in range(3):
        try:
            with urllib.request.urlopen(req, timeout=60) as r:
                data = r.read()
            cache.parent.mkdir(parents=True, exist_ok=True)
            cache.write_bytes(data)
            return json.loads(data)
        except urllib.error.HTTPError as e:
            if e.code == 404:
                cache.parent.mkdir(parents=True, exist_ok=True)
                cache.write_text(json.dumps({"status": "not-found", "url": url}))
                return json.loads(cache.read_text())
            time.sleep(2 + attempt * 3)
        except Exception:
            time.sleep(2 + attempt * 3)
    raise SystemExit(f"could not fetch {url}")


def crossref(doi: str) -> dict:
    fn = RAW / "crossref" / (urllib.parse.quote(doi.lower(), safe="") + ".json")
    return get_json("https://api.crossref.org/works/" + urllib.parse.quote(doi), fn)


def epmc_core(pmcid: str) -> dict:
    fn = RAW / "europepmc" / "core" / f"{pmcid}.json"
    url = ("https://www.ebi.ac.uk/europepmc/webservices/rest/search?" +
           urllib.parse.urlencode({"query": f"PMCID:{pmcid}", "format": "json", "resultType": "core"}))
    d = get_json(url, fn)
    res = d.get("resultList", {}).get("result", [])
    return res[0] if res else {}


def crossref_title(msg: dict) -> str:
    t = " ".join(msg.get("title", []))
    sub = " ".join(msg.get("subtitle", []))
    if sub and norm(sub) not in norm(t):
        t = f"{t}: {sub}"
    return html.unescape(re.sub(r"<[^>]+>", "", t))


def title_match(msg: dict, other: str) -> float:
    """Similarity of the Crossref title (with subtitle) and another title, ignoring punctuation."""
    a = re.sub(r"[^a-z0-9 ]", "", norm(crossref_title(msg)))
    b = re.sub(r"[^a-z0-9 ]", "", norm(html.unescape(re.sub(r"<[^>]+>", "", other))))
    a, b = " ".join(a.split()), " ".join(b.split())
    if len(a) > 30 and len(b) > 30 and (a in b or b in a):
        return 1.0  # one title is the other plus a subtitle or a publisher note
    return difflib.SequenceMatcher(None, a, b).ratio()


def xml_authors(pmcid: str) -> list[str]:
    """Author surnames in article order, from the article's own JATS XML (front matter)."""
    import xml.etree.ElementTree as ET
    root = ET.parse(fetch_fulltext.XML / f"{pmcid}.xml").getroot()
    meta = root.find("front/article-meta")
    out = []
    for cg in meta.iter("contrib-group"):
        for c in cg.findall("contrib"):
            if c.get("contrib-type", "author") != "author":
                continue
            sn = c.find("name/surname")
            if sn is None:
                sn = c.find("collab")
            if sn is not None:
                out.append(" ".join("".join(sn.itertext()).split()))
    return out


def crossref_first_author(msg: dict) -> str:
    au = msg.get("author", [])
    first = [a for a in au if a.get("sequence") == "first"] or au
    return first[0].get("family", first[0].get("name", "")) if first else ""


def licence_of(pmcid: str) -> str:
    return (epmc_core(pmcid).get("license") or "").strip().lower()


def quote_allowed(pmcid: str) -> bool:
    return licence_of(pmcid) in QUOTE_LICENCES


def slugify(s: str) -> str:
    s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode()
    return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")


def fmt_hours(h: float) -> str:
    if h == 0:
        return "0 h"
    for unit, size in (("years", 8766), ("months", 730.5), ("weeks", 168), ("days", 24), ("h", 1)):
        if h >= size and abs(h / size - round(h / size)) < 1e-6:
            v = round(h / size)
            u = unit if v != 1 or unit == "h" else unit[:-1]
            return f"{v} {u}"
    return f"{h:g} h"


def load_markers() -> dict:
    return {r["marker_slug"]: r for r in csv.DictReader(open(RAW / "lifefrom-release-1" / "markers.csv", encoding="utf-8"))}


WITHHELD_SKIPPED: list[str] = []


def validate_sheet(p: Path, markers: dict, header: list[str]) -> tuple[list[dict], list[str]]:
    """Validate one extraction sheet against its full text. Returns (rows, errors)."""
    errors: list[str] = []
    rows: list[dict] = []
    pmcid = p.stem
    xml = fetch_fulltext.XML / f"{pmcid}.xml"
    if not xml.exists():
        if OFFLINE:
            raise SystemExit(f"missing {xml}")
        fetch_fulltext.fetch(pmcid)
    txt = fetch_fulltext.render(xml)
    (fetch_fulltext.TXT / f"{pmcid}.txt").write_text(txt)
    text = norm(txt)
    rd = csv.DictReader(open(p, encoding="utf-8"))
    if rd.fieldnames != header:
        return [], [f"{p.name}: header differs from HEADER.csv"]
    for i, r in enumerate(rd, start=2):
        r = {k: (v or "").strip() for k, v in r.items()}
        where = f"{p.name}:{i}"
        if r["pmcid"] != pmcid:
            errors.append(f"{where}: pmcid {r['pmcid']} != file name")
        for col, allowed in (("specimen", SPECIMENS), ("processing", PROCESSING), ("condition", CONDITIONS),
                             ("temp_category", TEMPS), ("result", RESULTS), ("criterion_type", CRITERIA)):
            if r[col] not in allowed:
                errors.append(f"{where}: {col}={r[col]!r} not allowed")
        if r["marker_slug"] and r["marker_slug"] not in markers:
            errors.append(f"{where}: unknown marker_slug {r['marker_slug']!r}")
        if not r["location"]:
            errors.append(f"{where}: no location")
        q = norm(r["evidence_quote"])
        if not q and not quote_allowed(pmcid):
            WITHHELD_SKIPPED.append(where)  # quote withheld (licence): nothing to check
        elif len(q) < 8 or q not in text:
            errors.append(f"{where}: evidence_quote not found in full text: {r['evidence_quote'][:80]!r}")
        try:
            kind, stable = parse_duration(r["stable_for"])
            kind2, mx = parse_duration(r["max_tested"])
            un = parse_duration(r["unstable_at"]) if r["unstable_at"] else (kind, None)
        except ValueError as e:
            errors.append(f"{where}: {e}")
            continue
        if r["condition"] == "freeze-thaw":
            if kind != "cycles" or kind2 != "cycles" or un[0] != "cycles":
                errors.append(f"{where}: freeze-thaw durations must be in cycles")
        elif "cycles" in (kind, kind2, un[0]):
            errors.append(f"{where}: cycles used outside freeze-thaw")
        if r["result"] == "stable-to-max" and (r["unstable_at"] or stable != mx):
            errors.append(f"{where}: stable-to-max needs stable_for == max_tested and no unstable_at")
        if r["result"] == "stated-limit" and r["unstable_at"]:
            errors.append(f"{where}: stated-limit rows have no unstable_at")
        if r["result"] in ("unstable-after", "unstable-at-first") and not r["unstable_at"]:
            errors.append(f"{where}: {r['result']} needs unstable_at")
        if r["result"] == "unstable-at-first" and stable != 0:
            errors.append(f"{where}: unstable-at-first needs stable_for 0")
        if r["result"] == "unstable-after" and stable == 0:
            errors.append(f"{where}: stable_for 0 means unstable-at-first")
        if un[1] is not None and un[1] <= stable:
            errors.append(f"{where}: unstable_at must be later than stable_for")
        if un[1] is not None and un[1] > mx:
            errors.append(f"{where}: unstable_at beyond max_tested")
        if stable > mx:
            errors.append(f"{where}: stable_for beyond max_tested")
        if r["n"] and not r["n"].isdigit():
            errors.append(f"{where}: n must be an integer")
        r["_kind"], r["_stable"], r["_unstable"], r["_max"] = kind, stable, un[1], mx
        rows.append(r)
    return rows, errors


def main() -> None:
    markers = load_markers()
    header = next(csv.reader(open(REL / "extraction" / "HEADER.csv")))
    sheets = sorted(p for p in (REL / "extraction").glob("PMC*.csv"))
    errors: list[str] = []
    rows: list[dict] = []
    for p in sheets:
        rs, es = validate_sheet(p, markers, header)
        rows += rs
        errors += es
    if errors:
        print("\n".join(errors[:200]), file=sys.stderr)
        raise SystemExit(f"{len(errors)} extraction errors")
    if WITHHELD_SKIPPED:
        print(f"quote check skipped for {len(WITHHELD_SKIPPED)} rows whose quotes are withheld "
              f"(source licence not CC BY or CC0; quotes are not distributed). All other checks ran.")

    # ---- sources -------------------------------------------------------------------------
    excluded = []
    for p in sorted((REL / "extraction").glob("excluded*.csv")):
        excluded += list(csv.DictReader(open(p, encoding="utf-8")))
    sources = {}
    for pmcid in sorted({r["pmcid"] for r in rows}):
        core = epmc_core(pmcid)
        doi = (core.get("doi") or "").lower()
        if not doi:
            raise SystemExit(f"{pmcid}: no DOI in Europe PMC record")
        cr = crossref(doi)
        msg = cr.get("message", {})
        ep_title = html.unescape(re.sub(r"<[^>]+>", "", core.get("title", "")))
        sim = title_match(msg, ep_title)
        cr_title = crossref_title(msg)
        xml_lic = ""
        m = re.search(r"^LICENSE: (\S*)", (fetch_fulltext.TXT / f"{pmcid}.txt").read_text(), re.M)
        if m:
            xml_lic = m.group(1)
        lic = core.get("license", "") or ""
        if not lic and msg.get("license"):
            lic = msg["license"][0].get("URL", "")
        authors = xml_authors(pmcid)
        if not authors:
            raise SystemExit(f"{pmcid}: no authors in article XML")
        first = authors[0]
        cr_first = crossref_first_author(msg)
        epmc_first = (core.get("authorString", "").split(",")[0]).rsplit(" ", 1)[0].strip()
        if norm(cr_first) == norm(first):
            author_check = "matches Crossref"
        elif set(norm(first).split()) <= set(norm(cr_first).split()) or set(norm(cr_first).split()) <= set(norm(first).split()):
            author_check = f"matches Crossref (Crossref surname form: {cr_first})"
        elif norm(epmc_first) == norm(first) and norm(first) in {norm(a.get("family", "")) for a in msg.get("author", [])}:
            author_check = (f"Crossref lists {cr_first} first; article XML and Europe PMC list {first} first "
                            f"(Crossref deposit order differs from the article)")
        else:
            raise SystemExit(f"{pmcid}: first author {first!r} not confirmed (Crossref {cr_first!r}, Europe PMC {epmc_first!r})")
        year = core.get("pubYear") or str((msg.get("issued", {}).get("date-parts") or [[""]])[0][0])
        journal = (core.get("journalInfo", {}).get("journal", {}).get("medlineAbbreviation")
                   or (msg.get("container-title") or [""])[0])
        label = f"{first}{' et al.' if len(authors) > 1 else ''} {year}, {journal}"
        sources[pmcid] = {
            "source_id": pmcid,
            "doi": doi,
            "title": ep_title or cr_title,
            "first_author": first,
            "first_author_check": author_check,
            "year": year,
            "journal": journal,
            "volume": msg.get("volume", ""),
            "pages": msg.get("page", ""),
            "pmid": core.get("pmid", ""),
            "pmcid": pmcid,
            "license": lic,
            "license_url_in_xml": xml_lic,
            "open_access": "yes" if core.get("isOpenAccess") == "Y" else ("unclear" if not core else "no"),
            "full_text_read": "yes",
            "full_text_source": f"https://www.ebi.ac.uk/europepmc/webservices/rest/{pmcid}/fullTextXML",
            "doi_resolves_crossref": "yes" if msg else "no",
            "crossref_title_match": f"{sim:.2f}",
            "access_date": ACCESS_DATE,
            "source_label": label,
            "n_findings": sum(1 for r in rows if r["pmcid"] == pmcid),
        }
        if not msg or sim < 0.85:
            raise SystemExit(f"{pmcid}: DOI {doi} failed Crossref title check (sim {sim:.2f}): {cr_title!r} vs {ep_title!r}")

    # ---- findings ------------------------------------------------------------------------
    out_cols = ["finding_id", "analyte_key", "analyte_name", "analyte_reported", "marker_slug", "marker_name",
                "related_marker_slug", "marker_match", "measured_matrix", "specimen", "tube",
                "processing", "condition", "temp_category", "temp_reported", "stable_for", "stable_hours",
                "stable_cycles", "unstable_at", "unstable_at_hours", "unstable_at_cycles", "max_tested",
                "max_tested_hours", "max_tested_cycles", "result", "criterion", "criterion_type", "n", "population",
                "method_or_analyzer", "source_id", "doi", "source_label", "location", "full_text_read",
                "evidence_quote", "quote_status", "notes", "access_date"]
    keys = {r["analyte_reported"]: r for r in csv.DictReader(open(REL / "extraction" / "analyte_keys.csv", encoding="utf-8"))}

    fasting = {}
    for fr in csv.DictReader(open(REL / "extraction" / "fasting_state.csv", encoding="utf-8")):
        if not fr["evidence_quote"] and not quote_allowed(fr["pmcid"]):
            print(f"fasting_state.csv: quote for {fr['pmcid']} withheld (source licence); quote check skipped")
            fasting[fr["pmcid"]] = fr["fasting_state"]
            continue
        txt = norm(fetch_fulltext.render(fetch_fulltext.XML / f"{fr['pmcid']}.xml"))
        if norm(fr["evidence_quote"]) not in txt:
            raise SystemExit(f"fasting_state.csv: quote not found for {fr['pmcid']}")
        fasting[fr["pmcid"]] = fr["fasting_state"]

    def akey(r):
        """Return (analyte_key, analyte_name, marker_slug, related_marker_slug, marker_match, matrix)."""
        matrix = measured_matrix(r["specimen"], r["condition"])
        slug = r["marker_slug"]
        if slug:
            if slug in MARKER_SCOPE:
                key, name, ok_matrix, needs_fasting = MARKER_SCOPE[slug]
                if matrix not in ok_matrix:
                    return key, name, "", slug, f"different-matrix ({matrix})", matrix
                if needs_fasting and fasting.get(r["pmcid"]) != "fasting":
                    state = fasting.get(r["pmcid"], "not stated")
                    return key, name, "", slug, f"fasting state {state}", matrix
                return key, name, slug, slug, "exact", matrix
            return slug, markers[slug]["canonical_name"], slug, slug, "exact", matrix
        k = keys.get(r["analyte_reported"])
        key, name = (k["analyte_key"], k["analyte_name"]) if k else (slugify(r["analyte_reported"]), r["analyte_reported"])
        return key, name, "", "", "none", matrix

    neutral = {v[0] for v in MARKER_SCOPE.values()}
    for r in rows:
        r["_key"], r["_name"], r["_slug"], r["_related"], r["_match"], r["_matrix"] = akey(r)
        if r["_key"] in markers and not r["_related"] and r["_key"] not in neutral:
            raise SystemExit(f"analyte_key {r['_key']} collides with a marker_slug; set marker_slug instead")
    rows.sort(key=lambda r: (r["_key"], r["specimen"], r["condition"], r["temp_category"], r["pmcid"]))
    findings = []
    for i, r in enumerate(rows, start=1):
        cyc = r["_kind"] == "cycles"
        key = r["_key"]
        f = {
            "finding_id": f"SS{i:04d}",
            "analyte_key": key,
            "analyte_name": r["_name"],
            "analyte_reported": r["analyte_reported"],
            "marker_slug": r["_slug"],
            "marker_name": markers[r["_slug"]]["canonical_name"] if r["_slug"] else "",
            "related_marker_slug": r["_related"],
            "marker_match": r["_match"],
            "measured_matrix": r["_matrix"],
            "specimen": r["specimen"], "tube": r["tube"], "processing": r["processing"],
            "condition": r["condition"], "temp_category": r["temp_category"], "temp_reported": r["temp_reported"],
            "stable_for": r["stable_for"],
            "stable_hours": "" if cyc else f"{r['_stable']:g}",
            "stable_cycles": f"{r['_stable']:g}" if cyc else "",
            "unstable_at": r["unstable_at"],
            "unstable_at_hours": "" if cyc or r["_unstable"] is None else f"{r['_unstable']:g}",
            "unstable_at_cycles": "" if not cyc or r["_unstable"] is None else f"{r['_unstable']:g}",
            "max_tested": r["max_tested"],
            "max_tested_hours": "" if cyc else f"{r['_max']:g}",
            "max_tested_cycles": f"{r['_max']:g}" if cyc else "",
            "result": r["result"], "criterion": r["criterion"], "criterion_type": r["criterion_type"],
            "n": r["n"], "population": r["population"], "method_or_analyzer": r["method_or_analyzer"],
            "source_id": r["pmcid"], "doi": sources[r["pmcid"]]["doi"],
            "source_label": sources[r["pmcid"]]["source_label"], "location": r["location"],
            "full_text_read": "yes", "evidence_quote": r["evidence_quote"],
            "quote_status": "included" if quote_allowed(r["pmcid"]) else "withheld-licence",
            "notes": r["notes"],
            "access_date": ACCESS_DATE,
        }
        findings.append(f)
    shipped = [dict(f, evidence_quote=f["evidence_quote"] if f["quote_status"] == "included" else "")
               for f in findings]
    write_csv(REL / "data" / "stability_findings.csv", out_cols, shipped)

    # ---- summary -------------------------------------------------------------------------
    groups = defaultdict(list)
    for f in findings:
        temp = f["temp_category"] if f["temp_category"] != "other" else f"other ({f['temp_reported']})"
        groups[(f["analyte_key"], f["specimen"], f["processing"], f["condition"], temp)].append(f)
    summary = []
    for (key, spec, proc, cond, temp), fs in sorted(groups.items()):
        unit = "cycles" if cond == "freeze-thaw" else "hours"
        sk, uk = ("stable_cycles", "unstable_at_cycles") if unit == "cycles" else ("stable_hours", "unstable_at_hours")
        by_study = defaultdict(list)
        for f in fs:
            by_study[f["source_id"]].append(f)
        study_stable = {s: min(float(x[sk]) for x in v) for s, v in by_study.items()}
        study_fail = {s: min((float(x[uk]) for x in v if x[uk]), default=None) for s, v in by_study.items()}
        shortest = min(study_stable.values())
        shortest_src = sorted(s for s, v in study_stable.items() if v == shortest)
        consistent = 0
        for s in by_study:
            other_fails = [v for o, v in study_fail.items() if o != s and v is not None]
            if not other_fails or study_stable[s] < min(other_fails):
                consistent += 1
        n_st = len(by_study)
        agreement = "single study" if n_st == 1 else ("all consistent" if consistent == n_st else "conflicting")
        first_fail = min((v for v in study_fail.values() if v is not None), default=None)
        summary.append({
            "analyte_key": key,
            "related_marker_slug": fs[0]["related_marker_slug"],
            "analyte_name": fs[0]["analyte_name"],
            "specimen": spec, "processing": proc, "condition": cond, "temp": temp,
            "duration_unit": unit,
            "shortest_stable": f"{shortest:g}",
            "shortest_stable_label": (f"{shortest:g} cycle{'' if shortest == 1 else 's'}" if unit == "cycles"
                                      else fmt_hours(shortest)),
            "shortest_criterion_type": ";".join(sorted({f["criterion_type"] for f in fs if float(f[sk]) == shortest})),
            "longest_stable": f"{max(study_stable.values()):g}",
            "earliest_failure": "" if first_fail is None else f"{first_fail:g}",
            "n_findings": len(fs),
            "n_studies": n_st,
            "n_studies_consistent": consistent,
            "n_studies_reporting_failure": sum(1 for v in study_fail.values() if v is not None),
            "agreement": agreement,
            "shortest_from": ";".join(shortest_src),
            "sources": ";".join(sorted(by_study)),
            "finding_ids": ";".join(f["finding_id"] for f in fs),
            "study_quality_assessed": "no",
            "caveat": ("Index of published findings, not a recommended stability limit. No study-quality "
                       "assessment (e.g. CRESS) was done. Accredited labs must use the manufacturer's IFU "
                       "or their own verification."),
        })
    write_csv(REL / "data" / "summary.csv", list(summary[0].keys()), summary)

    src_cols = list(next(iter(sources.values())).keys())
    write_csv(REL / "data" / "sources.csv", src_cols, list(sources.values()))
    if excluded:
        write_csv(REL / "data" / "excluded_sources.csv", list(excluded[0].keys()), excluded)

    # ---- web JSON ------------------------------------------------------------------------
    analytes = defaultdict(list)
    for f in findings:
        analytes[f["analyte_key"]].append(f)
    web = {"version": VERSION, "analytes": []}

    def is_cpd(key):  # Sysmex cell population data: research parameters, listed last on the web
        fs = analytes[key]
        return all(f["source_id"] in CPD_SOURCES and not f["marker_slug"] for f in fs)

    for key in sorted(analytes, key=lambda k: (is_cpd(k), k)):
        fs = analytes[key]
        web["analytes"].append({
            "slug": key,
            "marker_slug": fs[0]["related_marker_slug"] or None,
            "name": fs[0]["analyte_name"],
            "rows": [{
                "specimen": f["specimen"], "measured_matrix": f["measured_matrix"],
                "marker_match": f["marker_match"],
                "tube": f["tube"], "processing": f["processing"],
                "condition": f["condition"],
                "temp": f["temp_category"] if f["temp_category"] != "other" else f["temp_reported"],
                "stable_for": f["stable_for"],
                "stable_hours": float(f["stable_hours"]) if f["stable_hours"] else None,
                "stable_cycles": float(f["stable_cycles"]) if f["stable_cycles"] else None,
                "result": f["result"],
                "unstable_at": f["unstable_at"] or None,
                "criterion": f["criterion"], "n": int(f["n"]) if f["n"] else None,
                "doi": f["doi"], "source_label": f["source_label"], "location": f["location"],
            } for f in fs],
        })
    (REL / "web").mkdir(exist_ok=True)
    (REL / "web" / "sample-stability.json").write_text(json.dumps(web, ensure_ascii=False, separators=(",", ":")))
    print(f"analytes={len(analytes)} findings={len(findings)} sources={len(sources)} summary_rows={len(summary)}")


def write_csv(path: Path, cols: list[str], rows: list[dict]) -> None:
    path.parent.mkdir(exist_ok=True)
    with open(path, "w", newline="", encoding="utf-8") as fh:
        w = csv.DictWriter(fh, fieldnames=cols, lineterminator="\n")
        w.writeheader()
        for r in rows:
            w.writerow({c: r.get(c, "") for c in cols})


if __name__ == "__main__":
    main()