scVelo實(shí)戰(zhàn)

velocyto預(yù)處理

###安裝velocyto###
#安裝依賴(lài)包
conda install numpy scipy cython numba matplotlib scikit-learn h5py click
#安裝velocyto包
pip install velocyto

Run velocyto

nohup velocyto run10x /.../P60-loupe/scVelo/loupe/ /.../refdata-gex-GRCh38-2020-A/genes/genes.gtf &

從Seurat對(duì)象導(dǎo)出細(xì)胞、基因、表達(dá)信息,供 scVelo 使用

#安裝R包
library(Seurat)
library(SpatialCPie)
library(Spaniel)
library(SingleR)
library(infercnv)
library(clustree)
library(clusterProfiler)
library(org.Hs.eg.db)
library(fgsea)
library(tidyverse)
library(ggplot2)
library(ggpubr)
library(devtools)
library(Matrix)
library(cowplot)
library(SeuratData)
library(patchwork)
library(dplyr)
library(hdf5r)

#讀空轉(zhuǎn)數(shù)據(jù)
 sRCC_P1<- Load10X_Spatial(
     data.dir="/.../P1-loupe/outs/",
     filename = "filtered_feature_bc_matrix.h5",
     assay = "Spatial",
     slice = "slice1",
     filter.matrix = TRUE,
     to.upper = FALSE,
)
Idents(sRCC_P1)<-"orig.ident"
sRCC_P1 <- RenameIdents(sRCC_P1, 'SeuratProject' = "sRCC_P1")
sRCC_P1$orig.ident<-Idents(sRCC_P1)

#標(biāo)準(zhǔn)化
sRCC_P1 <- SCTransform(sRCC_P1, assay = "Spatial", verbose = FALSE)

#降維和聚類(lèi)
# umap
sRCC_P1 <- RunPCA(sRCC_P1, assay = "SCT", verbose = FALSE, dims = 1:30)
sRCC_P1 <- FindNeighbors(sRCC_P1, reduction = "pca", dims = 1:30)
sRCC_P1 <- FindClusters(sRCC_P1, verbose = FALSE, resolution = 0.6)
sRCC_P1 <- RunUMAP(sRCC_P1, reduction = "pca", dims = 1:30)

#構(gòu)造函數(shù)Seurat to scVelo
Seurat2scVelo=function(sce, outputRoot){
  message("output to:", outputRoot)
  # save metadata table:
  sce$barcode <- colnames(sce)
  sce$UMAP_1 <- sce@reductions$umap@cell.embeddings[,1]
  sce$UMAP_2 <- sce@reductions$umap@cell.embeddings[,2]
  #write.csv(data.frame(sce@meta.data)[,c("barcode","seurat_clusters", "UMAP_1","UMAP_2")], 
  write.csv(sce@meta.data, 
            file=paste0(outputRoot, 'metadata.csv'), quote=F, row.names=F)
  
  # write expression counts matrix
  library(Matrix)
  counts_matrix <- GetAssayData(sce, assay='Spatial', slot='counts')
  writeMM(counts_matrix, file=paste0(outputRoot, 'counts.mtx'))
  
  # write dimesnionality reduction matrix, in this example case pca matrix
  write.csv(sce@reductions$pca@cell.embeddings, 
            file=paste0(outputRoot, 'pca.csv'), quote=F, row.names=F)
  
  # write gene names
  write.table(
    data.frame('gene'=rownames(counts_matrix)),
    file=paste0(outputRoot, 'gene_names.csv'),
    quote=F,row.names=F,col.names=F
  )
  return(invisible(NULL))
}

# 調(diào)用:
Seurat2scVelo(sRCC_P1, "/.../scVelo/1_sRCC-P1-loupe/velocyto/Seurat2scVelo/")

使用 Python 預(yù)處理數(shù)據(jù)

###讀取 Seurat 導(dǎo)出的數(shù)據(jù)###
import os
os.chdir("/.../scVelo/1_sRCC-P1-loupe/velocyto/Seurat2scVelo/")
os.getcwd()

import scanpy as sc
import anndata 
from scipy import io
from scipy.sparse import coo_matrix, csr_matrix
import numpy as np
import os
import pandas as pd

#(1) load sparse matrix:
X = io.mmread(f"./counts.mtx")
# create anndata object
adata = anndata.AnnData(
    X=X.transpose().tocsr()
)
#(2) load cell metadata:
cell_meta = pd.read_csv(f"./metadata.csv")
# load gene names:
with open(f"./gene_names.csv", 'r') as f:
    gene_names = f.read().splitlines()
# set anndata observations and index obs by barcodes, var by gene names
adata.obs = cell_meta
adata.obs.index = adata.obs['barcode']

adata.var.index = gene_names
#(3) load dimensional reduction:
pca = pd.read_csv(f"./pca.csv")
pca.index = adata.obs.index
# set pca and umap
adata.obsm['X_pca'] = pca.to_numpy()
adata.obsm['X_umap'] = np.vstack((adata.obs['UMAP_1'].to_numpy(), adata.obs['UMAP_2'].to_numpy())).T
# plot a UMAP colored by sampleID to test:
sc.pl.umap(adata, color='seurat_clusters', frameon=False, save=True)

###讀取 loom 數(shù)據(jù)(unsplied/spliced data)###
import scvelo as scv
import scanpy as sc
#import cellrank as cr
import numpy as np
import pandas as pd
import anndata as ad

# load loom files for spliced/unspliced matrices for each sample:
sample_loom_1="/.../scVelo/1_sRCC-P1-loupe/velocyto/sRCC.loom"
ldata1 = scv.read( sample_loom_1, cache=True)
ldata1
#加上cell ID
ldata1.obs.index[0:2]
barcodes = [bc.split(':')[1] for bc in ldata1.obs.index.tolist()]
barcodes = [bc[0:len(bc)-1] + '-1_1' for bc in barcodes]
ldata1.obs.index = barcodes
ldata1.obs.index[0:5]
ldata1.var.head()
ldata1.var_names_make_unique()
### 若有多個(gè)樣本就merge一下
#ldata = ldata1.concatenate([ldata2])
#ldata

#和Seurat數(shù)據(jù)合并
# merge matrices into the original adata object
adata = scv.utils.merge(adata, ldata1)
adata
adata.write_h5ad(f'/.../scVelo/1_sRCC-P1-loupe/velocyto/adata_ldata.h5ad')

scVelo計(jì)算RNA速率

#scVelo對(duì)數(shù)據(jù)預(yù)處理
import scvelo as scv
import scanpy as sc
import numpy as np
import pandas as pd
import anndata as ad
import os
os.chdir("/.../scVelo/1_sRCC-P1-loupe/velocyto/")
os.getcwd()


adata = sc.read(f'/.../scVelo/1_sRCC-P1-loupe/velocyto/adata_ldata.h5ad')
adata
###引入過(guò)Seurat信息后可以不做過(guò)濾等操作
scv.tl.velocity(adata, mode='stochastic')
scv.tl.velocity_graph(adata)
#######直接跳到可視化步驟#######
#scv.pp.filter_and_normalize(adata, min_shared_counts=5, min_shared_cells=3, log=True)
scv.pp.filter_and_normalize(adata)

#可選操作
## clean some genes##
#import re
#flag = [not bool(re.match('^Rp[ls]', i)) for i in adata.var_names]
#adata = adata[:,flag]
#adata = adata[:,adata.var_names != "Malat1"]
#adata

scv.set_figure_params()
scv.pp.moments(adata)

# this step will take a long while
import gc
gc.collect()
#
temp_pre= f"sRCC_nue.in_process2"
if False==os.path.exists(f"{temp_pre}.velo.gz.h5ad"):
    scv.tl.recover_dynamics(adata, var_names='all', n_jobs=64)
    scv.tl.velocity(adata, mode='dynamical')
    adata.write(f"{temp_pre}.velo.gz.h5ad", compression='gzip')
    print(">>Write to file")
else:
    adata = sc.read(f"{temp_pre}.velo.gz.h5ad", compression='gzip', ext="h5ad")
    print(">>read from file")

可視化

embedding

scv.pl.velocity_embedding(adata, basis = 'umap', title="sRCC",
                          save=f"./embedding.pdf",
                          color="seurat_clusters")

grid

scv.settings.set_figure_params('scvelo', dpi=300, dpi_save=300)
fig, ax = plt.subplots()
ax.set_aspect(1)

scv.pl.velocity_embedding_grid(adata, basis='umap',color='seurat_clusters', title='sRCC',
                               arrow_size=1, arrow_length=2, arrow_color="#D2691E",
                               alpha=0.1,
                               #density=0.9,
                               legend_loc='right margin',legend_fontsize=5,
                               show=True,
                               save=f"./grid.pdf", #figsize=(10,10),
                               xlim=[-10,10],ylim=[-10,10], ax=ax)

stream

import matplotlib.pyplot as plt
scv.settings.set_figure_params('scvelo', dpi=300, dpi_save=300)
#fig, ax = plt.subplots()
#ax.set_aspect(1)
scv.pl.velocity_embedding_stream(adata, basis='umap',color='seurat_clusters', title='sRCC',
                               #arrow_size=1, ##arrow_length=2, 
                               #arrow_color="#D2691E",
                               #alpha=0.01, density=0.9,
                               legend_loc='right margin',legend_fontsize=5,
                               show=True,
                               save=f"./stream.pdf")
                                #, #figsize=(10,10),
                               #xlim=[-10,10],ylim=[-10,10], 
                               #  ax=ax)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市废离,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌礁芦,老刑警劉巖蜻韭,帶你破解...
    沈念sama閱讀 206,013評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異柿扣,居然都是意外死亡肖方,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,205評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門(mén)未状,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)俯画,“玉大人,你說(shuō)我怎么就攤上這事司草〖璐梗” “怎么了泡仗?”我有些...
    開(kāi)封第一講書(shū)人閱讀 152,370評(píng)論 0 342
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)猜憎。 經(jīng)常有香客問(wèn)我娩怎,道長(zhǎng),這世上最難降的妖魔是什么胰柑? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,168評(píng)論 1 278
  • 正文 為了忘掉前任截亦,我火速辦了婚禮,結(jié)果婚禮上柬讨,老公的妹妹穿的比我還像新娘崩瓤。我一直安慰自己,他們只是感情好踩官,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,153評(píng)論 5 371
  • 文/花漫 我一把揭開(kāi)白布却桶。 她就那樣靜靜地躺著,像睡著了一般蔗牡。 火紅的嫁衣襯著肌膚如雪颖系。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 48,954評(píng)論 1 283
  • 那天蛋逾,我揣著相機(jī)與錄音集晚,去河邊找鬼窗悯。 笑死区匣,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的蒋院。 我是一名探鬼主播亏钩,決...
    沈念sama閱讀 38,271評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼欺旧!你這毒婦竟也來(lái)了姑丑?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 36,916評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤辞友,失蹤者是張志新(化名)和其女友劉穎栅哀,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體称龙,經(jīng)...
    沈念sama閱讀 43,382評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡留拾,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,877評(píng)論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了鲫尊。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片痴柔。...
    茶點(diǎn)故事閱讀 37,989評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖疫向,靈堂內(nèi)的尸體忽然破棺而出咳蔚,到底是詐尸還是另有隱情豪嚎,我是刑警寧澤,帶...
    沈念sama閱讀 33,624評(píng)論 4 322
  • 正文 年R本政府宣布谈火,位于F島的核電站侈询,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏堆巧。R本人自食惡果不足惜妄荔,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,209評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望谍肤。 院中可真熱鬧啦租,春花似錦、人聲如沸荒揣。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,199評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)系任。三九已至恳蹲,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間俩滥,已是汗流浹背嘉蕾。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,418評(píng)論 1 260
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留霜旧,地道東北人错忱。 一個(gè)月前我還...
    沈念sama閱讀 45,401評(píng)論 2 352
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像挂据,于是被迫代替她去往敵國(guó)和親以清。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,700評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容