mcpField
A
alphafold-database-access

alphafold-database-access

github.com/jaechang-hits数据与数据库38473 次安装6 天前更新
代码仓库

关于 alphafold-database-access

alphafold-database-access 是通过 BioPython、REST API 和 Google Cloud 查询及下载 AlphaFold DB 蛋白质结构的技能,面向结构生物学分析。它还涵盖 pLDDT 与 PAE 置信度评估及批量蛋白质组数据获取。

主要功能

  1. 01按 UniProt 编号检索预测结构
  2. 02下载 mmCIF、PDB 等结构文件
  3. 03分析 pLDDT 与 PAE 置信度
  4. 04通过 Google Cloud 批量获取数据
  5. 05解析结构并提取区域

适用场景

  1. 01为缺少实验结构的蛋白构建模型
  2. 02筛选高置信度区域用于对接分析
  3. 03批量下载指定物种的蛋白质组预测
  4. 04比较预测结构与实验 PDB 结构

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jaechang-hits/sciagent-skills --skill alphafold-database-access

安装后在 Claude Code 中输入/alphafold-database-access确认已加载。

附带文件references/api_schemas_reference.md

详细介绍

AlphaFold 数据库访问

概述

AlphaFold DB 是一个公开数据库,收录了由 AI 预测的超过 2 亿种蛋白质的 3D 结构,由 DeepMind 和 EMBL-EBI 维护。可通过 BioPython 或 REST API 获取预测结果,下载多种格式的坐标文件,分析置信度指标,并通过 Google Cloud 获取蛋白质组批量数据集。

适用场景

  • 根据 UniProt 登录号检索 AI 预测的蛋白质结构
  • 下载 PDB/mmCIF 坐标文件,用于结构分析或对接
  • 分析预测置信度(逐残基 pLDDT、结构域级 PAE)
  • 通过 Google Cloud 批量下载整个蛋白质组的预测结果
  • 将预测结构与实验 PDB 结构进行比较
  • 为缺少实验数据的蛋白质构建结构模型
  • 为药物发现识别高置信度结合位点
  • 仅需要实验结构时 → 直接使用 PDB
  • 运行 AlphaFold 预测时 → 使用 ColabFold 或本地 AlphaFold

前置条件

# Core (BioPython for structure access)
pip install biopython requests numpy matplotlib

# Optional: Google Cloud for bulk access
pip install google-cloud-bigquery google-cloud-storage

快速入门

from Bio.PDB import alphafold_db, MMCIFParser
import requests, numpy as np

# 1. Get prediction for a protein
uniprot_id = "P00520"  # ABL1 kinase
predictions = list(alphafold_db.get_predictions(uniprot_id))
af_id = predictions[0]['entryId']  # AF-P00520-F1

# 2. Download structure
cif_file = alphafold_db.download_cif_for(predictions[0], directory="./structures")

# 3. Check confidence
conf = requests.get(f"https://alphafold.ebi.ac.uk/files/{af_id}-confidence_v4.json").json()
scores = conf['confidenceScore']
print(f"Mean pLDDT: {np.mean(scores):.1f}, High-conf residues: {sum(1 for s in scores if s > 90)}/{len(scores)}")

核心 API

1. 获取预测结果

BioPython(推荐用于单个蛋白质):

from Bio.PDB import alphafold_db

# Get prediction metadata
predictions = list(alphafold_db.get_predictions("P00520"))
pred = predictions[0]
print(f"AlphaFold ID: {pred['entryId']}")
print(f"Gene: {pred['gene']}, Species: {pred['organismScientificName']}")

# Get Structure objects directly
structures = list(alphafold_db.get_structural_models_for("P00520"))

REST API(用于元数据或集成):

import requests

uniprot_id = "P00520"
url = f"https://alphafold.ebi.ac.uk/api/prediction/{uniprot_id}"
response = requests.get(url)
data = response.json()

# Response includes download URLs for all file types
pred = data[0]
print(f"CIF: {pred['cifUrl']}")
print(f"PDB: {pred['pdbUrl']}")
print(f"PAE: {pred['paeDocUrl']}")

3D-Beacons 联合 API(查询多个结构提供方):

url = f"https://www.ebi.ac.uk/pdbe/pdbe-kb/3dbeacons/api/uniprot/summary/{uniprot_id}.json"
data = requests.get(url).json()
af_structures = [s for s in data['structures'] if s['provider'] == 'AlphaFold DB']
2. 下载结构文件
import requests

af_id = "AF-P00520-F1"
version = "v4"
base = "https://alphafold.ebi.ac.uk/files"

# mmCIF (recommended — full metadata, supports large structures)
cif = requests.get(f"{base}/{af_id}-model_{version}.cif")
with open(f"{af_id}.cif", "w") as f:
    f.write(cif.text)

# PDB format (legacy — limited to 99,999 atoms)
pdb = requests.get(f"{base}/{af_id}-model_{version}.pdb")
with open(f"{af_id}.pdb", "wb") as f:
    f.write(pdb.content)

# Confidence JSON (per-residue pLDDT scores)
conf = requests.get(f"{base}/{af_id}-confidence_{version}.json").json()

# PAE matrix JSON (inter-residue confidence)
pae = requests.get(f"{base}/{af_id}-predicted_aligned_error_{version}.json").json()
3. 分析置信度指标

pLDDT(逐残基置信度,0–100):

import numpy as np

conf_url = f"https://alphafold.ebi.ac.uk/files/{af_id}-confidence_v4.json"
conf = requests.get(conf_url).json()
scores = conf['confidenceScore']

# Classify residues by confidence
very_high = sum(1 for s in scores if s > 90)
high = sum(1 for s in scores if 70 < s <= 90)
low = sum(1 for s in scores if 50 < s <= 70)
very_low = sum(1 for s in scores if s <= 50)
print(f"Very high (>90): {very_high}, High (70-90): {high}, Low (50-70): {low}, Very low (<50): {very_low}")

PAE(预测对齐误差)可视化:

import matplotlib.pyplot as plt

pae_url = f"https://alphafold.ebi.ac.uk/files/{af_id}-predicted_aligned_error_v4.json"
pae = requests.get(pae_url).json()
pae_matrix = np.array(pae['distance'])

plt.figure(figsize=(10, 8))
plt.imshow(pae_matrix, cmap='viridis_r', vmin=0, vmax=30)
plt.colorbar(label='PAE (Å)')
plt.title(f'Predicted Aligned Error: {af_id}')
plt.xlabel('Residue')
plt.ylabel('Residue')
plt.savefig(f'{af_id}_pae.png', dpi=300, bbox_inches='tight')
# Low PAE (<5 Å) = confident relative positioning; >15 Å = uncertain domain arrangement
4. 批量数据访问(Google Cloud)
# List available data
gsutil ls gs://public-datasets-deepmind-alphafold-v4/

# Download entire proteome by taxonomy ID
gsutil -m cp gs://public-datasets-deepmind-alphafold-v4/proteomes/proteome-tax_id-9606-*_v4.tar .

# Download accession index
gsutil cp gs://public-datasets-deepmind-alphafold-v4/accession_ids.csv .

BigQuery 元数据查询:

from google.cloud import bigquery

client = bigquery.Client()
query = """
SELECT entryId, uniprotAccession, gene, organismScientificName,
       globalMetricValue, fractionPlddtVeryHigh
FROM `bigquery-public-data.deepmind_alphafold.metadata`
WHERE organismScientificName = 'Homo sapiens'
  AND fractionPlddtVeryHigh > 0.8
  AND isReviewed = TRUE
LIMIT 100
"""
df = client.query(query).to_dataframe()
print(f"Found {len(df)} high-confidence human proteins")
5. 结构解析与分析
from Bio.PDB import MMCIFParser
import numpy as np
from scipy.spatial.distance import pdist, squareform

parser = MMCIFParser(QUIET=True)
structure = parser.get_structure("protein", f"{af_id}-model_v4.cif")

# Extract alpha-carbon coordinates
coords, plddt_scores = [], []
for model in structure:
    for chain in model:
        for residue in chain:
            if 'CA' in residue:
                coords.append(residue['CA'].get_coord())
                plddt_scores.append(residue['CA'].get_bfactor())  # pLDDT stored as B-factor

coords = np.array(coords)
print(f"Residues: {len(coords)}, Mean pLDDT: {np.mean(plddt_scores):.1f}")

# Contact map (Cα-Cα < 8 Å)
dist_matrix = squareform(pdist(coords))
contacts = np.where((dist_matrix > 0) & (dist_matrix < 8))
print(f"Contacts: {len(contacts[0]) // 2}")

核心概念

置信度解读
指标范围解读适用场景
pLDDT >90非常高主链和侧链均可靠详细分析、对接
pLDDT 70–90高主链总体可靠折叠分析、结构域识别
pLDDT 50–70低谨慎使用可能具有柔性或无序
pLDDT <50非常低可能无序从分析中排除
PAE <5 Å可信结构域间相对位置可靠多结构域组装
PAE 5–10 Å中等排布不确定将各结构域独立处理
PAE >15 Å不确定结构域可能会移动不要相信其相对方向
AlphaFold ID 格式

格式:AF-{UniProt_accession}-F{fragment_number}(例如,AF-P00520-F1)。大型蛋白质可能会拆分为多个片段(F1、F2、……)。当前数据库版本:v4 — 所有文件 URL 均须包含版本后缀。

文件类型
文件URL 后缀格式用途
模型坐标-model_v4.cifmmCIF结构分析(推荐)
模型坐标-model_v4.pdbPDB旧版工具(<99,999 个原子)
模型坐标-model_v4.bcif二进制 CIF压缩(体积约小 70%)
置信度-confidence_v4.jsonJSON逐残基 pLDDT 数组
对齐误差-predicted_aligned_error_v4.jsonJSONN×N PAE 矩阵
PAE 图像-predicted_aligned_error_v4.pngPNG快速目视评估

常见工作流

工作流 1:单个蛋白质结构分析
from Bio.PDB import alphafold_db, MMCIFParser
import requests, numpy as np

uniprot_id = "P04637"  # p53 tumor suppressor

# Retrieve and download
predictions = list(alphafold_db.get_predictions(uniprot_id))
cif_file = alphafold_db.download_cif_for(predictions[0], directory="./structures")
af_id = predictions[0]['entryId']

# Parse structure
parser = MMCIFParser(QUIET=True)
structure = parser.get_structure("p53", cif_file)

# Extract pLDDT from B-factors
plddt = [r['CA'].get_bfactor() for m in structure for c in m for r in c if 'CA' in r]
print(f"Length: {len(plddt)}, Mean pLDDT: {np.mean(plddt):.1f}")

# Identify high-confidence regions for docking
high_conf_regions = [(i+1, s) for i, s in enumerate(plddt) if s > 90]
print(f"High-confidence residues: {len(high_conf_regions)}/{len(plddt)}")
工作流 2:批量处理蛋白质
from Bio.PDB import alphafold_db
import requests, numpy as np, pandas as pd, time

uniprot_ids = ["P00520", "P12931", "P04637", "P38398"]
results = []

for uid in uniprot_ids:
    try:
        preds = list(alphafold_db.get_predictions(uid))
        if not preds:
            continue
        af_id = preds[0]['entryId']
        conf = requests.get(f"https://alphafold.ebi.ac.uk/files/{af_id}-confidence_v4.json").json()
        scores = conf['confidenceScore']
        results.append({
            'uniprot': uid, 'alphafold_id': af_id,
            'length': len(scores), 'mean_plddt': np.mean(scores),
            'frac_high_conf': sum(1 for s in scores if s > 90) / len(scores)
        })
        time.sleep(0.2)  # Rate limit: 100-200ms between requests
    except Exception as e:
        print(f"Error {uid}: {e}")

df = pd.DataFrame(results)
print(df.to_string(index=False))

关键参数

参数模块默认值范围作用
uniprot_id所有—UniProt 登录号主要查询标识符
version下载v4v1–v4数据库版本(始终使用最新版本)
directoryBioPython"."路径下载目标位置
QUIETMMCIFParserFalsebool禁止解析器警告
vmin/vmaxPAE 图0/30ÅPAE 色图范围
taxonomy_idGCS 批量处理—NCBI 分类 ID下载蛋白质组的物种
fractionPlddtVeryHighBigQuery—0.0–1.0按高置信度比例筛选
并发请求数API—≤10API 请求的最大并行数
请求间隔API—100–200ms连续请求之间的延迟

最佳实践

  1. 单个蛋白质使用 BioPython,批量处理使用 Google Cloud — 对于超过 100 个蛋白质,单独通过 API 下载速度很慢;使用 GCS 并行下载快几个数量级
  2. 下游分析前始终检查 pLDDT — 低置信度区域(pLDDT <50)可能是无序区域,应从对接、接触分析或结合位点预测中排除
  3. 反模式 — 对所有区域一视同仁:AlphaFold 预测缺少配体、PTM、辅因子和多链上下文。高 pLDDT 并不保证功能准确性
  4. 在本地缓存下载的文件 — 避免重复下载相同结构;每个版本的 AlphaFold 文件都是静态的
  5. 多结构域蛋白质使用 PAE — pLDDT 告诉你每个残基的置信度,而 PAE 则揭示结构域的相对取向是否可靠。低结构域间 PAE(<5 Å)= 相信其排列;高 PAE(>15 Å)= 将结构域视为彼此独立
  6. 在可复现的分析中固定数据库版本 — 在 URL 中加入 _v4,并记录所用版本

常见方案

方案 1:按物种下载蛋白质组
import subprocess

def download_proteome(taxonomy_id: int, output_dir: str = "./proteomes"):
    """Download all AlphaFold predictions for a species via GCS."""
    if not isinstance(taxonomy_id, int):
        raise ValueError("taxonomy_id must be an integer")
    pattern = f"gs://public-datasets-deepmind-alphafold-v4/proteomes/proteome-tax_id-{taxonomy_id}-*_v4.tar"
    subprocess.run(["gsutil", "-m", "cp", pattern, f"{output_dir}/"], check=True)

# Human (9606), E. coli (83333), Mouse (10090)
download_proteome(9606)
方案 2:提取高置信度区域
def extract_high_conf_residues(plddt_scores, threshold=90):
    """Extract contiguous high-confidence regions."""
    regions, start = [], None
    for i, score in enumerate(plddt_scores):
        if score > threshold and start is None:
            start = i
        elif score <= threshold and start is not None:
            regions.append((start + 1, i, i - start))  # 1-indexed
            start = None
    if start is not None:
        regions.append((start + 1, len(plddt_scores), len(plddt_scores) - start))
    return regions

# Usage: regions = extract_high_conf_residues(plddt_scores)
# Returns: [(start_res, end_res, length), ...]
方案 3:基于 PAE 的结构域分割
import numpy as np

def segment_domains(pae_matrix, threshold=10.0):
    """Simple domain segmentation from PAE matrix."""
    n = pae_matrix.shape[0]
    # Average PAE for each residue pair -> symmetric
    sym_pae = (pae_matrix + pae_matrix.T) / 2
    # Cluster: residues with low mutual PAE are in the same domain
    domains, current_domain = [0] * n, 0
    for i in range(1, n):
        if sym_pae[i-1, i] > threshold:
            current_domain += 1
        domains[i] = current_domain
    return domains

故障排除

问题原因解决方案
API 返回 404 Not Found此 UniProt ID 没有 AlphaFold 预测检查该蛋白质是否收录于 AlphaFold DB;部分生物未覆盖
429 Too Many Requests超出速率限制在请求之间添加 time.sleep(0.2);批量处理时使用 GCS
预测列表为空数据库中不存在该 UniProt ID在 alphafold.ebi.ac.uk 上验证 ID;尝试规范异构体
大型蛋白质被拆分为片段蛋白质超过 2700 个残基检查所有片段(F1、F2、...);如有需要,手动拼接
pLDDT 值全部偏低(<50)内在无序蛋白质属于预期情况;对 IDP 而言,结构预测不可靠
PAE 矩阵不对称PAE[i][j] ≠ PAE[j][i] 是设计使然PAE 衡量以残基 i 为基准对齐时的误差;聚类时可将其对称化
ModuleNotFoundError: Bio.PDB.alphafold_dbBioPython 版本过旧升级:pip install --upgrade biopython>=1.80
GCS 下载失败未配置 gsutil运行 gcloud auth login,或对公开数据使用匿名访问
超出 BigQuery 配额免费层限制(1 TB/月)使用 LIMIT 优化查询;批量访问文件时改用 GCS

捆绑资源

references/api_schemas_reference.md

详细的 API 数据架构和查找表:REST API 响应字段、mmCIF 数据类别、置信度 JSON 架构、PAE JSON 架构、BigQuery 元数据表字段、HTTP 错误代码、速率限制指南和版本历史(v1–v4)。解析 API 响应或构建自定义查询时,可查阅此文档了解字段级详情。脚本功能(原文中没有)。原 api_reference.md 的部分内容已移至 Core API(端点、常见代码模式)和 Key Concepts(置信度阈值、文件类型表);架构、字段目录和错误代码保留在此参考文档中。

相关技能

  • autodock-vina — 使用 AlphaFold 结构作为受体进行分子对接
  • biopython — 用于 AlphaFold 之外的通用蛋白质结构解析与分析

参考资料

评论

支持 Markdown