春江暮客

春江暮客的个人学习分享网站

Protein Structure File Formats: PDB, mmCIF, BCIF, and Where PDF Fits

2026-10-09 Technology
Protein Structure File Formats: PDB, mmCIF, BCIF, and Where PDF Fits

You download a protein structure, and the folder contains a .pdb, a .cif, a .bcif, and a PDF report. Which file should go into your Python script? Start with PDBx/mmCIF for a new workflow, use BinaryCIF when your tools support its binary encoding, and export legacy PDB when a downstream program requires it.

This guide shows how the formats represent atoms, downloads the same example in three formats, and provides a small inspection script. PDF belongs alongside the coordinates as a readable report. References and examples were checked on October 9, 2026.

1. Choose a format for the job

File Representation Practical use
.pdb Fixed-width text records Compatibility with a program that expects legacy PDB
.cif / .mmcif Named fields and tables using PDBx/mmCIF A source file for new structure-processing workflows
.bcif BinaryCIF-encoded CIF categories and columns Transfer and processing with a compatible decoder
.pdf A formatted document Reading a paper, validation report, or format manual

The wwPDB made PDBx/mmCIF its standard archive format in 2014. Legacy PDB is frozen and cannot fully represent entries above its 62-chain or 99,999-ATOM-record limits. PDBx/mmCIF removes those fixed field-capacity limits. See wwPDB’s format policy.

For reproducibility, keep the downloaded original, source URL, download date, and SHA-256 checksum. Treat a converted file as a derived artifact.

2. Read one atom in PDB and mmCIF

The first atom record in the downloaded 4HHB PDB file is:

ATOM      1  N   VAL A   1      19.323  29.727  42.781  1.00 49.05           N

It describes nitrogen N in residue VAL, author chain A, residue number 1. Coordinates are in ångströms; 1.00 is occupancy and 49.05 is the isotropic temperature factor. PDB assigns meaning through column positions, so use a PDB parser rather than treating whitespace splitting as a general reader. The coordinate specification defines ATOM, HETATM, alternate locations, and model records.

Here is an invented, reduced mmCIF example showing the same coordinate values. It illustrates syntax and is not a complete structure file for the inspection script:

data_demo
loop_
_atom_site.id
_atom_site.label_atom_id
_atom_site.label_comp_id
_atom_site.auth_asym_id
_atom_site.auth_seq_id
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
1 N VAL A 1 19.323 29.727 42.781

loop_ introduces a table. Each tag names a column; values follow in that order. Quoted strings and semicolon-delimited multiline values make a simple line-by-line split unreliable. Preserve the special missing-value tokens: ? marks missing/unknown information; . indicates no appropriate value or an intentionally omitted value. See the mmCIF syntax guide.

The .cif extension identifies a broader format family. Check its data categories before assuming it contains protein coordinates.

3. Understand what BCIF changes

BinaryCIF keeps the CIF category-and-column organization, then encodes columns separately. Repeated strings, runs of repeated integers, and numeric differences can be represented compactly. MessagePack stores the resulting container. The format supports lossless and lossy encodings; precision depends on the encoder settings. See the BinaryCIF paper and format specification.

Consequently, .bcif and .cif.gz need different readers. Gzip decompresses text CIF; BinaryCIF needs column decoding. Renaming an extension performs neither operation. A MessagePack reader can inspect the container but does not automatically reconstruct coordinate arrays or missing-value masks.

For a ready-made visualization workflow, Mol* supports these structural representations. For conversions, its CIF-to-BCIF tool documentation explains encoding configuration and category filters. Check both before assuming an export preserved all fields.

4. Install and download an example

The following example uses uncompressed files for the 4HHB entry. It was executed with Python 3.14.7, Biopython 1.88, and msgpack 1.2.3. No GPU is required.

mkdir structure-formats-demo
cd structure-formats-demo
python3 -m venv .venv
source .venv/bin/activate
python -m pip install biopython==1.88 msgpack==1.2.3

curl -fL --retry 2 https://files.rcsb.org/download/4hhb.pdb -o 4hhb.pdb
curl -fL --retry 2 https://files.rcsb.org/download/4hhb.cif -o 4hhb.cif
curl -fL --retry 2 https://models.rcsb.org/4hhb.bcif -o 4hhb.bcif

These endpoints follow RCSB’s download documentation. PDB availability varies by entry. A PDF validation report helps assess model quality, but its pages do not replace an atomic coordinate table.

5. Inspect the files with Python

Download inspect_structure.py, or save this complete script under that name:

"""Inspect text structures or BinaryCIF container metadata without editing."""
import argparse
import hashlib
import json
from pathlib import Path

import msgpack
from Bio.PDB import MMCIFParser, PDBParser
from Bio.PDB.MMCIF2Dict import MMCIF2Dict


def inspect(path):
    suffix = path.suffix.lower()
    report = {"file": path.name, "bytes": path.stat().st_size,
              "sha256": hashlib.sha256(path.read_bytes()).hexdigest()}
    if suffix == ".bcif":
        container = msgpack.unpackb(path.read_bytes(), raw=False)
        report["binarycif_version"] = container["version"]
        report["blocks"] = [
            {"header": block["header"],
             "atom_site_tables": [
                 {"rows": category["rowCount"],
                  "columns": [column["name"] for column in category["columns"]]}
                 for category in block["categories"]
                 if category["name"] == "_atom_site"]}
            for block in container["dataBlocks"]]
        return report  # Encoded column values and masks are NOT decoded here.
    if suffix == ".pdb":
        parser = PDBParser(PERMISSIVE=False)
    elif suffix == ".cif":
        parser = MMCIFParser(auth_chains=True, auth_residues=True)
    else:
        raise ValueError("Use an uncompressed .pdb, .cif, or .bcif file")
    structure = parser.get_structure(path.stem, str(path))
    report["models"] = [
            {"parser_model_serial": int(model.serial_num),
             "chain_ids": [chain.id for chain in model],
             "selected_atom_objects": sum(1 for _ in model.get_atoms())}
            for model in structure
        ]
    if suffix == ".cif":
        table = MMCIF2Dict(str(path))
        pairs = sorted(set(zip(table["_atom_site.label_asym_id"],
                               table["_atom_site.auth_asym_id"])))
        report["atom_site_rows"] = len(table["_atom_site.id"])
        report["label_to_auth_chain_pairs"] = pairs
    return report


def main():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument("files", nargs="+", type=Path)
    args = cli.parse_args()
    try:
        reports = [inspect(path) for path in args.files]
    except Exception as error:
        cli.exit(1, f"Cannot inspect structure: {error}\n")
    print(json.dumps(reports, indent=2))


if __name__ == "__main__":
    main()

Run:

python inspect_structure.py --help
python inspect_structure.py 4hhb.pdb 4hhb.cif 4hhb.bcif > inspection.json

For text files, the script uses Biopython’s structure parsers and reads raw mmCIF tags through MMCIF2Dict. See Biopython’s structure documentation. For BCIF, it reports container version, atom-table row counts, and column names; it does not decode binary coordinate values. The script reads files and writes JSON to standard output.

Selected results from the downloaded files:

File Bytes Inspection result
4hhb.pdb 473,850 1 parsed model, author chains A–D, 4,779 selected atom objects
4hhb.cif 772,198 1 parsed model, author chains A–D, 4,779 atom-site rows
4hhb.bcif 552,871 BinaryCIF 0.3.0 container, 4,779 atom-site rows

These are measurements of one download, not a speed benchmark or a universal size ranking. Files may be revised. Matching row counts do not prove identical coordinates or metadata. Biopython’s selected atom objects can also differ from raw atom-site rows when alternate conformations exist. The parser_model_serial is parser bookkeeping: this PDB example reports 0, while mmCIF reports the explicit model number 1.

6. Check identifiers before joining or converting

The JSON report contains 14 distinct mmCIF label_asym_id values mapped to four auth_asym_id values. For example, E → A and K → A occur alongside A → A. Inspect the corresponding rows to distinguish protein, ligand, and solvent instances.

label_asym_id identifies a molecular instance; auth_asym_id preserves the author/PDB chain naming. Likewise, label_seq_id and auth_seq_id use different residue-number conventions. The PDBx/mmCIF user guide explains both namespaces. Set Biopython’s auth_chains and auth_residues explicitly, as above, and keep identifier mappings when joining results.

Before accepting a conversion, compare:

  1. Model count and the intended biological assembly.
  2. Chain mapping, residue numbering, and insertion codes.
  3. Atom identities, alternate-location labels, occupancy, and coordinates with a stated tolerance.
  4. Ligands, waters, connections, and metadata required by your analysis.

Apply these checks to the same selected atoms and models. A successful parse proves readability, not full preservation. An entry coordinate file and a generated biological assembly can contain different molecular copies; the extension alone does not choose the assembly.

7. Fix common problems

Symptom Concrete next step
Python cannot import Bio or msgpack Activate the environment and repeat the python -m pip install command above.
The script rejects .gz input Download the uncompressed URL used above, or decompress a separate copy first.
BCIF looks unreadable in a text editor Use a BinaryCIF-capable tool; do not rename it to .cif.
Chain IDs differ across tools Check label_asym_id versus auth_asym_id and the parser settings.
A large structure has no PDB download Fetch mmCIF and use software that accepts it.
Biopython warns that a chain is discontinuous Inspect the reported rows. In this example, later ligand/solvent records reuse author chain IDs; the warning alone does not prove a broken peptide.

Summary

Keep the original mmCIF and its provenance as your starting point. Use BCIF where a compatible decoder helps your workflow, and verify any PDB export against the information your analysis needs. Keep PDF reports with the coordinates so you can review the supporting validation.

标签

1024 ablang adsense agents.md ai ai-agent ai-agents ai-seo algorithm amp antibodies apparmor argparse automation background backup bash batch-processing binarycif bioinformatics biopython blockchain boltz bootstrapping boxes bubblewrap c-index cca cdn checkpoint cli cloudflare codex cofoldarena copy cpu monitoring cron csv cuda curl data-leakage data-processing data-quality data-validation datascience datavisualization datetime debugging decimal deployment desktop-app devtools disk-space disown dns docker dovecot download economics electron encoding esm esm2 esm3 esmc esmfold2 fable faceswap fasta fastmcp faulthandler ffmpeg file-descriptors file-io flashppi flask folium frontend game generator git github-actions google google-research grep gzip harness hls html http hugo imports indexnow javascript jev json jsonl just k-means kaggle langfuse leecode linux list litellm llm llms.txt logging logs lollipop lsof m3u8 machine-learning macos manacher matplotlib mcp mirror mmcif model-evaluation monitoring mp3 mp4 mpnn multiomics mutation mysql nanobert nanobodies networkx nginx normalize numpy ollama omegatherm pandas password pathlib pdb pep-723 phaser pillow pip postfix preprocessing print probability protein-alignment protein-design protein-embeddings protein-interactions protein-language-models protein-stability protein-structure proxy pydantic pyecharts pyqt python python3 r raincloud reproducibility requests reservoir-sampling rfoptimization rg ripgrep rosettafold3 roundcube rrsi rsi rsync s-tui sampling scale scikit-learn scrapy screen seaborn security seo sequence-identity sha256 shell signals sklearn socket solana somaticsignatures spl sqlite ssh standardize static-site subprocess symlink sysadmin system-one tarfile tcp tensorflow tkinter tls toml trade tron tronpy troubleshooting turtle typesafe-ai ubuntu unicode usdt utf-8 uv vhhbert vite wallet webp wordcloud wordpress workflow yaml zipfile zoneinfo 迅雷解析

友情链接

其它