mcpField
C
cbioportal-database

cbioportal-database

github.com/leonchaox数据与数据库98572 次安装14 周前更新
代码仓库

关于 cbioportal-database

cBioPortal Database 是通过 cBioPortal REST API 探索癌症基因组数据的技能,面向结合临床数据分析分子改变的研究人员。它提供研究级数据,涵盖突变、拷贝数、表达等分子特征。

主要功能

  1. 01浏览癌症研究和分子特征
  2. 02获取突变与拷贝数数据
  3. 03检索临床数据
  4. 04分析基因改变频率
  5. 05比较不同研究中的基因改变

适用场景

  1. 01评估某癌种中的突变频率
  2. 02比较不同癌症的改变比例
  3. 03关联基因组改变与临床变量
  4. 04为生存分析准备数据

安装

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

$npx skills add https://github.com/leonchaox/qinyan-academic-skills --skill cbioportal-database

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

附带文件references/study_exploration.md

详细介绍

cBioPortal 数据库

概述

cBioPortal for Cancer Genomics(https://www.cbioportal.org/)是一个开放访问资源,可用于探索、可视化和分析多维癌症基因组学数据。它托管来自 The Cancer Genome Atlas(TCGA)、AACR Project GENIE、MSK-IMPACT 以及数百项其他癌症研究的数据,涵盖数千份癌症样本的突变、拷贝数改变(CNA)、结构变异、mRNA/蛋白质表达、甲基化和临床数据。

关键资源:

何时使用此技能

在以下情况下使用 cBioPortal:

  • 突变图谱:某种癌症类型中有多少比例存在特定基因突变?
  • 癌基因/TSG 验证:某个基因在癌症中是否经常发生突变、扩增或缺失?
  • 共突变模式:基因 A 和基因 B 的突变是互斥还是共同发生?
  • 生存分析:某个基因的突变是否与更好的或更差的患者结局相关?
  • 改变谱:哪些类型的改变(错义、截断、扩增、缺失)会影响某个基因?
  • 泛癌分析:比较不同癌症类型中的改变频率
  • 临床关联:将基因组改变与临床变量(分期、分级、治疗反应)关联起来
  • TCGA/GENIE 探索:系统访问 TCGA 和临床测序数据集

核心功能

1. cBioPortal REST API

基础 URL:https://www.cbioportal.org/api

该 API 遵循 REST 架构,返回 JSON,访问公开数据无需 API 密钥。

import requests

BASE_URL = "https://www.cbioportal.org/api"
HEADERS = {"Accept": "application/json", "Content-Type": "application/json"}

def cbioportal_get(endpoint, params=None):
    url = f"{BASE_URL}/{endpoint}"
    response = requests.get(url, params=params, headers=HEADERS)
    response.raise_for_status()
    return response.json()

def cbioportal_post(endpoint, body):
    url = f"{BASE_URL}/{endpoint}"
    response = requests.post(url, json=body, headers=HEADERS)
    response.raise_for_status()
    return response.json()
2. 浏览研究
def get_all_studies():
    """List all available cancer studies."""
    return cbioportal_get("studies", {"pageSize": 500})

# Each study has:
# studyId: unique identifier (e.g., "brca_tcga")
# name: human-readable name
# description: dataset description
# cancerTypeId: cancer type abbreviation
# referenceGenome: GRCh37 or GRCh38
# pmid: associated publication

studies = get_all_studies()
print(f"Total studies: {len(studies)}")

# Common TCGA study IDs:
# brca_tcga, luad_tcga, coadread_tcga, gbm_tcga, prad_tcga,
# skcm_tcga, blca_tcga, hnsc_tcga, lihc_tcga, stad_tcga

# Filter for TCGA studies
tcga_studies = [s for s in studies if "tcga" in s["studyId"]]
print([s["studyId"] for s in tcga_studies[:10]])
3. 分子谱

每项研究都有多个分子谱(突变、CNA、表达等):

def get_molecular_profiles(study_id):
    """Get all molecular profiles for a study."""
    return cbioportal_get(f"studies/{study_id}/molecular-profiles")

profiles = get_molecular_profiles("brca_tcga")
for p in profiles:
    print(f"  {p['molecularProfileId']}: {p['name']} ({p['molecularAlterationType']})")

# Alteration types:
# MUTATION_EXTENDED — somatic mutations
# COPY_NUMBER_ALTERATION — CNA (GISTIC)
# MRNA_EXPRESSION — mRNA expression
# PROTEIN_LEVEL — RPPA protein expression
# STRUCTURAL_VARIANT — fusions/rearrangements
4. 突变数据
def get_mutations(molecular_profile_id, entrez_gene_ids, sample_list_id=None):
    """Get mutations for specified genes in a molecular profile."""
    body = {
        "entrezGeneIds": entrez_gene_ids,
        "sampleListId": sample_list_id or molecular_profile_id.replace("_mutations", "_all")
    }
    return cbioportal_post(
        f"molecular-profiles/{molecular_profile_id}/mutations/fetch",
        body
    )

# BRCA1 Entrez ID is 672, TP53 is 7157, PTEN is 5728
mutations = get_mutations("brca_tcga_mutations", entrez_gene_ids=[7157])  # TP53

# Each mutation record contains:
# patientId, sampleId, entrezGeneId, gene.hugoGeneSymbol
# mutationType (Missense_Mutation, Nonsense_Mutation, Frame_Shift_Del, etc.)
# proteinChange (e.g., "R175H")
# variantClassification, variantType
# ncbiBuild, chr, startPosition, endPosition, referenceAllele, variantAllele
# mutationStatus (Somatic/Germline)
# alleleFreqT (tumor VAF)

import pandas as pd
df = pd.DataFrame(mutations)
print(df[["patientId", "mutationType", "proteinChange", "alleleFreqT"]].head())
print(f"\nMutation types:\n{df['mutationType'].value_counts()}")
5. 拷贝数改变数据
def get_cna(molecular_profile_id, entrez_gene_ids):
    """Get discrete CNA data (GISTIC: -2, -1, 0, 1, 2)."""
    body = {
        "entrezGeneIds": entrez_gene_ids,
        "sampleListId": molecular_profile_id.replace("_gistic", "_all").replace("_cna", "_all")
    }
    return cbioportal_post(
        f"molecular-profiles/{molecular_profile_id}/discrete-copy-number/fetch",
        body
    )

# GISTIC values:
# -2 = Deep deletion (homozygous loss)
# -1 = Shallow deletion (heterozygous loss)
#  0 = Diploid (neutral)
#  1 = Low-level gain
#  2 = High-level amplification

cna_data = get_cna("brca_tcga_gistic", entrez_gene_ids=[1956])  # EGFR
df_cna = pd.DataFrame(cna_data)
print(df_cna["value"].value_counts())
6. 改变频率(类似 OncoPrint)
def get_alteration_frequency(study_id, gene_symbols, alteration_types=None):
    """Compute alteration frequencies for genes across a cancer study."""
    import requests, pandas as pd

    # Get sample list
    samples = requests.get(
        f"{BASE_URL}/studies/{study_id}/sample-lists",
        headers=HEADERS
    ).json()
    all_samples_id = next(
        (s["sampleListId"] for s in samples if s["category"] == "all_cases_in_study"), None
    )
    total_samples = len(requests.get(
        f"{BASE_URL}/sample-lists/{all_samples_id}/sample-ids",
        headers=HEADERS
    ).json())

    # Get gene Entrez IDs
    gene_data = requests.post(
        f"{BASE_URL}/genes/fetch",
        json=[{"hugoGeneSymbol": g} for g in gene_symbols],
        headers=HEADERS
    ).json()
    entrez_ids = [g["entrezGeneId"] for g in gene_data]

    # Get mutations
    mutation_profile = f"{study_id}_mutations"
    mutations = get_mutations(mutation_profile, entrez_ids, all_samples_id)

    freq = {}
    for g_symbol, e_id in zip(gene_symbols, entrez_ids):
        mutated = len(set(m["patientId"] for m in mutations if m["entrezGeneId"] == e_id))
        freq[g_symbol] = mutated / total_samples * 100

    return freq

# Example
freq = get_alteration_frequency("brca_tcga", ["TP53", "PIK3CA", "BRCA1", "BRCA2"])
for gene, pct in sorted(freq.items(), key=lambda x: -x[1]):
    print(f"  {gene}: {pct:.1f}%")
7. 临床数据
def get_clinical_data(study_id, attribute_ids=None):
    """Get patient-level clinical data."""
    params = {"studyId": study_id}
    all_clinical = cbioportal_get(
        "clinical-data/fetch",
        params
    )
    # Returns list of {patientId, studyId, clinicalAttributeId, value}

# Clinical attributes include:
# OS_STATUS, OS_MONTHS, DFS_STATUS, DFS_MONTHS (survival)
# TUMOR_STAGE, GRADE, AGE, SEX, RACE
# Study-specific attributes vary

def get_clinical_attributes(study_id):
    """List all available clinical attributes for a study."""
    return cbioportal_get(f"studies/{study_id}/clinical-attributes")

查询工作流

工作流 1:某种癌症类型中的基因改变谱
import requests, pandas as pd

def alteration_profile(study_id, gene_symbol):
    """Full alteration profile for a gene in a cancer study."""

    # 1. Get gene Entrez ID
    gene_info = requests.post(
        f"{BASE_URL}/genes/fetch",
        json=[{"hugoGeneSymbol": gene_symbol}],
        headers=HEADERS
    ).json()[0]
    entrez_id = gene_info["entrezGeneId"]

    # 2. Get mutations
    mutations = get_mutations(f"{study_id}_mutations", [entrez_id])
    mut_df = pd.DataFrame(mutations) if mutations else pd.DataFrame()

    # 3. Get CNAs
    cna = get_cna(f"{study_id}_gistic", [entrez_id])
    cna_df = pd.DataFrame(cna) if cna else pd.DataFrame()

    # 4. Summary
    n_mut = len(set(mut_df["patientId"])) if not mut_df.empty else 0
    n_amp = len(cna_df[cna_df["value"] == 2]) if not cna_df.empty else 0
    n_del = len(cna_df[cna_df["value"] == -2]) if not cna_df.empty else 0

    return {"mutations": n_mut, "amplifications": n_amp, "deep_deletions": n_del}

result = alteration_profile("brca_tcga", "PIK3CA")
print(result)
工作流 2:泛癌基因突变频率
import requests, pandas as pd

def pan_cancer_mutation_freq(gene_symbol, cancer_study_ids=None):
    """Mutation frequency of a gene across multiple cancer types."""
    studies = get_all_studies()
    if cancer_study_ids:
        studies = [s for s in studies if s["studyId"] in cancer_study_ids]

    results = []
    for study in studies[:20]:  # Limit for demo
        try:
            freq = get_alteration_frequency(study["studyId"], [gene_symbol])
            results.append({
                "study": study["studyId"],
                "cancer": study.get("cancerTypeId", ""),
                "mutation_pct": freq.get(gene_symbol, 0)
            })
        except Exception:
            pass

    df = pd.DataFrame(results).sort_values("mutation_pct", ascending=False)
    return df
工作流 3:按突变状态进行生存分析
import requests, pandas as pd

def survival_by_mutation(study_id, gene_symbol):
    """Get survival data split by mutation status."""
    # This workflow fetches clinical and mutation data for downstream analysis

    gene_info = requests.post(
        f"{BASE_URL}/genes/fetch",
        json=[{"hugoGeneSymbol": gene_symbol}],
        headers=HEADERS
    ).json()[0]
    entrez_id = gene_info["entrezGeneId"]

    mutations = get_mutations(f"{study_id}_mutations", [entrez_id])
    mutated_patients = set(m["patientId"] for m in mutations)

    clinical = cbioportal_get("clinical-data/fetch", {"studyId": study_id})
    clinical_df = pd.DataFrame(clinical)

    os_data = clinical_df[clinical_df["clinicalAttributeId"].isin(["OS_MONTHS", "OS_STATUS"])]
    os_wide = os_data.pivot(index="patientId", columns="clinicalAttributeId", values="value")
    os_wide["mutated"] = os_wide.index.isin(mutated_patients)

    return os_wide

主要 API 端点摘要

端点描述
GET /studies列出所有研究
GET /studies/{studyId}/molecular-profiles某项研究的分子谱
POST /molecular-profiles/{profileId}/mutations/fetch获取突变数据
POST /molecular-profiles/{profileId}/discrete-copy-number/fetch获取 CNA 数据
POST /molecular-profiles/{profileId}/molecular-data/fetch获取表达数据
GET /studies/{studyId}/clinical-attributes可用的临床变量
GET /clinical-data/fetch临床数据
POST /genes/fetch按符号或 Entrez ID 获取基因元数据
GET /studies/{studyId}/sample-lists样本列表

最佳实践

  • 了解研究 ID:使用 Swagger UI 或 GET /studies 查找正确的研究 ID
  • 使用样本列表:每项研究都有 all 样本列表和子集;请务必指定合适的列表
  • TCGA 与 GENIE:TCGA 数据较全面但年代较早;GENIE 包含较新的临床测序数据
  • Entrez 基因 ID:该 API 使用 Entrez ID;使用 /genes/fetch 将基因符号转换为 ID
  • 处理 404 错误:某些研究可能没有对应的分子谱
  • 速率限制:批量查询时请添加延迟;对于大规模分析,可考虑下载数据文件

数据下载

对于大规模分析,可直接下载研究数据:

# Download TCGA BRCA data
wget https://cbioportal-datahub.s3.amazonaws.com/brca_tcga.tar.gz

其他资源

评论

支持 Markdown