2024-11-21CellphoneBD教程

1、cellphoneBD Rstudio 前期准备工作

建立输入文件
setwd("D:/D/metropolypus/FastMNN/cellphoneDB")
###根据colname名字区分BD单细胞和10X单细胞测序,提取10X单细胞测序数据
colnames(sce)
sce$tech <- sapply(colnames(x = sce), function(x) unlist(strsplit(x, "_"))[1]) 
sce$IF=sapply(sce$tech, function(x) unlist(nchar(x)>10))
table(sce$IF)

Idents(sce)<-sce$IF
ten=subset(sce,idents = c("TRUE"))
table(ten$sample)

subcell <- sample(colnames(ten),10000)
sce <- ten[,subcell]

library(SeuratDisk)
# 将Seurat对象保存为h5Seurat文件
SaveH5Seurat(sce, filename = "seurat_obj.h5Seurat")
# 转换为h5ad格式
Convert("seurat_obj.h5Seurat", dest = "h5ad")


# 安装pandas和anndata
# pip install pandas anndata
import pandas as pd
import anndata
# 读取CSV文件
expression_matrix = pd.read_csv("/mnt/d/D/temp/cellphoneDB/expression_matrix.csv", index_col=0)
# 创建AnnData对象
adata = anndata.AnnData(X=expression_matrix)
# 保存为.h5ad文件
adata.write("/mnt/d/D/temp/cellphoneDB/sce.h5ad")
print(count_cells[:10])

sce$Cell = rownames(sce@meta.data)
df = sce@meta.data[,c("Cell","celltype")]
colnames(df) = c("Cell","cell_type")
df$Cell <- gsub("-", ".", df$Cell)
write.table(df, file = "meta1.txt",sep = "\t",quote = F,row.names = F)

sce$Cell = rownames(sce@meta.data)
df = sce@meta.data[,c("celltype","group")]
colnames(df) = c("cell_type","microenvironment")
write.table(df, file = "microenvironment.txt",sep = "\t",quote = F,row.names = F)

DEG.Au <-dplyr::filter(DEG.A,DEG.A$avg_log2F >0.25)
write.table(DEG.Au, file = "degs_file.txt",sep = "\t",quote = F,row.names = F)

2、CellPhoneDB python中运行

#https://github.com/ventolab/CellphoneDB
#https://github.com/ventolab/CellphoneDB/blob/master/NatureProtocols2024_case_studies/CaseExample1_differentiation/analysis_method3_CellSign_microenvironments.ipynb
conda create -n cpdb python=3.8
source activate
conda activate cpdb
source activate cpdb
cd /mnt/d/D/temp/cellphoneDB

import pandas as pd
# 加载 meta 文件
meta_df = pd.read_csv("/mnt/d/D/temp/cellphoneDB/meta1.txt", sep="\t")
meta_clusters = set(meta_df['cell_type'])  # 使用meta文件中实际使用的列名

# 加载 DEGs 文件(需要早excel表格中手动调节DEGs每列的顺序需要和example_data中DEGs的顺序保持一致)
degs_df = pd.read_csv("/mnt/d/D/temp/cellphoneDB/degs_file.txt", sep="\t") 
degs_clusters = set(degs_df.iloc[:, 5])  # 取DEGs文件的第一列

# 检查 DEGs 中不存在于 meta 中的集群/细胞类型
missing_clusters = degs_clusters - meta_clusters
if missing_clusters:
    print("Missing clusters in meta:", missing_clusters)
else:
    print("All clusters match.")


from cellphonedb.src.core.methods import cpdb_degs_analysis_method
cpdb_results = cpdb_degs_analysis_method.call(
         cpdb_file_path = "/mnt/d/D/temp/cellphoneDB/cellphonedb.zip",
         meta_file_path = "/mnt/d/D/temp/cellphoneDB/meta1.txt",
         counts_file_path = "/mnt/d/D/temp/cellphoneDB/sce.h5ad",
         degs_file_path = "/mnt/d/D/temp/cellphoneDB/degs_file.txt",
         counts_data = 'hgnc_symbol',
         threshold = 0.1,
         output_path = "/mnt/d/D/temp/cellphoneDB/out/")

##代码运行时,所有表格列名的位置都要和D:\D\temp\cellphonedb\CellphoneDB-master\CellphoneDB-master\example_data中顺序一样

import anndata
adata = anndata.read_h5ad("/mnt/d/D/temp/cellphoneDB/seurat_obj.h5ad")
import matplotlib.pyplot as plt

# 调用绘制热图的函数
kpy.plot_cpdb_heatmap(
    pvals=cpdb_results['relevant_interactions'],
    degs_analysis=True,
    figsize=(5, 5),
    title="Sum of significant interactions"
)

# 保存图像到指定路径
output_path = "/mnt/d/D/temp/cellphoneDB/heatmap.png"
plt.savefig(output_path, format='png', dpi=300, bbox_inches='tight')

# 关闭当前图以释放内存
plt.close()


from plotnine import facet_wrap
# 创建图形对象
p = kpy.plot_cpdb(
    adata=adata,
    cell_type1=".",
    cell_type2="Mast_cells",
    means=cpdb_results['means'],
    pvals=cpdb_results['relevant_interactions'],
    celltype_key="celltype",
    figsize=(12, 8),
    title="Interactions with Mast cells",
    max_size=6,
    highlight_size=0.75,
    degs_analysis=True,
    standard_scale=False
)
# 添加facet_wrap
final_plot = p + facet_wrap("~ classification", ncol=2)
# 使用 plotnine 的 draw 方法,然后调用保存
output_path = "/mnt/d/D/temp/cellphoneDB/interaction_plot.mastcells.pdf"
from plotnine import ggplot
final_plot.save(filename=output_path, format='pdf', dpi=600, height=20, width=12, units='in')

p=kpy.plot_cpdb(
    adata = adata,
    cell_type1 = "Mast_cells",
    cell_type2 = ".", 
    means = cpdb_results['means'],
    pvals = cpdb_results['relevant_interactions'],
    celltype_key = "celltype",
#     genes = ["JAG1"],
    figsize = (10,15),
    title = "Interactions between oocytes and granulosa in the follicles",
    max_size = 5,
    highlight_size = 0.75,
    degs_analysis = True,
    standard_scale = False,
#     interaction_scores = cpdb_results['interaction_scores'],
    scale_alpha_by_interaction_scores=True,
)
output_path = "/mnt/d/D/temp/cellphoneDB/interaction_mastcell.allcells1.pdf"
from plotnine import ggplot
p.save(filename=output_path, format='pdf', dpi=600, height=8, width=8, units='in')
p.save(filename=output_path, format='pdf', dpi=300)
# 关闭当前图以释放内存
plt.close()

p = kpy.plot_cpdb(
    adata = adata,
    cell_type1 = ".",
    cell_type2 = "Mast_cells", 
    means = cpdb_results['means'],
    pvals = cpdb_results['relevant_interactions'],
    celltype_key = "celltype",
    genes = ["DHRS9"],
    figsize = (10,5),
    title = "Interactions involving DHRS9",
    max_size = 5,
    highlight_size = 0.75,
    degs_analysis = True,
    standard_scale = False
)
# 使用 plotnine 的 draw 方法,然后调用保存
output_path = "/mnt/d/D/temp/cellphoneDB/interaction_plotDHRS9-PGR.pdf"
final_plot.save(filename=output_path, format='pdf', dpi=300)

# 关闭当前图以释放内存
plt.close()
p = kpy.plot_cpdb(
    adata = adata,
    cell_type1 = "unciliated_EpC|ciliated_EpC",
    cell_type2 = "Mast_cells", 
    means = cpdb_results['means'],
    pvals = cpdb_results['relevant_interactions'],
    celltype_key = "celltype",
    figsize = (8, 5),
    title = "Interactions between oocytes and granulosa in the follicles \n supported by downstream TF activity",
    max_size = 6,
    highlight_size = 0.75,
    degs_analysis = True,
    standard_scale = False,
    cellsign = cpdb_results['CellSign_active_interactions'],
    filter_by_cellsign = True,
    scale_alpha_by_cellsign = False
)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容