File size: 26,020 Bytes
93e3ef1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Extract MathML formulas from the PubMed Central open-access bucket.

Three stages, all resumable:

``select``   asks the Europe PMC REST search for candidate articles of
             a list of journals (by publisher group and publication
             period) whose abstracts mention mathematical vocabulary and
             whose licence field names CC BY, CC BY-SA or CC0.
``extract``  fetches each candidate from the anonymous ``pmc-oa-opendata``
             S3 bucket (metadata JSON, then JATS XML), confirms the
             licence, finds the MathML formulas, samples at most 60
             distinct formulas per article and appends them to a
             compressed store. Documents are streamed one at a time and
             never kept.
``build``    merges the store into ``pmc.jsonl`` (one row per distinct
             formula) and ``pmc.documents.jsonl`` (one line per article).

Licence rule: an article is used only if the ``license_code`` of its
metadata JSON and the Creative Commons URLs in the licence element of
its JATS agree on one of CC BY, CC BY-SA or CC0, with a stated version.

Service etiquette: about one request per second to each service, one
connection at a time, generic client name, stop on HTTP 429 or 403.

Usage:
    pmc.py select  --work DIR [--per-bucket N] [--groups g1,g2] [--max-journals N] [--windows N]
    pmc.py extract --work DIR [--max-docs-per-group N] [--groups g1,g2]
    pmc.py build   --work DIR --out DIR
"""

import argparse
import hashlib
import html
import json
import os
import re
import sys
import urllib.parse

import scholarly_common as sc

BUCKET = "https://pmc-oa-opendata.s3.amazonaws.com"
EUROPE_PMC = "https://www.ebi.ac.uk/europepmc/webservices/rest/search"
SEED = "mathconv-corpus-v1"
CAP_PER_DOCUMENT = 60

# Target number of distinct formulas per publisher group.
TARGETS = {
    "springer-nature": 25000,
    "elsevier": 20000,
    "mdpi": 15000,
    "wiley-hindawi": 15000,
    "oup-pnas-royal-society": 15000,
    "plos": 12000,
    "elife": 12000,
    "frontiers": 8000,
    "f1000research": 8000,
    "aims-press": 8000,
    "peerj": 8000,
    "other": 15000,
}

# Journals to query (Europe PMC journal names) for each group.
JOURNALS = {
    "springer-nature": [
        "Sci Rep", "Nat Commun", "BMC Bioinformatics", "Theor Biol Med Model",
        "Malar J", "Parasit Vectors", "BMC Public Health", "J Math Neurosci",
        "Commun Biol", "Commun Phys", "Light Sci Appl", "Genome Biol",
        "BMC Syst Biol", "BMC Med Res Methodol", "npj Syst Biol Appl",
        "J Cheminform", "BMC Biol", "Eur Phys J C", "Adv Differ Equ",
    ],
    "elsevier": [
        "Heliyon", "Biophys J", "Cell Rep", "iScience", "Cell Rep Phys Sci",
        "Patterns (N Y)", "Comput Struct Biotechnol J", "Neuroimage",
        "J Biol Chem", "Epidemics", "Infect Dis Model", "Curr Res Struct Biol",
        "Biophys Rep (N Y)", "Neuron", "Cell Syst", "Ultrason Sonochem",
        "Math Biosci", "Neuroimage Clin", "Curr Res Neurobiol", "Mater Today Bio",
        "Data Brief", "MethodsX", "Genomics Proteomics Bioinformatics", "J Adv Res",
        "Redox Biol", "EBioMedicine", "Neurobiol Dis", "Biophys Rep", "STAR Protoc",
        "Cell Rep Methods", "Cell Rep Med", "Cell Genom", "Curr Biol", "Cell",
        "Mol Cell", "Dev Cell", "Structure", "Biochim Biophys Acta", "Nanomedicine",
    ],
    "mdpi": [
        "Entropy (Basel)", "Sensors (Basel)", "Symmetry (Basel)",
        "Mathematics (Basel)", "Materials (Basel)", "Micromachines (Basel)",
        "Algorithms", "Appl Sci (Basel)", "Polymers (Basel)", "Int J Mol Sci",
        "Biosensors (Basel)", "Nanomaterials (Basel)", "Sensors",
        "Entropy", "Math", "Axioms", "Fractal Fract",
    ],
    "wiley-hindawi": [
        "Comput Math Methods Med", "Comput Intell Neurosci", "J Healthc Eng",
        "Ecol Evol", "Stat Med", "Med Phys", "Biomed Res Int", "J Math",
        "J Appl Math", "Math Probl Eng", "Contrast Media Mol Imaging",
        "Brain Behav", "Cancer Med", "Evol Appl", "Methods Ecol Evol",
        "Wiley Interdiscip Rev Comput Mol Sci", "Bioeng Transl Med",
        "Comput Intell Neurosci",
    ],
    "oup-pnas-royal-society": [
        "Gigascience", "Bioinformatics", "Nucleic Acids Res", "Mol Biol Evol",
        "Genetics", "G3 (Bethesda)", "Proc Natl Acad Sci U S A",
        "Proc Biol Sci", "J R Soc Interface", "Philos Trans A Math Phys Eng Sci",
        "Proc Math Phys Eng Sci", "R Soc Open Sci", "Interface Focus",
        "Biol Lett", "Open Biol", "Cereb Cortex", "Genome Biol Evol",
        "Bioinform Adv", "Plant Physiol",
    ],
    "plos": [
        "PLoS One", "PLoS Comput Biol", "PLoS Genet", "PLoS Pathog",
        "PLoS Biol", "PLoS Negl Trop Dis",
    ],
    "elife": ["eLife"],
    "frontiers": [
        "Front Neurosci", "Front Physiol", "Front Comput Neurosci",
        "Front Neuroinform", "Front Psychol", "Front Genet", "Front Phys",
        "Front Appl Math Stat", "Front Neurorobot", "Front Bioeng Biotechnol",
        "Front Neural Circuits", "Front Syst Neurosci", "Front Public Health",
    ],
    "f1000research": ["F1000Res"],
    "aims-press": ["Math Biosci Eng", "AIMS Public Health", "AIMS Neurosci",
                   "AIMS Microbiol", "AIMS Biophys"],
    "peerj": ["PeerJ", "PeerJ Comput Sci", "PeerJ Phys Chem", "PeerJ Mater Sci"],
    "other": [
        "Biomed Opt Express", "Opt Express", "ACS Omega", "ACS Cent Sci",
        "J Phys Chem Lett", "Epidemiol Infect", "Proc Nutr Soc", "Nanophotonics",
        "Open Phys", "J Integr Bioinform", "Int J Nanomedicine", "Sci Adv",
        "eNeuro", "mBio", "J Exp Biol", "Development", "Biol Open",
        "Nano Lett", "Phys Med Biol", "AIP Adv", "Chaos", "J Chem Phys",
        "IEEE Access", "Stat Appl Genet Mol Biol", "Biometrics", "J Appl Stat",
        "Life Sci Alliance", "Physiol Rep", "Genes Dev", "Genome Res",
        "JACS Au", "ACS Phys Chem Au", "ACS Nano", "Anal Chem", "J Chem Inf Model",
        "J Chem Theory Comput", "ACS Appl Mater Interfaces", "J Biol Dyn",
        "Stat Methods Med Res", "Quant Plant Biol", "Parasitology", "Epidemiol Infect",
        "Cambridge Prisms Glob Ment Health", "Philos Trans R Soc Lond B Biol Sci",
        "Nat Hum Behav", "Sci Data", "Commun Chem", "Commun Mater", "Commun Earth Environ",
        "Nat Commun", "Phys Rev Res", "Rev Mod Phys",
        "Micromachines", "Photonics", "Open Math", "Adv Sci (Weinh)",
        "Environ Res Lett", "Sensors and Actuators", "Atmos Chem Phys",
    ],
}

WINDOWS = [(2009, 2014), (2015, 2018), (2019, 2021), (2022, 2026)]
MATH_TERMS = ('("differential equation" OR "mathematical model" OR "analytical solution" '
              'OR Hamiltonian OR "numerical simulation" OR theorem OR stochastic OR Bayesian '
              'OR optimization OR equations)')
LICENCE_FILTER = '(LICENSE:"cc by" OR LICENSE:"cc0" OR LICENSE:"cc by-sa")'

# metadata license_code -> class; Creative Commons URL path -> class
CODE_CLASS = {"CC BY": "by", "CC BY-SA": "by-sa", "CC0": "zero"}
SPDX = {"by": "CC-BY-{v}", "by-sa": "CC-BY-SA-{v}", "zero": "CC0-{v}"}
CC_URL = re.compile(r"https?://creativecommons\.org/(licenses|publicdomain)/([\w-]+)/?([\d.]*)", re.I)

PUBLISHER_GROUP = [  # (substring of the lower-case publisher name, producer, group)
    ("royal society of chemistry", "Royal Society of Chemistry", "other"),
    ("springer", "Springer Nature", "springer-nature"),
    ("nature", "Springer Nature", "springer-nature"),
    ("biomed central", "Springer Nature", "springer-nature"),
    ("bmc", "Springer Nature", "springer-nature"),
    ("elsevier", "Elsevier", "elsevier"),
    ("cell press", "Elsevier", "elsevier"),
    ("mdpi", "MDPI", "mdpi"),
    ("hindawi", "Hindawi", "wiley-hindawi"),
    ("wiley", "Wiley", "wiley-hindawi"),
    ("oxford university press", "Oxford University Press", "oup-pnas-royal-society"),
    ("national academy of sciences", "PNAS", "oup-pnas-royal-society"),
    ("royal society", "Royal Society", "oup-pnas-royal-society"),
    ("public library of science", "PLOS", "plos"),
    ("elife", "eLife", "elife"),
    ("frontiers", "Frontiers", "frontiers"),
    ("f1000", "F1000Research", "f1000research"),
    ("aims press", "AIMS Press", "aims-press"),
    ("public library", "PLOS", "plos"),
    ("plos", "PLOS", "plos"),
    ("faculty of 1000", "F1000Research", "f1000research"),
    ("american institute of mathematical sciences", "AIMS Press", "aims-press"),
    ("peerj", "PeerJ", "peerj"),
]


# DOI prefix -> (producer, group); the prefix identifies the publisher
# whose production pipeline wrote the markup, also for society journals.
DOI_PREFIX = {
    "10.1016": ("Elsevier", "elsevier"), "10.3390": ("MDPI", "mdpi"),
    "10.1038": ("Springer Nature", "springer-nature"),
    "10.1186": ("Springer Nature", "springer-nature"),
    "10.1007": ("Springer Nature", "springer-nature"),
    "10.1155": ("Hindawi", "wiley-hindawi"), "10.1002": ("Wiley", "wiley-hindawi"),
    "10.1111": ("Wiley", "wiley-hindawi"),
    "10.1093": ("Oxford University Press", "oup-pnas-royal-society"),
    "10.1073": ("PNAS", "oup-pnas-royal-society"),
    "10.1098": ("Royal Society", "oup-pnas-royal-society"),
    "10.1371": ("PLOS", "plos"), "10.7554": ("eLife", "elife"),
    "10.3389": ("Frontiers", "frontiers"), "10.12688": ("F1000Research", "f1000research"),
    "10.3934": ("AIMS Press", "aims-press"), "10.7717": ("PeerJ", "peerj"),
}


def producer_and_group(publisher, doi=None):
    """Normalise to ``(producer, group)`` from the DOI prefix, else the publisher name."""
    low = publisher.lower()
    if doi and doi.split("/")[0] in DOI_PREFIX:
        producer, group = DOI_PREFIX[doi.split("/")[0]]
        if "hindawi" in low:
            producer = "Hindawi"
        return producer, group
    for needle, producer, group in PUBLISHER_GROUP:
        if needle in low:
            return producer, group
    return publisher.strip() or "unknown", "other"


# ---------------------------------------------------------------- select

def bucket_size(group, docs_per_target=30, margin=2):
    """Candidates to request per (journal, period) bucket of a group.

    About ``target / 30`` articles are needed to reach a group's target at
    roughly 30 distinct formulas per article; twice as many are requested
    because some articles carry no MathML or fail the licence check.
    """
    buckets = len(set(JOURNALS[group])) * len(WINDOWS)
    need = margin * TARGETS[group] / docs_per_target
    return int(min(400, max(40, need / buckets)))


def select(args):
    """Query Europe PMC for candidate articles and append them to candidates.jsonl."""
    os.makedirs(args.work, exist_ok=True)
    http = sc.HttpClient(1.0)
    done = sc.DoneList(os.path.join(args.work, "select.done"))
    name = "candidates." + (args.groups.replace(",", "+") if args.groups else "all") \
        + (".any" if args.any_topic else "") + ".jsonl"
    out = open(os.path.join(args.work, name), "a", encoding="utf-8")
    only = set(args.groups.split(",")) if args.groups else None
    for group, journals in JOURNALS.items():
        if only and group not in only:
            continue
        for journal in list(dict.fromkeys(journals))[: args.max_journals or None]:
            for lo, hi in WINDOWS[-args.windows:]:
                bucket = f"{group}|{journal}|{lo}-{hi}" + ("|any" if args.any_topic else "")
                if bucket in done:
                    continue
                per_bucket = args.per_bucket or bucket_size(group)
                query = (f'JOURNAL:"{journal}" AND OPEN_ACCESS:y AND HAS_FT:y AND {LICENCE_FILTER} '
                         f'AND PUB_YEAR:[{lo} TO {hi}]'
                         + ('' if args.any_topic else f' AND ABSTRACT:{MATH_TERMS}'))
                url = EUROPE_PMC + "?" + urllib.parse.urlencode({
                    "query": query, "format": "json", "resultType": "lite",
                    "pageSize": per_bucket})
                status, body, _ = http.get(url)
                if status != 200:
                    sc.log("select failed", bucket, status)
                    continue
                data = json.loads(body)
                for rank, r in enumerate(data["resultList"]["result"]):
                    if not r.get("pmcid"):
                        continue
                    out.write(json.dumps({
                        "pmcid": r["pmcid"], "group": group, "bucket": bucket, "rank": rank,
                        "journal": r.get("journalTitle"), "year": r.get("pubYear")}) + "\n")
                out.flush()
                done.add(bucket)
                sc.log("select", bucket, data["hitCount"], len(data["resultList"]["result"]))


# --------------------------------------------------------------- extract

def first(pattern, text, flags=re.S):
    m = re.search(pattern, text, flags)
    return m.group(1) if m else None


def plain(s):
    """Text of an XML fragment with tags removed and entities decoded."""
    return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", "", s or ""))).strip()


def parse_front(xml):
    """Return bibliographic metadata and licence URLs from the article front matter."""
    front = xml[: xml.find("</front>")] if "</front>" in xml else xml[:200000]
    journal_meta = first(r"<journal-meta>(.*?)</journal-meta>", front) or ""
    meta = first(r"<article-meta>(.*)", front) or front
    authors = []
    for c in re.findall(r'<contrib\b[^>]*contrib-type="author"[^>]*>(.*?)</contrib>', meta, re.S):
        sn = first(r"<surname[^>]*>(.*?)</surname>", c)
        gn = first(r"<given-names[^>]*>(.*?)</given-names>", c)
        if sn:
            authors.append(plain((gn + " " if gn else "") + sn))
    years = re.findall(r"<pub-date\b[^>]*>.*?<year>(\d{4})</year>", meta, re.S)
    perms = first(r"<permissions>(.*?)</permissions>", meta) or ""
    return {
        "title": plain(first(r"<article-title[^>]*>(.*?)</article-title>", meta)),
        "authors": "; ".join(authors),
        "journal": plain(first(r"<journal-title[^>]*>(.*?)</journal-title>", journal_meta)),
        "publisher": plain(first(r"<publisher-name[^>]*>(.*?)</publisher-name>", journal_meta)),
        "year": min(years) if years else None,
        "doi": plain(first(r'<article-id pub-id-type="doi">(.*?)</article-id>', meta)),
        "licence_urls": sorted({m.group(0).rstrip("/") + "/" for m in CC_URL.finditer(perms)}),
    }


def licence_decision(code, urls):
    """Return ``(spdx, url, reason)``; ``spdx`` is None when the article must be skipped."""
    cls = CODE_CLASS.get(code)
    if cls is None:
        return None, None, f"licence code {code!r}"
    parsed = set()
    for u in urls:
        m = CC_URL.match(u)
        kind = {"zero": "zero", "by": "by", "by-sa": "by-sa"}.get(m.group(2).lower(), "other:" + m.group(2))
        parsed.add((kind, m.group(3).strip(".")))
    classes = {k for k, _ in parsed}
    # A CC0 dedication next to the article licence (Springer Nature adds one
    # for supplementary data) is more permissive and does not conflict.
    if classes - {"zero"} != {cls} - {"zero"} or (cls != "zero" and cls not in classes):
        return None, None, f"licence mismatch: code {code!r}, JATS {sorted(classes) or 'none'}"
    parsed = {(k, v) for k, v in parsed if k == cls}
    versions = sorted({v for _, v in parsed})
    if len(versions) != 1 or not versions[0]:
        return None, None, "licence version missing or ambiguous"
    url = next(u for u in urls if CC_URL.match(u).group(2).lower() == cls and versions[0] in u)
    return SPDX[cls].format(v=versions[0]), url, None


class Frame:
    __slots__ = ("kind", "tex", "maths")

    def __init__(self, kind):
        self.kind, self.tex, self.maths = kind, [], []


WRAPPER = re.compile(r"<(/?)(inline-formula|disp-formula|alternatives)(?=[\s>/])[^>]*?(/?)>")
TEX_MATH = re.compile(r"<tex-math(?=[\s>])[^>]*>(.*?)</tex-math>", re.S)
ANNOTATION_TEX = re.compile(
    r"<(?:\w+:)?annotation\b[^>]*encoding=[\"'][^\"']*tex[^\"']*[\"'][^>]*>(.*?)</(?:\w+:)?annotation\s*>",
    re.S | re.I)


def clean_tex(raw):
    raw = raw.strip()
    m = re.fullmatch(r"<!\[CDATA\[(.*)\]\]>", raw, re.S)
    raw = m.group(1) if m else html.unescape(raw)
    return sc.tidy_tex(raw)


def extract_formulas(xml):
    """Return ``(found, formulas)`` for a JATS document.

    ``found`` is the number of math elements; ``formulas`` maps each
    distinct MathML string to a record with its occurrence count, context
    (from the enclosing inline or display formula, else the ``display``
    attribute) and the TeX of a sibling ``tex-math`` inside the same
    ``alternatives`` element.
    """
    spans = sc.find_math_spans(xml)
    events = []  # (position, order, kind, payload)
    for m in WRAPPER.finditer(xml):
        if m.group(3) == "/":
            continue
        events.append((m.start(), 0, "close" if m.group(1) else "open", m.group(2)))
    for m in TEX_MATH.finditer(xml):
        events.append((m.start(), 1, "tex", m.group(1)))
    for i, (a, b) in enumerate(spans):
        events.append((a, 2, "math", i))
    events.sort(key=lambda e: e[:2])
    stack, math_info = [], {}
    for _, _, kind, payload in events:
        if kind == "open":
            stack.append(Frame(payload))
        elif kind == "close":
            while stack and stack[-1].kind != payload:
                stack.pop()
            if not stack:
                continue
            f = stack.pop()
            if f.kind == "alternatives" and f.tex and len(f.tex) == len(f.maths):
                for i, t in zip(f.maths, f.tex):
                    math_info[i]["tex"] = t
        elif kind == "tex":
            for f in reversed(stack):
                if f.kind == "alternatives":
                    f.tex.append(payload)
                    break
        else:
            ctx = None
            for f in reversed(stack):
                if f.kind in ("inline-formula", "disp-formula"):
                    ctx = "inline" if f.kind == "inline-formula" else "display"
                    break
            math_info[payload] = {"ctx": ctx, "tex": None}
            for f in reversed(stack):
                if f.kind == "alternatives":
                    f.maths.append(payload)
                    break
    formulas = {}
    for i, (a, b) in enumerate(spans):
        s = xml[a:b]
        info = math_info.get(i, {"ctx": None, "tex": None})
        tex, kind = (clean_tex(info["tex"]) if info["tex"] else None), None
        if tex:
            kind = "author"
        else:
            m = ANNOTATION_TEX.search(s)
            if m:
                tex = clean_tex(m.group(1))
                kind = "author" if tex else None
        rec = formulas.get(s)
        if rec is None:
            formulas[s] = {"n": 1, "context": info["ctx"] or sc.context_from_display(s),
                           "tex": tex, "tex_kind": kind, "markup": sc.classify_markup(s)}
        else:
            rec["n"] += 1
            if rec["tex"] is None and tex:
                rec["tex"], rec["tex_kind"] = tex, kind
    return len(spans), formulas


def candidate_order(work, only):
    """Per-group candidate lists, interleaved across (journal, period) buckets.

    Reads every ``candidates*.jsonl`` file of the work directory (one per
    ``select`` run).
    """
    queues, seen, rows = {}, set(), []
    for name in sorted(os.listdir(work)):
        if name.startswith("candidates") and name.endswith(".jsonl"):
            with open(os.path.join(work, name), encoding="utf-8") as f:
                rows.extend(json.loads(line) for line in f)
    rows.sort(key=lambda r: (r["rank"], hashlib.sha256((SEED + r["bucket"]).encode()).hexdigest()))
    for r in rows:
        if r["pmcid"] in seen or (only and r["group"] not in only):
            continue
        seen.add(r["pmcid"])
        queues.setdefault(r["group"], []).append(r)
    return queues


def extract(args):
    """Fetch candidates until every group reaches its target or runs out."""
    http = sc.HttpClient(1.0)
    done = sc.DoneList(os.path.join(args.work, "extract.done"))
    store = sc.DocumentStore(os.path.join(args.work, "documents.jsonl.gz"))
    log_path = open(os.path.join(args.work, "decisions.tsv"), "a", encoding="utf-8")
    only = set(args.groups.split(",")) if args.groups else None
    queues = candidate_order(args.work, only)
    distinct = {g: set() for g in TARGETS}
    for rec in store:
        g = rec["doc"]["group"]
        distinct[g].update(sc.formula_id(f["mathml"]) for f in rec["formulas"])
    attempts = {g: 0 for g in TARGETS}
    cursor = {g: 0 for g in queues}
    try:
        while True:
            open_groups = [g for g in queues
                           if len(distinct[g]) < TARGETS[g] and cursor[g] < len(queues[g])
                           and (not args.max_docs_per_group or attempts[g] < args.max_docs_per_group)]
            if not open_groups:
                break
            group = max(open_groups, key=lambda g: TARGETS[g] - len(distinct[g]))
            cand = queues[group][cursor[group]]
            cursor[group] += 1
            if cand["pmcid"] in done:
                continue
            attempts[group] += 1
            outcome = process(http, cand, store, distinct)
            log_path.write(f"{cand['pmcid']}\t{cand['group']}\t{outcome}\n")
            log_path.flush()
            done.add(cand["pmcid"])
            if len(done.keys) % 25 == 0:
                sc.log("done", len(done.keys), {g: len(v) for g, v in distinct.items() if v})
    except sc.StopRequested as e:
        sc.log("stopped:", e)
        return 3
    sc.log("finished", {g: len(v) for g, v in distinct.items() if v})
    return 0


def find_version(http, pmcid):
    """Return the highest version of an article in the bucket, or None."""
    status, body, _ = http.get(f"{BUCKET}/?list-type=2&delimiter=/&prefix={pmcid}.")
    versions = re.findall(rf"<Prefix>{pmcid}\.(\d+)/</Prefix>", body.decode("utf-8", "replace"))
    return max(map(int, versions)) if versions else None


def process(http, cand, store, distinct):
    """Fetch, check and store one article. Returns a short outcome string."""
    pmcid = cand["pmcid"]
    ver = 1
    status, body, _ = http.get(f"{BUCKET}/{pmcid}.{ver}/{pmcid}.{ver}.json")
    if status == 404:
        ver = find_version(http, pmcid)
        if ver is None:
            return "skip: not in bucket"
        status, body, _ = http.get(f"{BUCKET}/{pmcid}.{ver}/{pmcid}.{ver}.json")
    if status != 200:
        return f"skip: metadata status {status}"
    meta = json.loads(body)
    if meta.get("license_code") not in CODE_CLASS:
        return f"skip: licence code {meta.get('license_code')!r}"
    if meta.get("is_manuscript") or meta.get("is_retracted") or meta.get("is_historical_ocr"):
        return "skip: manuscript, retracted or scanned"
    xml_url = f"{BUCKET}/{pmcid}.{ver}/{pmcid}.{ver}.xml"
    status, body, _ = http.get(xml_url)
    if status != 200:
        return f"skip: xml status {status}"
    xml = body.decode("utf-8", "replace")
    front = parse_front(xml)
    spdx, lic_url, reason = licence_decision(meta["license_code"], front["licence_urls"])
    if spdx is None:
        return "skip: " + reason
    found, formulas = extract_formulas(xml)
    if not formulas:
        return "skip: no MathML"
    doi = front["doi"] or meta.get("doi")
    producer, group = producer_and_group(front["publisher"], doi)
    if len(distinct[group]) >= TARGETS[group]:
        return f"skip: group {group} complete"
    origin = f"https://doi.org/{doi}" if doi else f"https://pmc.ncbi.nlm.nih.gov/articles/{pmcid}/"
    chosen = sc.sample_formulas(formulas, CAP_PER_DOCUMENT, SEED, pmcid)
    doc = {
        "origin": origin, "pmcid": pmcid, "pmc_version": ver, "title": front["title"],
        "authors": front["authors"], "journal": front["journal"], "year": front["year"],
        "publisher": front["publisher"], "producer": producer, "group": group,
        "licence": spdx, "licence_url": lic_url, "license_code": meta["license_code"],
        "access_url": xml_url, "retrieved": sc.today(),
        "formulas_found": found, "formulas_distinct": len(formulas),
    }
    out = [dict(mathml=s, **{k: v for k, v in rec.items()}) for s, rec in chosen]
    store.append({"doc": doc, "formulas": out})
    distinct[group].update(sc.formula_id(s) for s, _ in chosen)
    return f"kept {len(chosen)}/{len(formulas)} {group}"


# ----------------------------------------------------------------- build

def build(args):
    """Merge the store into ``pmc.jsonl`` and ``pmc.documents.jsonl``."""
    store = sc.DocumentStore(os.path.join(args.work, "documents.jsonl.gz"))
    print(json.dumps(sc.build_outputs(store, "pmc", args.out), indent=1))


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = p.add_subparsers(dest="cmd", required=True)
    s = sub.add_parser("select")
    s.add_argument("--work", required=True)
    s.add_argument("--per-bucket", type=int, default=0, help="candidates per bucket (0: sized from the group target)")
    s.add_argument("--groups", default="", help="comma-separated group names (default: all)")
    s.add_argument("--any-topic", action="store_true",
                   help="do not require mathematical vocabulary in the abstract")
    s.add_argument("--max-journals", type=int, default=0, help="first N journals per group (0: all)")
    s.add_argument("--windows", type=int, default=len(WINDOWS), help="use the latest N periods")
    e = sub.add_parser("extract")
    e.add_argument("--work", required=True)
    e.add_argument("--max-docs-per-group", type=int, default=0)
    e.add_argument("--groups", default="")
    b = sub.add_parser("build")
    b.add_argument("--work", required=True)
    b.add_argument("--out", required=True)
    args = p.parse_args()
    return {"select": select, "extract": extract, "build": build}[args.cmd](args)


if __name__ == "__main__":
    sys.exit(main())