Alterlab pdb

From AlterLab-IEU/AlterLab-Academic-Skills · View interactive version

Alterlab pdb is an AI agent skill from the GitHub repository AlterLab-IEU/AlterLab-Academic-Skills. Access the RCSB Protein Data Bank (PDB) for EXPERIMENTALLY determined 3D structures (X-ray, cryo-EM, NMR) of proteins and nucleic acids — searching by text, sequence, or structure similarity and downloading coordinates in PDB/mmCIF format with metadata. Use when retrieving a structure by PDB ID, run

How to use this skill

Skill file

PDB Database

Overview

RCSB PDB is the worldwide repository for 3D structural data of biological macromolecules. Search for structures, retrieve coordinates and metadata, perform sequence and structure similarity searches across ~260,000 experimentally determined entries (2026-09) plus computed structure models (CSMs) imported from AlphaFold DB and ModelArchive.

Scripts

scripts/query_pdb.py — RCSB Search + Data + file APIs (stdlib only, JSON to stdout):

python scripts/query_pdb.py search hemoglobin --rows 25     # full-text search (entry IDs)
python scripts/query_pdb.py similar 4HHB --assembly 1       # 3D shape search (or --chain A)
python scripts/query_pdb.py entry 4HHB                      # entry metadata
python scripts/query_pdb.py download 4HHB --format cif      # download coordinates

similar sends the same query as rcsb-api's StructSimilarityQuery and prints it with the

hits (2026-11-04: 4HHB assembly 1 → 1,408 entries either way).

Say how it was retrieved. End every answer with a short "How this was retrieved" line: the

query a reader can re-run (the rcsbapi call such as `StructSimilarityQuery(entry_id="4HHB",

assembly_id="1"), or the Search API JSON / query_pdb.py` command) with its key parameters,

the total_count, and the retrieval date. Give the query itself, not a temporary script path.

When to Use This Skill

This skill should be used when:

Does NOT Trigger

| Scenario | Use Instead |

|----------|-------------|

| AI-predicted structure for a protein without experimental data | alterlab-alphafold-db |

| Protein sequence, function annotation, or accession mapping | alterlab-uniprot |

| Domain/family classification of a protein | alterlab-interpro |

| Predicting a new complex or co-folding structure | alterlab-boltz |

| Docking a ligand into a structure | alterlab-diffdock |

Hand-off rule. When the request matches a row above, open your answer by naming that skill by its exact id (for example alterlab-alphafold-db) and saying in one line why it fits better, then stop applying this skill's procedure. Name it even when you also need to ask for missing input. If only part of the request is out of scope, name the skill for that part and do only the in-scope part. A brief general pointer is fine; the named skill does the work.

Core Capabilities

1. Searching for Structures

Find PDB entries using various search criteria:

Text Search: Search by protein name, keywords, or descriptions

from rcsbapi.search import TextQuery
query = TextQuery("hemoglobin")
results = list(query())
print(f"Found {len(results)} structures")

Attribute Search: Query specific properties (organism, resolution, method, etc.)

from rcsbapi.search import AttributeQuery
from rcsbapi.search import search_attributes as attrs

# Find human protein structures (idiomatic form — recommended)
query = attrs.rcsb_entity_source_organism.scientific_name == "Homo sapiens"
results = list(query())

# OR explicit AttributeQuery with a dotted-path STRING (not the Attr object):
query = AttributeQuery(
    attribute="rcsb_entity_source_organism.scientific_name",
    operator="exact_match",
    value="Homo sapiens",
)
results = list(query())

Sequence Similarity: Find structures similar to a given sequence

from rcsbapi.search import SeqSimilarityQuery

query = SeqSimilarityQuery(
    value="MTEYKLVVVGAGGVGKSALTIQLIQNHFVDEYDPTIEDSYRKQVVIDGETCLLDILDTAGQEEYSAMRDQYMRTGEGFLCVFAINNTKSFEDIHHYREQIKRVKDSEDVPMVLVGNKCDLPSRTVDTKQAQDLARSYGIPFIETSAKTRQGVDDAFYTLVREIRKHKEKMSKDGKKKKKKSKTKCVIM",
    evalue_cutoff=0.1,
    identity_cutoff=0.9,
    sequence_type="protein"
)
results = list(query())

Structure Similarity: Find structures with similar 3D geometry

from rcsbapi.search import StructSimilarityQuery

# structure_search_type is "entry_id" (default), "file_url", or "file_upload";
# pass assembly_id or chain_id to pick what is compared ("entry"/"chain"/"assembly"
# are not valid search types and return HTTP 400). Embeddings-based since rcsb-api 1.6:
# hits above ptmscore_cutoff (predicted TM-score, default 0.8); similarity_type "local"
# (default) or "global"; the old BioZernike `operator` is deprecated.
query = StructSimilarityQuery(
    entry_id="4HHB",   # Hemoglobin
    assembly_id="1",   # or chain_id="A"
)
results = list(query())

Combining Queries: Use logical operators to build complex searches

from rcsbapi.search import search_attributes as attrs

# High-resolution human proteins
query1 = attrs.rcsb_entity_source_organism.scientific_name == "Homo sapiens"
query2 = attrs.rcsb_entry_info.resolution_combined < 2.0
combined_query = query1 & query2  # AND operation
results = list(combined_query())

2. Retrieving Structure Data

Access detailed information about specific PDB entries:

Basic Entry Information:

from rcsbapi.data import DataQuery

# Get entry-level data
query = DataQuery(
    input_type="entries",
    input_ids=["4HHB"],
    return_data_list=["struct.title", "exptl.method"],
)
data = query.exec()  # synchronous; returns a dict
entry = data["data"]["entries"][0]
print(entry["struct"]["title"])
print(entry["exptl"][0]["method"])

Polymer Entity Information:

from rcsbapi.data import DataQuery

# Get protein/nucleic acid information
query = DataQuery(
    input_type="polymer_entities",
    input_ids=["4HHB_1"],
    return_data_list=["entity_poly.pdbx_seq_one_letter_code"],
)
data = query.exec()
entity = data["data"]["polymer_entities"][0]
print(entity["entity_poly"]["pdbx_seq_one_letter_code"])

Building Queries (GraphQL under the hood):

from rcsbapi.data import DataQuery

# DataQuery builds the GraphQL query for you from input_type/input_ids/return_data_list;
# there is no separate fetch(query_type="graphql", ...) entry point.
query = DataQuery(
    input_type="entries",
    input_ids=["4HHB"],
    return_data_list=[
        "struct.title",
        "exptl.method",
        "rcsb_entry_info.resolution_combined",
        "rcsb_entry_info.deposited_atom_count",
    ],
)
# Inspect the auto-generated GraphQL / open it in the editor:
print(query.get_editor_link())
data = query.exec()

3. Downloading Structure Files

Retrieve coordinate files in various formats:

Download Methods:

Example Download:

import requests

pdb_id = "4HHB"

# Download PDB format
pdb_url = f"https://files.rcsb.org/download/{pdb_id}.pdb"
response = requests.get(pdb_url)
with open(f"{pdb_id}.pdb", "w") as f:
    f.write(response.text)

# Download mmCIF format
cif_url = f"https://files.rcsb.org/download/{pdb_id}.cif"
response = requests.get(cif_url)
with open(f"{pdb_id}.cif", "w") as f:
    f.write(response.text)

4. Working with Structure Data

Common operations with retrieved structures:

Parse and Analyze Coordinates:

Use BioPython or other structural biology libraries to work with downloaded files:

from Bio.PDB import PDBParser

parser = PDBParser()
structure = parser.get_structure("protein", "4HHB.pdb")

# Iterate through atoms
for model in structure:
    for chain in model:
        for residue in chain:
            for atom in residue:
                print(atom.get_coord())

Extract Metadata:

from rcsbapi.data import DataQuery

# Get experimental details
query = DataQuery(
    input_type="entries",
    input_ids=["4HHB"],
    return_data_list=[
        "rcsb_entry_info.resolution_combined",
        "exptl.method",
        "rcsb_accession_info.deposit_date",
    ],
)
data = query.exec()["data"]["entries"][0]

resolution = data.get("rcsb_entry_info", {}).get("resolution_combined")
method = data.get("exptl", [{}])[0].get("method")
deposition_date = data.get("rcsb_accession_info", {}).get("deposit_date")

print(f"Resolution: {resolution[0] if resolution else None} Å")  # resolution_combined is a list
print(f"Method: {method}")
print(f"Deposited: {deposition_date}")

5. Batch Operations

Process multiple structures efficiently:

from rcsbapi.data import DataQuery

pdb_ids = ["4HHB", "1MBN", "1GZX"]  # Hemoglobin, myoglobin, etc.

# A single DataQuery can fetch all entries at once. Use fully qualified paths:
# source organism lives on polymer entities, not on the entry.
query = DataQuery(
    input_type="entries",
    input_ids=pdb_ids,
    return_data_list=[
        "rcsb_id",
        "struct.title",
        "rcsb_entry_info.resolution_combined",
        "polymer_entities.rcsb_entity_source_organism.scientific_name",
    ],
)

results = {}
for data in query.exec()["data"]["entries"]:
    pdb_id = data["rcsb_id"]
    resolution = (data.get("rcsb_entry_info") or {}).get("resolution_combined") or [None]
    entities = data.get("polymer_entities") or [{}]
    organisms = (entities[0].get("rcsb_entity_source_organism") or [{}])
    results[pdb_id] = {
        "title": data["struct"]["title"],
        "resolution": resolution[0],
        "organism": organisms[0].get("scientific_name"),
    }

# Display results
for pdb_id, info in results.items():
    print(f"\n{pdb_id}: {info['title']}")
    print(f"  Resolution: {info['resolution']} Å")
    print(f"  Organism: {info['organism']}")

Python Package Installation

Use the official RCSB PDB Python API client (rcsb-api, current major version

1.x; examples here target >=1.7) without an install step — uv resolves it for the run:

uv run --with "rcsb-api>=1.7" python search.py

(Checked 2026-10-23: resolves to rcsb-api 1.7.3; a SeqSimilarityQuery for the KRAS4B

G-domain at identity 0.9 / e-value 0.1 returned 814 entries, the same as the raw Search API.)

The rcsb-api package provides unified access to both Search and Data APIs through

the rcsbapi.search and rcsbapi.data modules. (The older rcsbsearchapi package

is superseded by rcsb-api and its import rcsbsearchapi path is gone — prefer

rcsb-api for new code.)

The scripts/query_pdb.py helper needs none of this — it hits the public REST APIs

with only the Python standard library.

Common Use Cases

Drug Discovery

Protein Engineering

Structural Biology Research

Education and Visualization

Key Concepts

PDB ID: Unique 4-character identifier (e.g., "4HHB") for each structure entry. AlphaFold and ModelArchive entries start with "AF_" or "MA_" prefixes.

mmCIF/PDBx: Modern file format that uses key-value structure, replacing legacy PDB format for large structures.

Biological Assembly: The functional form of a macromolecule, which may contain multiple copies of chains from the asymmetric unit.

Resolution: Measure of detail in crystallographic structures (lower values = higher detail). Typical range: 1.5-3.5 Å for high-quality structures.

Entity: A unique molecular component in a structure (protein chain, DNA, ligand, etc.).

Resources

This skill includes reference documentation in the references/ directory:

references/api_reference.md

Comprehensive API documentation covering:

Use this reference when you need in-depth information about API capabilities, complex query construction, or detailed data schema information.

Additional Resources

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.