OpenFold3 Training Data: sample notebook

A worked notebook for OpenFold3 Training Data, with 9 code cells and the output each one printed. On Scigantic it opens in a hosted JupyterLab with the dataset already mounted, so nothing is downloaded first.

Provider
OpenFold Consortium
License
CC BY 4.0 (license terms)
Format
mmCIF (in sampled files)
Stored at
Amazon S3, s3://openfold3-data (us-west-2)
Access
Free and public. No account with the data provider is needed.

The notebook

Querying the whole OpenFold3 training set

OpenFold3 was trained on a corpus a little over 40 TB spread across five datasets. Looking at one entry at a time tells you almost nothing about it. The questions worth asking are about the corpus as a whole: what is actually in here, where does the training cutoff bite, which entries have an alignment, and how much evolutionary signal does any given entry really carry?

All of that is answerable in seconds, because the bucket ships its own index. portal_indexes/ holds six small SQLite files, one per dataset, and they are the same indexes that back the explore pages on portal.openfold.omsf.io. Reading pdb.sqlite costs 22 MB instead of walking 244,272 directories.

This notebook queries that index, follows a row out to the files it names, and ends on a result you can only get by reading the data: the two alignment files that ship for the same chain contain completely different evolutionary neighbourhoods, and which one you load changes every downstream number.

1. Open the index

The archive is mounted read-only, so open SQLite read-only too. Otherwise it tries to create a -wal sidecar on a filesystem that will not take one.

import os
import sqlite3
from pathlib import Path

MNT = Path(os.environ.get('SCIGANTIC_MOUNT_PATH', '/mnt/archive'))
INDEX = MNT / 'portal_indexes' / 'pdb.sqlite'

print(f'Archive:  {os.environ.get("SCIGANTIC_ARCHIVE_TITLE", "OpenFold3 Training Data")}')
print(f'Mount:    {MNT}  (exists: {MNT.exists()})')
print(f'Index:    {INDEX.name}  ({INDEX.stat().st_size / 1e6:.1f} MB)')

con = sqlite3.connect(f'file:{INDEX}?mode=ro', uri=True)
con.row_factory = sqlite3.Row

Output:

Archive:  OpenFold3 Training Data
Mount:    /private/tmp/claude-501/-Users-aaronkanzer-projects-scigantic/3255d9c9-786a-4a2e-bedd-6682bd6b6324/scratchpad/of3/mockmount  (exists: True)
Index:    pdb.sqlite  (22.7 MB)

2. What the index holds

One table, datapoints, one row per entry. All six portal_indexes/*.sqlite files share this schema, so the same queries work against the RNA, disordered and monomer distillation sets.

print(con.execute("SELECT sql FROM sqlite_master WHERE type='table'").fetchone()[0])

n = con.execute('SELECT COUNT(*) FROM datapoints').fetchone()[0]
print(f'\n{n:,} indexed entries')

# 1lol is the entry the OpenFold portal uses as its worked example. Same numbers here.
row = con.execute("SELECT * FROM datapoints WHERE id = '1lol'").fetchone()
print('\n1lol:', {k: row[k] for k in row.keys()})

Output:

CREATE TABLE datapoints (
            id TEXT PRIMARY KEY,
            release_date TEXT,
            resolution REAL,
            token_count INTEGER,
            chain_count INTEGER,
            molecule_types TEXT,
            template_count INTEGER
        )

180,975 indexed entries

1lol: {'id': '1lol', 'release_date': '2002-08-07', 'resolution': 1.9, 'token_count': None, 'chain_count': 6, 'molecule_types': 'LIGAND,PROTEIN', 'template_count': 0}

3. Composition of the corpus

One query, all 180,975 entries. Watch molecule_types: it is a single comma-joined string, not a relation, so = 'PROTEIN' means *protein and nothing else* and quietly drops the 114,974 entries that also carry a ligand.

print(f'{"molecule_types":<26s} {"entries":>9s}  {"mean res":>8s}')
for r in con.execute('''
        SELECT molecule_types, COUNT(*) AS n, AVG(resolution) AS res
          FROM datapoints GROUP BY molecule_types ORDER BY n DESC LIMIT 10'''):
    res = f'{r["res"]:.2f}' if r['res'] is not None else '-'
    print(f'{r["molecule_types"]:<26s} {r["n"]:>9,}  {res:>8s}')

exact = con.execute("SELECT COUNT(*) FROM datapoints WHERE molecule_types = 'PROTEIN'").fetchone()[0]
contains = con.execute("SELECT COUNT(*) FROM datapoints WHERE molecule_types LIKE '%PROTEIN%'").fetchone()[0]
missing = con.execute('SELECT COUNT(*) FROM datapoints WHERE resolution IS NULL').fetchone()[0]

print(f'\nprotein-only        : {exact:>9,}')
print(f'contains protein    : {contains:>9,}   <- use LIKE when you mean this')
print(f'resolution IS NULL  : {missing:>9,}   <- NMR etc; SQL comparisons drop these silently')

Output:

molecule_types               entries  mean res
LIGAND,PROTEIN               114,974      2.13
PROTEIN                       52,715      2.30
DNA,LIGAND,PROTEIN             3,883      2.54
LIGAND,PROTEIN,RNA             2,120      3.12
DNA,PROTEIN                    1,808      2.76
DNA,LIGAND                     1,145      1.96
PROTEIN,RNA                    1,019      3.39
DNA                              989      2.22
LIGAND,RNA                       912      2.40
RNA                              701      2.43

protein-only        :    52,715
contains protein    :   177,076   <- use LIKE when you mean this
resolution IS NULL  :    13,501   <- NMR etc; SQL comparisons drop these silently

4. The training cutoff, visible in the data

OpenFold3 uses the AlphaFold 3 cutoff: 2021-09-30. You do not have to take that on faith, it is a property of the index. The 2021 bar is short because the year is truncated three months early, and the maximum release date lands the day before.

years = con.execute('''
    SELECT substr(release_date, 1, 4) AS y, COUNT(*) AS n
      FROM datapoints WHERE release_date != '' GROUP BY y ORDER BY y''').fetchall()

peak = max(r['n'] for r in years)
for r in years[-16:]:
    print(f'{r["y"]}  {r["n"]:>6,}  {"#" * int(46 * r["n"] / peak)}')

lo, hi = con.execute(
    "SELECT MIN(release_date), MAX(release_date) FROM datapoints WHERE release_date != ''").fetchone()
print(f'\nrelease dates span {lo} to {hi}')
print('nothing after the cutoff, which is what makes later PDB entries a clean held-out test')

Output:

2006   6,366  #####################
2007   7,106  #######################
2008   6,862  ######################
2009   7,231  ########################
2010   7,687  #########################
2011   7,877  ##########################
2012   8,704  #############################
2013   9,235  ##############################
2014   9,453  ###############################
2015   9,176  ##############################
2016  10,734  ###################################
2017  10,966  ####################################
2018  11,071  ####################################
2019  11,363  #####################################
2020  13,795  ##############################################
...

5. From an index row to files on disk

id is the directory name under the structure prefix, so a row maps straight to a path and no listing is needed. Coverage is uneven though: the bucket holds 244,272 structure directories, the index covers 180,975 of them, and only 176,710 have an alignment directory. Check before you open.

STRUCT = MNT / 'pdb_training_set' / 'preprocessed_pdb_data' / 'standard' / 'structure_files'
MSAS = MNT / 'msas' / 'pdb_msas_completed'

def parts_for(entry, chain='A'):
    d = MSAS / f'{entry}_{chain}'
    return {
        'cif': STRUCT / entry / f'{entry}.cif',
        'fasta': STRUCT / entry / f'{entry}.fasta',
        # Protein chains ship cfdb_uniref30.a3m and *_hits.sto; nucleic-acid
        # chains ship rfam_hits.a3m / rnacentral_hits.sto instead.
        'a3m': next(iter(sorted(d.glob('*.a3m'))), None) if d.is_dir() else None,
        'sto': next(iter(sorted(d.glob('uniref90_hits.sto'))), None) if d.is_dir() else None,
    }

candidates = [r['id'] for r in con.execute('''
    SELECT id FROM datapoints
     WHERE molecule_types LIKE '%PROTEIN%' AND resolution IS NOT NULL
     ORDER BY id LIMIT 60''')]

target = None
print(f'{"entry":<7s} {"cif":>6s} {"fasta":>6s} {"a3m":>6s} {"sto":>6s}')
for entry in candidates[:12]:
    p = parts_for(entry)
    have = {k: (v is not None and v.exists()) for k, v in p.items()}
    print(f'{entry:<7s} {str(have["cif"]):>6s} {str(have["fasta"]):>6s} '
          f'{str(have["a3m"]):>6s} {str(have["sto"]):>6s}')
    if target is None and all(have.values()):
        target = entry

print(f'\nfully-equipped entry to work with: {target}')

Output:

entry      cif  fasta    a3m    sto
101m      True   True  False  False
102l      True   True   True   True
102m      True   True  False  False
103l      True   True   True   True
103m      True   True  False  False
104l      True   True   True   True
104m      True   True  False  False
105m      True   True  False  False
106m      True   True   True   True
107l      True   True   True   True
107m      True   True  False  False
108l      True   True   True   True

fully-equipped entry to work with: 102l

6. Read the structure

These are preprocessed mmCIF files with the _atom_site loop intact, so a short parser gets you real coordinates. No structural-biology dependency needed.

def read_atom_site(path):
    """Yield the _atom_site loop of an mmCIF as dicts."""
    fields, rows, in_loop = [], [], False
    with path.open('r', errors='replace') as fh:
        for line in fh:
            line = line.rstrip('\n')
            if line.startswith('_atom_site.'):
                fields.append(line.split('.', 1)[1].strip())
                in_loop = True
                continue
            if in_loop:
                if not line or line.startswith(('#', 'loop_', '_')):
                    break
                vals = line.split()
                if len(vals) == len(fields):
                    rows.append(dict(zip(fields, vals)))
    return rows

parts = parts_for(target)
atoms = read_atom_site(parts['cif'])
seq = ''.join(l.strip() for l in parts['fasta'].read_text().splitlines() if not l.startswith('>'))

meta = con.execute('SELECT * FROM datapoints WHERE id = ?', (target,)).fetchone()
print(f'{target}: {meta["resolution"]} A, {meta["chain_count"]} chains, '
      f'{meta["molecule_types"]}, released {meta["release_date"]}')
print(f'{len(atoms):,} atoms from {parts["cif"].stat().st_size / 1e3:.0f} KB of mmCIF')
print(f'chain sequence: {len(seq)} residues')
print(seq[:60] + '...')

Output:

102l: 1.74 A, 5 chains, LIGAND,PROTEIN, released 1993-10-31
1,323 atoms from 110 KB of mmCIF
chain sequence: 165 residues
MNIFEMLRIDEGLRLKIYKDTEGYYTIGIGHLLTKSPSLNAAAKSELDKAIGRNTNGVIT...

7. Two alignments for the same chain

Each msas/pdb_msas_completed/{entry}_{chain}/ directory carries several search results, and they are not interchangeable. uniref90_hits.sto is a UniRef90 search. cfdb_uniref30.a3m searches the expanded BFD (CFDB), which is heavily metagenomic.

Both parse into the same shape: strip to the query's match columns and compare each hit to the query. An a3m stores insertions as lowercase, a Stockholm file gaps the query directly, so the two parsers differ slightly but produce the same thing.

def parse_a3m(path, limit=20000):
    """a3m: uppercase and '-' are match columns, lowercase are insertions."""
    names, seqs, cur = [], [], []
    with path.open('r', errors='replace') as fh:
        for line in fh:
            line = line.rstrip('\n')
            if not line:
                continue
            if line.startswith('>'):
                if cur:
                    seqs.append(''.join(cur)); cur = []
                if len(names) >= limit:
                    break
                names.append(line[1:])
            else:
                cur.append(line)
    if cur and len(seqs) < len(names):
        seqs.append(''.join(cur))
    rows = [''.join(c for c in s if c.isupper() or c == '-') for s in seqs]
    width = len(rows[0])
    return names, [r for r in rows if len(r) == width]

def parse_sto(path):
    """Stockholm: interleaved 'name seq' blocks; keep the query's non-gap columns."""
    blocks, order = {}, []
    with path.open('r', errors='replace') as fh:
        for line in fh:
            line = line.rstrip('\n')
            if not line or line[0] == '#' or line.startswith('//'):
                continue
            parts_ = line.split(None, 1)
            if len(parts_) != 2:
                continue
            name, frag = parts_
            if name not in blocks:
                blocks[name] = []; order.append(name)
            blocks[name].append(frag.strip())
    rows = [(n, ''.join(blocks[n])) for n in order]
    keep = [i for i, c in enumerate(rows[0][1]) if c not in '-.']
    return ([n for n, _ in rows],
            [''.join(a[i] for i in keep).upper().replace('.', '-') for _, a in rows])

a3m_names, a3m_rows = parse_a3m(parts['a3m'])
sto_names, sto_rows = parse_sto(parts['sto'])

print(f'{parts["a3m"].name:<22s} {len(a3m_rows):>6,} sequences x {len(a3m_rows[0])} columns')
print(f'{parts["sto"].name:<22s} {len(sto_rows):>6,} sequences x {len(sto_rows[0])} columns')
print(f'\nboth align to the same {len(seq)}-residue query: '
      f'{a3m_rows[0] == sto_rows[0] == seq}')

Output:

cfdb_uniref30.a3m       1,148 sequences x 165 columns
uniref90_hits.sto       1,613 sequences x 165 columns

both align to the same 165-residue query: True
How close are the hits?

Percent identity of each hit to the query, over the positions the hit actually covers. This is the number that decides whether an alignment carries usable evolutionary signal.

def identity(query, hit):
    n = m = 0
    for a, b in zip(query, hit):
        if b == '-':
            continue
        n += 1
        m += (a == b)
    return m / n if n else 0.0

def summarize(label, rows):
    q = rows[0]
    ids = sorted(identity(q, r) for r in rows[1:])
    p = lambda f: ids[int(len(ids) * f)]
    print(f'{label:<22s} depth {len(ids):>6,}   median {p(0.5):.3f}   p90 {p(0.9):.3f}   '
          f'max {max(ids):.3f}   >=30%: {sum(i >= 0.3 for i in ids):>5,}   '
          f'>=50%: {sum(i >= 0.5 for i in ids):>4,}')
    return ids

print(f'identity of each hit to the {target} query sequence\n')
sto_ids = summarize(parts['sto'].name, sto_rows)
a3m_ids = summarize(parts['a3m'].name, a3m_rows)

print('\nidentity distribution')
for lo in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]:
    hi = lo + 0.1
    s = sum(lo <= i < hi for i in sto_ids)
    a = sum(lo <= i < hi for i in a3m_ids)
    print(f'  {lo:.1f}-{hi:.1f}   sto {s:>5,} {"#" * int(30 * s / len(sto_ids)):<30s} '
          f'a3m {a:>5,} {"#" * int(30 * a / len(a3m_ids))}')

Output:

identity of each hit to the 102l query sequence

uniref90_hits.sto      depth  1,612   median 0.350   p90 0.536   max 1.000   >=30%: 1,454   >=50%:  205
cfdb_uniref30.a3m      depth  1,147   median 0.105   p90 0.170   max 0.220   >=30%:     0   >=50%:    0

identity distribution
  0.0-0.1   sto     0                                a3m   497 ############
  0.1-0.2   sto     0                                a3m   611 ###############
  0.2-0.3   sto   166 ###                            a3m    39 #
  0.3-0.4   sto 1,041 ###################            a3m     0 
  0.4-0.5   sto   208 ###                            a3m     0 
  0.5-0.6   sto    81 #                              a3m     0
The consequence

Two files, same chain, same directory, and they describe different worlds. Per-column conservation (the fraction of non-gap sequences carrying the most common residue) is computed identically from each, and the answers do not agree. Take the deep metagenomic file alone and every position looks variable; the constrained core only shows up against close homologs.

Whichever file a pipeline happens to load is a modelling decision, not a detail.

from collections import Counter

def conservation(rows):
    q = rows[0]
    out = []
    for col in range(len(q)):
        chars = [r[col] for r in rows if r[col] != '-']
        out.append(Counter(chars).most_common(1)[0][1] / len(chars) if chars else 0.0)
    return out

cons_sto = conservation(sto_rows)
cons_a3m = conservation(a3m_rows)

print(f'mean per-column conservation')
print(f'  {parts["sto"].name:<22s} {sum(cons_sto) / len(cons_sto):.3f}')
print(f'  {parts["a3m"].name:<22s} {sum(cons_a3m) / len(cons_a3m):.3f}')

print(f'\npositions scoring above 0.8 (strongly constrained)')
print(f'  {parts["sto"].name:<22s} {sum(c > 0.8 for c in cons_sto):>4d}')
print(f'  {parts["a3m"].name:<22s} {sum(c > 0.8 for c in cons_a3m):>4d}')

top = sorted(range(len(cons_sto)), key=lambda i: -cons_sto[i])[:12]
print(f'\nmost conserved positions by UniRef90, with what the CFDB file says about each')
print(f'  {"pos":>4s} {"aa":>3s} {"uniref90":>9s} {"cfdb":>7s}')
for i in sorted(top):
    print(f'  {i+1:>4d} {seq[i]:>3s} {cons_sto[i]:>9.2f} {cons_a3m[i]:>7.2f}')

Output:

mean per-column conservation
  uniref90_hits.sto      0.468
  cfdb_uniref30.a3m      0.156

positions scoring above 0.8 (strongly constrained)
  uniref90_hits.sto        21
  cfdb_uniref30.a3m         1

most conserved positions by UniRef90, with what the CFDB file says about each
   pos  aa  uniref90    cfdb
    11   E      0.99    0.24
    12   G      0.96    0.36
    18   Y      0.99    0.27
    30   G      0.99    0.44
   108   G      0.99    0.41
...

Where to go from here

Run it

Open this notebook to run it, see the dataset page for the full description, or browse the full catalog.