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のタンパク質構造を取得・解析するスキルです。構造ファイル、信頼度指標、プロテオーム一括データを扱う研究者向けです。

主な機能

  1. 01UniProtアクセッションで予測を検索
  2. 02mmCIF、PDBなどの構造ファイルを取得
  3. 03pLDDTとPAEの信頼度を分析
  4. 04Google 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 は、DeepMind と EMBL-EBI が管理する、2 億種類を超えるタンパク質の AI 予測 3D 構造を収録した公開リポジトリです。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.bcifBinary 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 tax IDプロテオームのダウンロード対象の種
fractionPlddtVeryHighBigQuery—0.0–1.0高信頼度領域の割合によるフィルタリング
同時リクエスト数API—≤10API リクエストの最大並列数
リクエスト間隔API—100–200ms順次リクエスト間の遅延

ベストプラクティス

  1. 単一タンパク質には BioPython、一括処理には Google Cloud を使用する — 個別の API ダウンロードは100個を超えるタンパク質では遅くなります。GCS の並列ダウンロードは桁違いに高速です
  2. 下流解析の前に必ず pLDDT を確認する — 信頼度の低い領域(pLDDT <50)は無秩序である可能性が高く、ドッキング、接触解析、結合部位予測から除外する必要があります
  3. アンチパターン — すべての領域を同等に信頼する:AlphaFold の予測にはリガンド、PTM、補因子、複数鎖のコンテキストが含まれません。pLDDT が高くても、機能的な正確性が保証されるわけではありません
  4. ダウンロードしたファイルをローカルにキャッシュする — 同じ構造を再ダウンロードしないようにしてください。AlphaFold のファイルはバージョンごとに固定されています
  5. 複数ドメインタンパク質には PAE を使用する — pLDDT でわかるのは残基ごとの信頼度ですが、PAE からはドメインの向きが信頼できるかどうかがわかります。ドメイン間 PAE が低い(<5 Å)場合は配置を信頼し、高い(>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 以外のタンパク質構造の解析と一般的なパース

参考資料

コメント