File size: 11,920 Bytes
21786f2
 
 
 
 
 
 
 
 
 
 
 
 
 
b454975
 
 
 
21786f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b454975
21786f2
 
 
 
 
 
 
b454975
 
21786f2
 
 
 
b454975
 
 
 
21786f2
 
 
 
 
 
 
 
 
 
 
 
 
 
b454975
21786f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b454975
 
21786f2
 
 
 
 
 
 
 
 
 
 
 
b454975
 
21786f2
 
 
 
 
 
 
 
 
 
 
 
 
 
b454975
 
21786f2
 
 
 
 
 
 
b454975
 
21786f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Build the advanced-search data from MuSProt.db (+ the MuSProt-index.db sidecar).

MuSProt.db stores every value as TEXT and indexes only the per-chain lookups,
so arbitrary filters over its 113M edges would scan 47 GB. This writes typed,
column-compressed Parquet that DuckDB filters in seconds:

  MuSProt-search-nodes.parquet      one row per observation; node_id (int) plus
                                    every node column, numbers as numbers, and
                                    function_text (top functions, lower case)
  MuSProt-search-edges.parquet      one row per directed transition; node_id_A /
                                    node_id_B link to the nodes file, every edge
                                    column typed; cross_state flag

The website also serves its chain pages from these files (app/protein/records.py),
so nodes are ordered by (pdb_id, chain) = node_id and edges / partners by node_id,
in small row groups.
  MuSProt-search-partners.parquet   the partner table, typed, with node_id
  MuSProt-search-sequences.parquet  the index's sequence catalog
  MuSProt-search-facets.json        value lists / ranges the search form offers

Empty strings become NULL. RMSD and coverage are NULL where pair_similarity is
empty (no shared residues; the DB stores 0.0 there). Values are otherwise
exactly the DB's, so a downloaded subset matches MuSProt.db.

Usage:
  python backend/scripts/build_search.py /path/MuSProt.db /path/MuSProt-index.db --out-dir DIR
"""
from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

import duckdb

INT, DBL, BOOL = "INTEGER", "DOUBLE", "BOOLEAN"

NODE_COLS: list[tuple[str, str | None]] = [
    ("sequence_id", None), ("uniprot_id", None), ("pdb_id", None), ("auth_asym_id", None),
    ("sequence", None), ("sequence_length", INT), ("modeled_sequence", None),
    ("modeled_sequence_length", INT), ("resolved_label_seq", None), ("n_resolved_aa", INT),
    ("resolved_coverage", DBL), ("binders", None), ("binding_status", None),
    ("experimental_method", None), ("resolution", DBL), ("pH", DBL), ("temp_K", DBL),
    ("experimental_details", None), ("chain_composition", None),
    ("non_protein_polymer_binding", None), ("initial_release_date", None), ("cath_id", None),
    ("cath_superfamily", None), ("pfam_id", None), ("ecod_id", None), ("ecod_fid", None),
    ("state_id", INT), ("Rosetta", DBL), ("FoldX", DBL), ("EvoEF2", DBL), ("RW", DBL), ("RW+", DBL),
    ("n_seqres", INT), ("n_resolved", INT), ("n_scored", INT), ("scored_coverage", DBL),
    ("foldx_n_scored", INT), ("foldx_coverage", DBL), ("ranked_functions", None),
    ("matching_scores", None), ("polymer_partners", None), ("polymer_partner_status", None),
    ("em_label", None), ("em_label_source", None), ("em_reconstruction", None),
    ("modified_residues", None), ("modification_types", None),
]

EDGE_COLS: list[tuple[str, str | None]] = [
    ("pdb_id_A", None), ("auth_asym_id_A", None), ("pdb_id_B", None), ("auth_asym_id_B", None),
    ("sequence_id", None), ("tm_aln", DBL), ("RMSD", DBL), ("coverage", DBL), ("pair_similarity", DBL),
    ("delta_Rosetta", DBL), ("delta_FoldX", DBL), ("delta_EvoEF2", DBL), ("delta_RW", DBL), ("delta_RW+", DBL),
    ("z_Rosetta", DBL), ("z_FoldX", DBL), ("z_EvoEF2", DBL), ("z_RW", DBL), ("z_RW+", DBL),
    ("state_id_A", INT), ("state_id_B", INT), ("state_similarity", DBL), ("state_fidelity", None),
    ("pair_fidelity", None), ("n_shared_resolved", INT), ("delta_order_valid", BOOL),
    ("order_invalid_reason", None), ("n_ordered", INT), ("n_disordered", INT),
    ("ordered_ranges", None), ("disordered_ranges", None), ("longest_ordered_segment", INT),
    ("longest_disordered_segment", INT), ("n_terminal_ordered", INT), ("n_internal_ordered", INT),
    ("order_evidence", None), ("ordering_with_ligand_change", BOOL),
]

PARTNER_COLS: list[tuple[str, str | None]] = [
    ("pdb_id", None), ("auth_asym_id", None), ("partner_chain", None), ("partner_entity", None),
    ("partner_type", None), ("partner_description", None), ("partner_uniprot", None),
    ("n_res_target", INT), ("n_res_partner", INT), ("n_contacts", INT), ("target_interface", None),
    ("same_entity", BOOL), ("via_symmetry", BOOL), ("in_assembly1", BOOL),
]


def log(msg: str) -> None:
    print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)


def q(name: str) -> str:
    return '"' + name.replace('"', '""') + '"'


def typed(alias: str, col: str, typ: str | None) -> str:
    src = f"NULLIF({alias}.{q(col)}, '')"
    if typ is None:
        return f"{src} AS {q(col)}"
    if typ == BOOL:
        return f"CASE lower({src}) WHEN 'true' THEN TRUE WHEN '1' THEN TRUE WHEN 'false' THEN FALSE WHEN '0' THEN FALSE END AS {q(col)}"
    return f"TRY_CAST({src} AS {typ}) AS {q(col)}"


def present(con, schema: str, table: str) -> set[str]:
    return {r[1] for r in con.execute(f"PRAGMA table_info({schema}.{q(table)})").fetchall()}


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("db", type=Path)
    ap.add_argument("index", type=Path)
    ap.add_argument("--out-dir", type=Path, required=True)
    ap.add_argument("--threads", type=int, default=16)
    ap.add_argument("--memory", default="24GB", help="DuckDB memory limit")
    ap.add_argument("--limit", type=int, default=None, help="debug: only the first N edges")
    args = ap.parse_args()
    out = args.out_dir
    out.mkdir(parents=True, exist_ok=True)

    con = duckdb.connect()
    con.execute(f"SET threads = {args.threads}")
    con.execute(f"SET memory_limit = '{args.memory}'")
    con.execute(f"SET temp_directory = '{out / '.duckdb_tmp'}'")  # the edge sort spills here
    con.execute("SET preserve_insertion_order = false")
    con.execute("INSTALL sqlite; LOAD sqlite;")
    con.execute(f"ATTACH '{args.db}' AS m (TYPE sqlite, READ_ONLY)")
    con.execute(f"ATTACH '{args.index}' AS ix (TYPE sqlite, READ_ONLY)")
    # sorted by chain with small row groups, so a per-chain read (the website's
    # chain pages) touches one or two groups: min/max statistics prune the rest
    def pq(rows: int) -> str:
        return f"(FORMAT parquet, COMPRESSION zstd, ROW_GROUP_SIZE {rows})"

    t0 = time.time()
    have = present(con, "m", "node")
    cols = ",\n  ".join(typed("n", c, t) for c, t in NODE_COLS if c in have)
    log("nodes")
    con.execute(f"""
        CREATE TEMP TABLE nodes AS
        SELECT CAST(row_number() OVER (ORDER BY lower(n.pdb_id), n.auth_asym_id) - 1 AS INTEGER) AS node_id,
               {cols},
               -- the top functions, lower-cased, for fast text matching (ranked_functions is long JSON)
               lower(substr(NULLIF(n.ranked_functions, ''), 1, 2000)) AS function_text
        FROM m.node n
    """)
    con.execute("UPDATE nodes SET pdb_id = lower(pdb_id)")
    con.execute(f"COPY (SELECT * FROM nodes ORDER BY node_id) TO '{out / 'MuSProt-search-nodes.parquet'}' {pq(10_000)}")
    log(f"  {con.execute('SELECT count(*) FROM nodes').fetchone()[0]:,} nodes ({time.time() - t0:.0f} s)")

    log("edges")
    have = present(con, "m", "edge")
    cols = ",\n  ".join(typed("e", c, t) for c, t in EDGE_COLS if c in have)
    src = f"(SELECT * FROM m.edge LIMIT {int(args.limit)})" if args.limit else "m.edge"
    con.execute(f"""
        COPY (
          WITH e AS (
            SELECT {cols} FROM {src} e
          )
          SELECT a.node_id AS node_id_A, b.node_id AS node_id_B,
                 e.* REPLACE (lower(e.pdb_id_A) AS pdb_id_A, lower(e.pdb_id_B) AS pdb_id_B,
                              CASE WHEN e.pair_similarity IS NULL THEN NULL ELSE e.RMSD END AS RMSD,
                              CASE WHEN e.pair_similarity IS NULL THEN NULL ELSE e.coverage END AS coverage),
                 e.state_id_A IS DISTINCT FROM e.state_id_B AS cross_state
          FROM e
          JOIN nodes a ON a.pdb_id = lower(e.pdb_id_A) AND a.auth_asym_id = e.auth_asym_id_A
          JOIN nodes b ON b.pdb_id = lower(e.pdb_id_B) AND b.auth_asym_id = e.auth_asym_id_B
          ORDER BY node_id_A, node_id_B
        ) TO '{out / 'MuSProt-search-edges.parquet'}' {pq(122_880)}
    """)
    n_e = con.execute(f"SELECT count(*) FROM '{out / 'MuSProt-search-edges.parquet'}'").fetchone()[0]
    log(f"  {n_e:,} edges ({time.time() - t0:.0f} s)")

    log("partners")
    have = present(con, "m", "partner")
    cols = ",\n  ".join(typed("p", c, t) for c, t in PARTNER_COLS if c in have)
    con.execute(f"""
        COPY (
          SELECT n.node_id, p.* REPLACE (lower(p.pdb_id) AS pdb_id)
          FROM (SELECT {cols} FROM m.partner p) p
          JOIN nodes n ON n.pdb_id = lower(p.pdb_id) AND n.auth_asym_id = p.auth_asym_id
          ORDER BY n.node_id, p.partner_chain
        ) TO '{out / 'MuSProt-search-partners.parquet'}' {pq(50_000)}
    """)

    log("sequences")
    con.execute(f"""
        COPY (
          SELECT s.*, agg.n_modified, agg.n_bound_hetero, agg.best_resolution
          FROM ix.sequence s
          LEFT JOIN (
            SELECT sequence_id,
                   count(*) FILTER (WHERE modified_residues IS NOT NULL) AS n_modified,
                   count(*) FILTER (WHERE polymer_partner_status = 'hetero') AS n_bound_hetero,
                   min(resolution) AS best_resolution
            FROM nodes GROUP BY sequence_id
          ) agg USING (sequence_id)
          ORDER BY sequence_id
        ) TO '{out / 'MuSProt-search-sequences.parquet'}' {pq(20_000)}
    """)

    log("facets")
    facets = build_facets(con, out)
    (out / "MuSProt-search-facets.json").write_text(json.dumps(facets))
    for f in sorted(out.glob("MuSProt-search-*")):
        log(f"  {f.name}: {f.stat().st_size / 1e9:.2f} GB")
    import shutil
    shutil.rmtree(out / ".duckdb_tmp", ignore_errors=True)
    log(f"done ({time.time() - t0:.0f} s)")


def build_facets(con, out: Path) -> dict:
    """Value lists for categorical / list fields and ranges for numeric ones, per file."""
    files = {
        "nodes": out / "MuSProt-search-nodes.parquet",
        "edges": out / "MuSProt-search-edges.parquet",
        "sequences": out / "MuSProt-search-sequences.parquet",
    }
    res: dict[str, dict] = {}
    for name, path in files.items():
        cols = con.execute(f"DESCRIBE SELECT * FROM '{path}'").fetchall()
        res[name] = {}
        for col, typ, *_ in cols:
            qc = q(col)
            if typ in ("INTEGER", "BIGINT", "DOUBLE", "FLOAT"):
                r = con.execute(
                    f"SELECT min({qc}), max({qc}), quantile_cont({qc}, [0.05, 0.5, 0.95]), count({qc}) FROM '{path}'"
                ).fetchone()
                res[name][col] = {"min": r[0], "max": r[1], "quantiles": r[2], "n": r[3]}
            elif typ == "VARCHAR":
                n_distinct = con.execute(f"SELECT approx_count_distinct({qc}) FROM '{path}'").fetchone()[0]
                if n_distinct <= 60:
                    vals = con.execute(
                        f"SELECT {qc}, count(*) FROM '{path}' WHERE {qc} IS NOT NULL GROUP BY 1 ORDER BY 2 DESC"
                    ).fetchall()
                    res[name][col] = {"values": [[v, c] for v, c in vals]}
                elif col in LIST_COLS:
                    vals = con.execute(
                        f"SELECT t, count(*) FROM (SELECT unnest(string_split({qc}, ';')) AS t FROM '{path}' "
                        f"WHERE {qc} IS NOT NULL) WHERE t <> '' GROUP BY 1 ORDER BY 2 DESC LIMIT 300"
                    ).fetchall()
                    res[name][col] = {"tokens": [[v, c] for v, c in vals]}
    return res


# ';'-joined columns whose individual items are offered as choices
LIST_COLS = {
    "binders", "modification_types", "cath_superfamily", "pfam_id", "ecod_fid", "methods", "ecod_hset",
    "pfam_ids", "em_reconstruction",
}


if __name__ == "__main__":
    main()