File size: 6,569 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
#!/usr/bin/env python3
"""Extract Content MathML from SBML models in BioModels (CC0).

Usage: biomodels.py --work DIR --out DIR [--seed N] [--models N]
                    [--max-total N] [--max-model N] [--max-file-mb X]

Lists the SBML models through the public BioModels search API (one request
per second), picks `--models` of them with a seeded random sample, downloads
each model file once into `DIR/biomodels` (reused on a rerun) and reads every
`<math>` element of the file outside `<notes>`.  Models whose file is larger than `--max-file-mb` are skipped.  A model is used only if its
own file states the CC0 public domain dedication (a link to
creativecommons.org/publicdomain/zero/1.0/); the URL found in the file is
recorded as the licence URL.  At most `--max-model` distinct elements are
kept per model, and `--max-total` overall, by seeded sampling.  The element
is copied as found: SBML writes `<math xmlns="http://www.w3.org/1998/Math/MathML">`
with Content MathML children (`apply`, `ci`, `cn`, `lambda`, `piecewise`).
"""
import argparse
import json
import os
import random
import re
import urllib.parse
from datetime import date

import corpus_common as cc

API = "https://www.ebi.ac.uk/biomodels/search?query=*:*&format=json&numResults=100&sort=id-asc&offset=%d"
FILES = "https://www.ebi.ac.uk/biomodels/model/files/%s?format=json"
FILE = "https://www.ebi.ac.uk/biomodels/model/download/%s?filename=%s"
NOTES = re.compile(r"<notes\b.*?</notes>", re.S)
CC0 = re.compile(r'https?://creativecommons\.org/publicdomain/zero/1\.0/?')
CREATOR = re.compile(r"<vCard:Family>([^<]*)</vCard:Family>\s*<vCard:Given>([^<]*)</vCard:Given>")
CREATOR2 = re.compile(r"<vCard:Given>([^<]*)</vCard:Given>\s*<vCard:Family>([^<]*)</vCard:Family>")


def model_list(cache):
    path = os.path.join(cache, "model-list.json")
    if os.path.exists(path):
        return json.load(open(path))
    models, off = [], 0
    while True:
        d = json.loads(cc.polite_get(API % off))
        models += [m for m in d["models"] if m.get("format") == "SBML"]
        off += 100
        if off >= d["matches"]:
            break
    json.dump(models, open(path, "w"))
    return models


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--work", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--seed", type=int, default=1)
    ap.add_argument("--models", type=int, default=1100)
    ap.add_argument("--max-file-mb", type=float, default=1.5,
                    help="skip models whose SBML file is larger than this")
    ap.add_argument("--max-total", type=int, default=8000)
    ap.add_argument("--max-model", type=int, default=40)
    a = ap.parse_args()
    cache = os.path.join(a.work, "biomodels")
    os.makedirs(cache, exist_ok=True)
    rng = random.Random(a.seed)
    listing = model_list(cache)
    shuffled = random.Random(a.seed).sample(listing, len(listing))   # a larger --models extends the sample
    chosen = sorted(shuffled[:a.models], key=lambda m: m["id"])
    cands, docs, found, skipped = [], [], 0, []
    today = date.today().isoformat()
    for m in chosen:
        mid = m["id"]
        fpath = os.path.join(cache, mid + ".xml")
        if os.path.exists(fpath + ".skip"):
            skipped.append((mid, "file larger than %g MB" % a.max_file_mb))
            continue
        if os.path.exists(fpath) and os.path.getsize(fpath) > a.max_file_mb * 1e6:
            skipped.append((mid, "file larger than %g MB" % a.max_file_mb))
            os.remove(fpath)
            open(fpath + ".skip", "w").write("large")
            continue
        if not os.path.exists(fpath):
            try:
                main_files = json.loads(cc.polite_get(FILES % mid)).get("main") or []
                entry = next(f for f in main_files if f["name"].endswith(".xml"))
                name = entry["name"]
                if int(entry.get("fileSize", 0)) > a.max_file_mb * 1e6:
                    skipped.append((mid, "file larger than %g MB" % a.max_file_mb))
                    open(fpath + ".skip", "w").write("large")
                    continue
                text = cc.polite_get(FILE % (mid, urllib.parse.quote(name)))
            except RuntimeError:
                raise
            except Exception as e:
                skipped.append((mid, str(e)))
                continue
            open(fpath, "w", encoding="utf-8").write(text)
            open(fpath + ".name", "w", encoding="utf-8").write(name)
        text = open(fpath, encoding="utf-8").read()
        name = open(fpath + ".name", encoding="utf-8").read() if os.path.exists(fpath + ".name") \
            else mid + "_url.xml"
        lic = CC0.search(text)
        if not lic:
            skipped.append((mid, "no CC0 statement"))
            continue
        body = NOTES.sub("", text)
        spans = [body[s:e] for s, e in cc.find_spans(body)]
        found += len(spans)
        distinct = list(dict.fromkeys(spans))
        if len(distinct) > a.max_model:
            distinct = rng.sample(distinct, a.max_model)
        origin = "https://www.ebi.ac.uk/biomodels/" + mid
        names = CREATOR.findall(text)
        names = ["%s %s" % (g.strip(), f.strip()) for f, g in names] or \
            ["%s %s" % (g.strip(), f.strip()) for g, f in CREATOR2.findall(text)]
        title = re.search(r'<model\b[^>]*\bname="([^"]*)"', text)
        docs.append(dict(origin=origin, title=title.group(1) if title else mid,
                         authors=", ".join(dict.fromkeys(names)) or m.get("submitter"),
                         licence="CC0-1.0", licence_url=lic.group(0).rstrip("/") + "/",
                         access_url=FILE % (mid, urllib.parse.quote(name)), retrieved=today, formulas=len(spans)))
        cands += [(x, origin, docs[-1]["licence_url"]) for x in distinct]
    if len(cands) > a.max_total:
        keep = set(rng.sample(range(len(cands)), a.max_total))
        cands = [c for i, c in enumerate(cands) if i in keep]
    w = cc.Writer("biomodels")
    w.stats["formulas_found"] = found
    for x, origin, lurl in cands:
        w.add(x, producer="BioModels (SBML kinetic laws, rules and function definitions)",
              origin=origin, licence="CC0-1.0", licence_url=lurl,
              context="unknown", markup=cc.classify_markup(x))
    w.stats.update(models_requested=len(chosen), models_skipped=len(skipped))
    w.write(a.out, docs)
    cc.log("biomodels found", found, "kept", len(w), "models", len(docs), "skipped", skipped[:5])


if __name__ == "__main__":
    main()