社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python版本:CellphoneDB的分析流程(方法二)学习

单细胞天地 • 1 年前 • 626 次点击  

CellphoneDB 是一个用于分析单细胞转录组数据中细胞-细胞通讯的数据库和计算工具。它基于细胞中表达的配体(ligands)和受体(receptors)来推断不同细胞类型之间的相互作用。

CellphoneDB的分析方法一共三种,其中最常用的可能是第二种分析方法:

方法1-简单分析(>= v1):不进行统计分析。CellphoneDB 将输出每种细胞类型组合间所有相互作用的平均值。请注意,只有当相互作用中的所有基因成员在至少一个细胞类型中的细胞中表达时( threshold ),CellphoneDB才会报告平均值。如果条件threshold不满足,该相互作用将在相应的细胞类型组合中被忽略。

方法2-统计分析(>= v1):是一种统计分析方法,用于评估数据集中所有可能发生的相互作用的显著性,也就是说,分析所有可能的细胞类型对之间的相互作用。在这里,CellphoneDB使用经验性置换(empirical shuffling)来计算哪些配体-受体对在细胞类型之间具有显著特异性。具体来说,它通过随机打乱所有细胞的簇标签,来估计作用簇中配体和受体表达均值的平均值的原假设分布(null distribution)。某一受体-配体复合物在特定细胞类型中具有特异性的显著性 P 值,是通过计算原假设分布中,均值大于或等于实际观测均值的比例来获得的。

方法3-degs_analysis(>= v3):此方法被提议作为统计推断方法的替代方案。这种方法允许用户设计更复杂的比较,以检索特定细胞类型的相互作用。当研究问题超出“一种”细胞类型与“其余”比较的范围时,这一点尤其相关。替代对比的示例包括分层比较(例如,对特定谱系感兴趣,如上皮细胞,并希望识别在此谱系中表达发生变化的基因)或比较疾病与对照(例如,通过将疾病 T 细胞与对照 T 细胞进行比较,希望识别疾病 T 细胞中上调的基因)。对于此 CellphoneDB 方法( cpdb_degs_analysis_method ),用户提供一个输入文件(命令下方的 test_DEGs.txt ),指示哪些基因对细胞类型相关(例如,标记基因或差异表达分析(DEG)产生的显著上调基因)。CellphoneDB 将选择满足以下条件的相互作用:1. 相互作用中的所有基因在相应细胞类型中由超过 10%的细胞表达( threshold = 0.1 ),2.至少有一个基因-细胞类型对在提供的 DEG.tsv 文件中。

CellphoneDB也有自己的数据库, 需要提前下载数据库内容:

# 展示数据库版本
from IPython.display import HTML, display
from cellphonedb.utils import db_releases_utils

display(HTML(db_releases_utils.get_remote_database_versions_html()['db_releases_html_table']))

# 设定数据库版本
cpdb_version = 'v5.0.0'

# 数据库资料所需的存放文件的路径
# 路径自行设定
cpdb_target_dir = os.path.join('/home/jovyan/cpdb_tutorial/db/test', cpdb_version)
# 开始下载数据
from cellphonedb.utils import db_utils

db_utils.download_database(cpdb_target_dir, cpdb_version)

方法二的分析流程:

1.创建环境
conda create -n cpdb python=3.8
conda activate cpdb

# 注册内核
pip install ipykernel
python -m ipykernel install --user --name cpdb --display-name "Python(cpdb)"
2.安装
# 终端中安装
pip install cellphonedb
# 需要在终端中安装ktplotspy,这是一个适用于cellphoneDB的可视化工具
pip install ktplotspy
3.导入
# 有一些包是多余的,但是也可以导入
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import scanpy as sc
import numpy as np
import anndata as ad
import ktplotspy as kpy
import os
# 确认位置
os.getcwd()
pd.set_option('display.max_columns', 100) # 设置pandas显示的最大列数为100,如果超过默认显示的数量,pandas会省略一些列显示。
os.chdir('./3-CellphoneDB/') # 移动到相应的文件夹中
4.数据准备

这里使用之前保存的h5ad文件

# 读取adata数据
adata = sc.read_h5ad("../scRNA_V5.h5ad")
# 归一化数据
sc.pp.normalize_per_cell(adata, counts_per_cell_after=1e4)
# 保存一个新的数据
adata.write('./adata_Nor_counts.h5ad')

注释文件:1. barcode_sample:该列表示实验中每个细胞的条形码。2. cell_type:该列表示分配的细胞标签。

# 获取adata的细胞注释文件
import pandas as pd

# 创建一个包含Cell和Cell_type两列的DataFrame
df = pd.DataFrame({
    'Cell': adata.obs_names,
    'Cell_type': adata.obs['celltype']
})

# 显示前几行(可选)
print(df.head())

# 如果需要保存为 CSV 文件:
df.to_csv('cell_annotations.csv', index=False)
5.输入文件
cpdb_file_path = '../cpdb_database/v5/cellphonedb.zip'
meta_file_path = './cell_annotations.csv'
counts_file_path = './adata_Nor_counts.h5ad'
#microenvs_file_path = 'cell_annotations.csv'
#active_tf_path = 'data/active_TFs.tsv'
out_path = './'
6.运行统计分析
from cellphonedb.src.core.methods import cpdb_statistical_analysis_method

cpdb_results = cpdb_statistical_analysis_method.call(
    cpdb_file_path = cpdb_file_path,                 # 必填: CellphoneDB database zip file.
    meta_file_path = meta_file_path,                 # 必填: tsv file defining barcodes to cell label.
    counts_file_path = counts_file_path,             # 必填: normalized count matrix - a path to the counts file, or an in-memory AnnData object
    counts_data = 'hgnc_symbol',                     # 在计数矩阵中定义基因注释信息.
    #active_tfs_file_path = active_tf_path,           # 可选: 定义细胞类型及其活跃的转录因子(TFs)。
    #microenvs_file_path = microenvs_file_path,       # 可选 (default: None): 定义了每个微环境中的细胞数量.
    score_interactions = True,                       # 可选: 是否要记录互动情况. 
    iterations = 1000,                               # 表示在分析中执行的随机置换次数。.
    threshold = 0.1,                                 # 定义了在分析中使用某个基因所需的最小细胞表达百分比。.
    threads = 5,                                     # 分析中使用的线程数量。.
    debug_seed = 42,                                 # 调试随机种子。要禁用,请设置为 >= 0。.
    result_precision = 3,                            # Sets the rounding for the mean values in significan_means.
    pvalue = 0.05,                                   # P值的阈值
    subsampling = False,                             # 启用数据的子抽样(几何草图)。
    subsampling_log = False,                         # (必填)为未经过对数转换的数据输入启用 subsampling log1p。
    subsampling_num_pc = 100,                        # 通过几何草图进行子抽样的组件数量(默认:100)。
    subsampling_num_cells = 1000,                    # 要进行子抽样的细胞数量(整数)(默认:数据集的 1/3)。
    separator = '|',                                 # 设置用于分隔结果数据框中细胞的字符串 "cellA|CellB"。
    debug = False,                                   # 将分析过程中使用的所有中间表以 pkl 格式保存。
    output_path = out_path,                          # Path to save results.
    output_suffix = None                             # Replaces the timestamp in the output files by a user defined string in the  (default: None).
    )
list(cpdb_results.keys())

# ['deconvoluted',
#  'deconvoluted_percents',
#  'means',
#  'pvalues',
#  'significant_means',
#  'CellSign_active_interactions',
#  'CellSign_active_interactions_deconvoluted',
#  'interaction_scores']
7.ktplots可视化

整体情况

kpy.plot_cpdb_heatmap(pvals = cpdb_results['pvalues'],
                      degs_analysis = False,
                      figsize = (5, 5),
                      title = "Sum of significant interactions")

聚焦特定细胞和基因家族

kpy.plot_cpdb(
    adata=adata,
    cell_type1="B cell",#比如这里我们需要看B cells细胞与其他细胞的通讯
    cell_type2=".",  # 表示所有细胞
    means=cpdb_results['means'],
    pvals=cpdb_results['pvalues'],
    celltype_key="celltype",
    gene_family="chemokines",
    figsize=(8, 5),
    title="interacting interactions",
    max_size = 3,
    highlight_size = 0.75
)
kpy.plot_cpdb(
    adata = adata,
    cell_type1 = "B cell",
    cell_type2 = ".",
    means = cpdb_results['means'],
    pvals = cpdb_results['pvalues'],
    celltype_key = "celltype",
    genes = ["TGFB2", "CSF1R"],
    figsize = (10, 3),
    title = "Interactions between\nB cell and other",
    max_size =  3,
    highlight_size = 0.75,
    degs_analysis = False,
    standard_scale = True,
    interaction_scores = cpdb_results['interaction_scores'],
    scale_alpha_by_interaction_scores = True
)

参考资料:

  1. cellphonedb github: https://cellphonedb.readthedocs.io/en/latest/
  2. cellphonebd database:https://github.com/ventolab/cellphonedb-data
  3. 单细胞天地:https://mp.weixin.qq.com/s/a6TFQ84sVi7hYIJYEJnKDQ
  4. 生信技能树:https://mp.weixin.qq.com/s/O7HHvEQMCdgcsuYlpQ_8pw
  5. 生信菜鸟团:https://mp.weixin.qq.com/s/PSMzh-MhhYMag81o9mq7Mw
  6. ktplotspy: https://ktplotspy.readthedocs.io/en/latest/index.html

注:若对内容有疑惑或者有发现明确错误的朋友,请联系后台(欢迎交流)。

文末友情宣传

强烈建议你推荐给身边的博士后以及年轻生物学PI,多一点数据认知,让他们的科研上一个台阶:


    Python社区是高质量的Python/Django开发社区
    本文地址:http://www.python88.com/topic/185155