Cell type deconvoluation of Visium
Translate cell types from single cell reference to ST data (full-rank cluster mode)
In addition to shared genes,
TransDeconvrequires single cell type lables and per-cell annotations as input;After fitting the translation function,
TransDeconvwill output the predictions as well as the weights for each cell type
[ ]:
# import FineST as fst
# from FineST.datasets import dataset
# import FineST.plottings as fstplt
# print("FineST version: %s" %fst.__version__)
## From GPU2
path = '/mnt/lingyu/nfs_share2/Python/'
import os
os.chdir(str(path) + 'FineST/FineST/')
import FineST as fst
from FineST.datasets import dataset
import FineST.plottings as fstplt
print("FineST version: %s" %fst.__version__)
FineST version: 0.1.0
[2]:
# import scvelo as scv
import scanpy as sc
import numpy as np
import pandas as pd
import transpa
from transpa.util import expVeloImp, leiden_cluster, expDeconv
print("transpa version: %s" %transpa.__version__)
import torch
import warnings
warnings.filterwarnings('ignore')
seed = 10
device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")
transpa version: 0.1.1
Set pathway
[ ]:
import os
path = '/mnt/lingyu/nfs_share2/Python/'
# path = '/home/lingyu/ssd/Python/'
1. Log normalized (Run once time)
WARNING: It seems you use rank_genes_groups on the raw count data. Please logarithmize your data before calling rank_genes_groups.
[3]:
## load preprocessed scRNA-seq and spatial datasets
RNA_PATH = str(path)+"NPC/Data/scdata/NPC_rds_reference_rna.h5ad"
[4]:
RNA = scv.read(RNA_PATH)
RNA
[4]:
AnnData object with n_obs × n_vars = 5508 × 33628
obs: 'orig.ident', 'nCount_RNA', 'nFeature_RNA', 'percent.mt', 'Study', 'Group', 'Batch', 'Patient', 'RNA_snn_res.0.8', 'seurat_clusters', 'mygroup', 'mygroup2', 'Cluster'
var: '_index', 'features'
[5]:
RNA.var_names = RNA.var['features']
[6]:
print(RNA.X.todense())
print(RNA.X.min(), RNA.X.max())
[[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
...
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]
[0. 0. 0. ... 0. 0. 0.]]
0.0 21765.0
[7]:
sc.pp.normalize_total(RNA, target_sum=2000)
sc.pp.log1p(RNA)
print(RNA)
print(RNA.X.min(), RNA.X.max())
AnnData object with n_obs × n_vars = 5508 × 33628
obs: 'orig.ident', 'nCount_RNA', 'nFeature_RNA', 'percent.mt', 'Study', 'Group', 'Batch', 'Patient', 'RNA_snn_res.0.8', 'seurat_clusters', 'mygroup', 'mygroup2', 'Cluster'
var: '_index', 'features'
uns: 'log1p'
0.0 7.407887340374392
[8]:
RNA.var
[8]:
| _index | features | |
|---|---|---|
| features | ||
| MIR1302-2HG | MIR1302-2HG | MIR1302-2HG |
| FAM138A | FAM138A | FAM138A |
| OR4F5 | OR4F5 | OR4F5 |
| AL627309.1 | AL627309.1 | AL627309.1 |
| AL627309.3 | AL627309.3 | AL627309.3 |
| ... | ... | ... |
| LMP-1 | LMP-1 | LMP-1 |
| BNLF2b | BNLF2b | BNLF2b |
| BNLF2a | BNLF2a | BNLF2a |
| EBER1 | EBER1 | EBER1 |
| EBER2 | EBER2 | EBER2 |
33628 rows × 2 columns
[9]:
RNA.var_names
[9]:
Index(['MIR1302-2HG', 'FAM138A', 'OR4F5', 'AL627309.1', 'AL627309.3',
'AL627309.2', 'AL627309.4', 'AL732372.1', 'OR4F29', 'AC114498.1',
...
'BALF3', 'BARF0', 'BALF2', 'BALF1', 'BARF1', 'LMP-1', 'BNLF2b',
'BNLF2a', 'EBER1', 'EBER2'],
dtype='object', name='features', length=33628)
[10]:
if '_index' in RNA.var.columns:
RNA.var.drop(columns=['_index'], inplace=True)
if '_index' in RNA.raw.var.columns:
RNA.raw.var.drop(columns=['_index'], inplace=True)
print(RNA)
AnnData object with n_obs × n_vars = 5508 × 33628
obs: 'orig.ident', 'nCount_RNA', 'nFeature_RNA', 'percent.mt', 'Study', 'Group', 'Batch', 'Patient', 'RNA_snn_res.0.8', 'seurat_clusters', 'mygroup', 'mygroup2', 'Cluster'
var: 'features'
uns: 'log1p'
[11]:
## save adata
# RNA.write(str(path)+'NPC/Data/scdata/NPC_rds_reference_rna_4SpatialScope.h5ad')
2. Begin cell type deconvoluation
[6]:
## load preprocessed scRNA-seq and spatial datasets
# RNA_PATH = str(path)+"NPC/Data/scdata/NPC_rds_reference_rna_4SpatialScope.h5ad" # for woody server
RNA_PATH = str(path)+"FineST/FineST_local/Dataset/NPC/TransImp/NPC_rds_reference_rna_4SpatialScope.h5ad"
RNA = sc.read(RNA_PATH)
patientxy = 'patient1'
ST_PATH = str(path)+'FineST/FineST_local/Dataset/ImputData/'+str(patientxy)+'/'+str(patientxy)+'_adata_imput_all_sc.h5ad'
[7]:
RNA = sc.read(RNA_PATH)
HybISS = sc.read(ST_PATH)
RNA, HybISS
[7]:
(AnnData object with n_obs × n_vars = 5508 × 33628
obs: 'orig.ident', 'nCount_RNA', 'nFeature_RNA', 'percent.mt', 'Study', 'Group', 'Batch', 'Patient', 'RNA_snn_res.0.8', 'seurat_clusters', 'mygroup', 'mygroup2', 'Cluster'
var: 'features'
uns: 'log1p',
AnnData object with n_obs × n_vars = 40068 × 596
obs: 'x', 'y'
uns: 'spatial'
obsm: 'spatial')
[8]:
HybISS.to_df().head()
[8]:
| TGFB1 | TGFBR1 | TGFBR2 | TGFB2 | TGFB3 | ACVR1B | ACVR1C | ACVR1 | BMP2 | BMPR1A | ... | KDR | TREM2 | SEMA6A | SEMA6B | SEMA7A | PLXNC1 | SIGLEC1 | THY1 | VCAM1 | VSIR | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0.262914 | 0.186327 | 0.464312 | 0.068035 | 0.055982 | 0.532792 | 0.003026 | 0.125616 | 0.015445 | 0.113145 | ... | 0.004381 | 0.004725 | 0.039676 | 0.015800 | 0.183981 | 0.003781 | 0.004408 | 0.158374 | 0.334349 | 0.235620 |
| 1 | 1.797625 | 0.846512 | 0.725175 | 0.026779 | 0.119732 | 0.066159 | 0.004082 | 0.178944 | 0.299725 | 0.046523 | ... | 0.066852 | 0.003381 | 0.057715 | 0.320275 | 0.538943 | 0.004133 | 0.003983 | 0.920966 | 1.834921 | 0.585638 |
| 2 | 0.380308 | 0.244998 | 0.033317 | 0.004972 | 0.066450 | 0.275714 | 0.004106 | 0.098649 | 0.004587 | 0.194033 | ... | 0.013605 | 0.183658 | 0.004656 | 0.004766 | 0.222726 | 0.023602 | 0.033465 | 0.163557 | 0.453851 | 0.732290 |
| 3 | 0.210108 | 1.501863 | 0.482271 | 0.059778 | 0.034524 | 0.179217 | 0.002923 | 0.083871 | 0.014544 | 0.145562 | ... | 0.004060 | 0.004754 | 0.469650 | 0.004223 | 0.624454 | 0.485028 | 0.004397 | 0.501598 | 2.923608 | 1.224518 |
| 4 | 0.352550 | 0.173602 | 0.121180 | 0.090928 | 0.088416 | 0.231018 | 0.002821 | 0.078262 | 0.003924 | 0.170986 | ... | 0.004153 | 0.004814 | 0.424619 | 0.004336 | 0.194609 | 0.003708 | 0.004515 | 0.244271 | 2.110376 | 0.845303 |
5 rows × 596 columns
[10]:
print(RNA.obs['Cluster'])
print(set(RNA.obs['Cluster']))
AAACGGGGTGTTCTTT-12 B
AAAGTAGAGGTTACCT-12 B
AAAGTAGCACCTGGTG-12 normal
AAATGCCAGACTTTCG-12 B
AACTCTTGTCCCGACA-12 Treg
...
TGACTTTGTTGTGGCC-61 T
TGCCAAAAGCTTATCG-61 fibroblast
TTAGGACTCGATGAGG-61 fibroblast
TTAGGCACAGCGAACA-61 fibroblast
TTGAACGTCCGTAGTA-61 fibroblast
Name: Cluster, Length: 5508, dtype: category
Categories (7, object): ['B', 'Myeloid', 'T', 'Treg', 'fibroblast', 'normal', 'tumor']
{'fibroblast', 'B', 'Myeloid', 'Treg', 'tumor', 'normal', 'T'}
The following code prepares input for expDeconv, it
filters SC types with less than 2 samples,
select top cell-type marker genes as training candidate,
align training & testing genes
prepare cell cluster labels and annotations
[11]:
sc.pp.pca(HybISS, n_comps=30)
celltype_counts = RNA.obs['Cluster'].value_counts()
celltype_drop = celltype_counts.index[celltype_counts < 2]
rna_adata = RNA.copy()
if len(celltype_drop):
print(f'Drop celltype {list(celltype_drop)} (contain less 2 samples)')
rna_adata = RNA[~RNA.obs['Cluster'].isin(celltype_drop),].copy()
sc.tl.rank_genes_groups(rna_adata, groupby="Cluster", use_raw=False, method="wilcoxon")
markers_df = pd.DataFrame(rna_adata.uns["rank_genes_groups"]["names"]).iloc[0:100, :]
genes_sc = np.unique(markers_df.melt().value.values)
gene = np.intersect1d(genes_sc, HybISS.var_names)
print(gene.shape)
rna_adata = rna_adata[:, gene].copy()
spa_adata = HybISS[:, gene].copy()
print(rna_adata)
print(spa_adata)
(80,)
AnnData object with n_obs × n_vars = 5508 × 80
obs: 'orig.ident', 'nCount_RNA', 'nFeature_RNA', 'percent.mt', 'Study', 'Group', 'Batch', 'Patient', 'RNA_snn_res.0.8', 'seurat_clusters', 'mygroup', 'mygroup2', 'Cluster'
var: 'features'
uns: 'log1p', 'rank_genes_groups'
AnnData object with n_obs × n_vars = 40068 × 80
obs: 'x', 'y'
uns: 'spatial', 'pca'
obsm: 'spatial', 'X_pca'
varm: 'PCs'
[12]:
df_ref = pd.DataFrame(rna_adata.X.A, columns=rna_adata.var_names)
df_tgt = pd.DataFrame(spa_adata.X, columns=spa_adata.var_names)
print(df_ref.shape, df_tgt.shape)
(5508, 80) (40068, 80)
[13]:
shared_gene = np.intersect1d(df_ref.columns, df_tgt.columns)
df_ref = df_ref[shared_gene]
df_tgt = df_tgt[shared_gene]
classes = rna_adata.obs.Cluster.values
ct_list = np.unique(classes)
Run the main cell type deconvoluation method
Normalize result and select the top1 cell type
[14]:
preds, weight = expDeconv(
df_ref=df_ref,
df_tgt=df_tgt,
classes=classes,
ct_list=ct_list,
n_epochs=8000,
lr=1e-2,
seed=seed,
device=device
)
df_results = pd.DataFrame(weight, columns=ct_list)
df_results = (df_results.T/df_results.sum(axis=1)).T
df_results
[LinTrans] Epoch: 8000/8000, loss: 0.462533: 100%|██████████████████████████████████████████████████████████████| 8000/8000 [00:49<00:00, 160.57it/s]
[14]:
| B | Myeloid | T | Treg | fibroblast | normal | tumor | |
|---|---|---|---|---|---|---|---|
| 0 | 0.152193 | 0.103570 | 0.141658 | 0.004052 | 0.068908 | 0.376742 | 0.152876 |
| 1 | 0.290726 | 0.133424 | 0.138967 | 0.090358 | 0.151030 | 0.161922 | 0.033573 |
| 2 | 0.117871 | 0.135463 | 0.312806 | 0.127460 | 0.167820 | 0.000000 | 0.138580 |
| 3 | 0.289334 | 0.250692 | 0.101216 | 0.108613 | 0.067047 | 0.000000 | 0.183099 |
| 4 | 0.240868 | 0.142326 | 0.088075 | 0.150278 | 0.065865 | 0.000000 | 0.312588 |
| ... | ... | ... | ... | ... | ... | ... | ... |
| 40063 | 0.102169 | 0.145068 | 0.274381 | 0.095771 | 0.157204 | 0.000000 | 0.225407 |
| 40064 | 0.210840 | 0.126019 | 0.153550 | 0.134746 | 0.254464 | 0.000000 | 0.120380 |
| 40065 | 0.177253 | 0.335785 | 0.075577 | 0.173291 | 0.020756 | 0.000000 | 0.217337 |
| 40066 | 0.463004 | 0.025115 | 0.132535 | 0.033568 | 0.210539 | 0.000000 | 0.135240 |
| 40067 | 0.119663 | 0.261590 | 0.245963 | 0.121300 | 0.095210 | 0.000000 | 0.156276 |
40068 rows × 7 columns
[15]:
print(df_results[df_results.columns].idxmax(axis=1))
0 normal
1 B
2 T
3 B
4 tumor
...
40063 T
40064 fibroblast
40065 Myeloid
40066 B
40067 Myeloid
Length: 40068, dtype: object
[16]:
print(df_results.columns[np.argmax(df_results.values, axis=1)])
Index(['normal', 'B', 'T', 'B', 'tumor', 'tumor', 'B', 'Myeloid', 'B', 'tumor',
...
'T', 'T', 'T', 'tumor', 'T', 'T', 'fibroblast', 'Myeloid', 'B',
'Myeloid'],
dtype='object', length=40068)
[17]:
HybISS.obs['cell_type'] = df_results.columns[np.argmax(df_results.values, axis=1)]
HybISS
[17]:
AnnData object with n_obs × n_vars = 40068 × 596
obs: 'x', 'y', 'cell_type'
uns: 'spatial', 'pca'
obsm: 'spatial', 'X_pca'
varm: 'PCs'
Add cell type propotion and save adata
[18]:
df_results.index = df_results.index.astype(str)
HybISS.obsm['TransImp_ct_pred'] = df_results
HybISS
[18]:
AnnData object with n_obs × n_vars = 40068 × 596
obs: 'x', 'y', 'cell_type'
uns: 'spatial', 'pca'
obsm: 'spatial', 'X_pca', 'TransImp_ct_pred'
varm: 'PCs'
[19]:
InputFile = 'ScanpyDataP1'
adata_Visium = sc.read_visium(str(path)+'NPC/'+str(InputFile))
HybISS.obsm['spatial'] = np.stack([HybISS.obs['x'], HybISS.obs['y']], axis=1)
HybISS.uns = adata_Visium.uns
HybISS
[19]:
AnnData object with n_obs × n_vars = 40068 × 596
obs: 'x', 'y', 'cell_type'
uns: 'spatial'
obsm: 'spatial', 'X_pca', 'TransImp_ct_pred'
varm: 'PCs'
[20]:
## save the results
os.chdir(str(path)+'FineST/FineST_local/Dataset/NPC/TransImp/')
HybISS.write(str(patientxy)+"_nuclei_anno_TransImp_NPC1_sc.h5ad")
[21]:
!pwd
/mnt/lingyu/nfs_share2/Python/FineST/FineST_local/Dataset/NPC/TransImp
3. Deconvolution result visualization
[23]:
os.chdir(str(path)+'FineST/FineST_local/Dataset/NPC/TransImp/')
HybISS = sc.read_h5ad(str(patientxy)+"_nuclei_anno_TransImp_NPC1_sc.h5ad")
print(HybISS)
AnnData object with n_obs × n_vars = 40068 × 596
obs: 'x', 'y', 'cell_type'
uns: 'spatial'
obsm: 'TransImp_ct_pred', 'X_pca', 'spatial'
varm: 'PCs'
[24]:
HybISS.obs['cell_type']
[24]:
0 normal
1 B
2 T
3 B
4 tumor
...
40063 T
40064 fibroblast
40065 Myeloid
40066 B
40067 Myeloid
Name: cell_type, Length: 40068, dtype: category
Categories (7, object): ['B', 'Myeloid', 'T', 'Treg', 'fibroblast', 'normal', 'tumor']
[ ]:
import matplotlib.pyplot as plt
ctype_hex_map = {'B': '#565DFD',
'normal': '#4fa9ff',
'Treg': '#FE664D',
'fibroblast': '#9f50f9',
'Myeloid': '#009203',
'tumor': '#e5e022',
'T': '#CB6035'}
[26]:
fig, ax = plt.subplots(1, 1, figsize=(12, 8), dpi=100)
sc.pl.spatial(HybISS, img_key='hires', color="cell_type", size=0.3, alpha_img=0.9, palette=ctype_hex_map, title="TransImp", ax=ax)
fig, ax = plt.subplots(1, 1, figsize=(12, 8), dpi=100)
sc.pl.spatial(HybISS, img_key=None, color="cell_type", size=0.3, alpha_img=0.9, palette=ctype_hex_map, title="TransImp", ax=ax)
[27]:
## directly save the cell2location result
clust_labels = ['B', 'Myeloid', 'T', 'Treg', 'fibroblast', 'normal', 'tumor']
HybISS.obs[clust_labels] = HybISS.obsm['TransImp_ct_pred']
HybISS
[27]:
AnnData object with n_obs × n_vars = 40068 × 596
obs: 'x', 'y', 'cell_type', 'B', 'Myeloid', 'T', 'Treg', 'fibroblast', 'normal', 'tumor'
uns: 'spatial', 'cell_type_colors'
obsm: 'TransImp_ct_pred', 'X_pca', 'spatial'
varm: 'PCs'
[28]:
!pwd
/mnt/lingyu/nfs_share2/Python/FineST/FineST_local/Dataset/NPC/TransImp
[31]:
# save figures
with mpl.rc_context({'axes.facecolor': 'black', 'figure.figsize': [4.5, 3.5]}):
sc.pl.spatial(HybISS,
color=['B', 'Myeloid', 'T', 'Treg', 'fibroblast', 'normal', 'tumor'],
ncols=7, size=0.3,
img_key='hires',
alpha_img=0.9,
vmin=0, vmax='p99.2',
save="NPC_patient1_celltype_7tissue_nuclei_image.pdf")
WARNING: saving figure to file figures/showNPC_patient1_celltype_7tissue_nuclei_image.pdf
[35]:
import matplotlib.pyplot as plt
import scanpy as sc
fig, ax = plt.subplots(1, 1, dpi=100) # figsize=(12, 8),
sc.pl.spatial(HybISS, img_key='hires', color="cell_type", size=0.3, alpha_img=0.5, palette=ctype_hex_map, title="TransImp", ax=ax)
fig.savefig('NPC1_anno_nuclei_TransImp_image.pdf', format='pdf')
fig, ax = plt.subplots(1, 1, dpi=100)
sc.pl.spatial(HybISS, img_key=None, color="cell_type", size=0.3, alpha_img=0.9, palette=ctype_hex_map, title="TransImp", ax=ax)
fig.savefig('NPC1_anno_nuclei_TransImp.pdf', format='pdf')
[36]:
p2_res = HybISS.obs['cell_type']
ss = pd.DataFrame(p2_res.value_counts()/p2_res.shape[0])
ss.columns = ['NPC1_TransImp']
df_res = ss.T
df_res
[36]:
| cell_type | tumor | B | Treg | T | Myeloid | fibroblast | normal |
|---|---|---|---|---|---|---|---|
| NPC1_TransImp | 0.323874 | 0.177748 | 0.152066 | 0.117775 | 0.115703 | 0.068908 | 0.043925 |
[37]:
df_res.columns
# !pwd
df_res.to_csv('celltype_prop_NPC1_Visiun_nuclei.csv')
color_dict = ctype_hex_map
plot_columns = np.array(df_res.columns)
plot_colors = [color_dict[_] for _ in plot_columns]
labels = plot_columns
colors = plot_colors
labels = plot_columns#df_res.columns
colors = plot_colors#['#1D2F6F', '#8390FA', '#6EAF46', '#FAC748']
title = 'Video Game Sales By Platform and Region\n'
subtitle = 'Proportion of Games Sold by Region'
[42]:
os.chdir(f"{path}/FineST/FineST_local/Dataset/NPC/TransImp/")
fstplt.plot_stackedbar_p(df_res, labels, colors, title, subtitle, fig_size=(6, 1.5), save_path='TranImp_nuclei_NPC1.pdf')
4. ROI region analysis
[43]:
import squidpy as sq
import matplotlib.pyplot as plt
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
os.chdir(str(path))
## NPC1
image = plt.imread('NPC/Data/stdata/GSE200310_RAW/patient1/20210809-C-AH4199551.tif')
img = sq.im.ImageContainer(image)
[44]:
## pattern 1 local
inset_x = int(img.shape[0]*(3.1/10)) # column
inset_y = int(img.shape[1]*(3.9/10)) # row
inset_sx = int(img.shape[0]*(2.5/10)) # weidth
inset_sy = int(img.shape[1]*(7.0/10)) # high
HybISS_sp_crop = HybISS[
(HybISS.obsm["spatial"][:, 0] > inset_x) & (HybISS.obsm["spatial"][:, 1] > inset_y)
& (HybISS.obsm["spatial"][:, 0] < inset_x+inset_sx) & (HybISS.obsm["spatial"][:, 1] < inset_y+inset_sy), :
].copy()
print(HybISS_sp_crop)
AnnData object with n_obs × n_vars = 9993 × 596
obs: 'x', 'y', 'cell_type', 'B', 'Myeloid', 'T', 'Treg', 'fibroblast', 'normal', 'tumor'
uns: 'spatial', 'cell_type_colors'
obsm: 'TransImp_ct_pred', 'X_pca', 'spatial'
varm: 'PCs'
[45]:
## ['B', 'Myeloid', 'T', 'Treg', 'fibroblast', 'tumor']].idxmax(axis=1)
HybISS_sp_crop.obs["ROI1"]=pd.DataFrame(HybISS_sp_crop.obsm['TransImp_ct_pred'][['B', 'Myeloid', 'T', 'Treg', 'fibroblast', 'normal', 'tumor']].idxmax(axis=1))
HybISS_sp_crop
[45]:
AnnData object with n_obs × n_vars = 9993 × 596
obs: 'x', 'y', 'cell_type', 'B', 'Myeloid', 'T', 'Treg', 'fibroblast', 'normal', 'tumor', 'ROI1'
uns: 'spatial', 'cell_type_colors'
obsm: 'TransImp_ct_pred', 'X_pca', 'spatial'
varm: 'PCs'
[46]:
!pwd
/mnt/lingyu/nfs_share2/Python
[47]:
os.chdir(str(path)+'FineST/FineST_local/Dataset/NPC/TransImp/')
[48]:
fig, ax = plt.subplots(1, 1, dpi=100)
sc.pl.spatial(HybISS_sp_crop, img_key='hires', color="ROI1", palette=ctype_hex_map, size=0.3, ax=ax)
fig.savefig('NPC1_anno_TransImp_niclei_ROI.pdf', format='pdf')
... storing 'ROI1' as categorical
[49]:
p2_res = HybISS_sp_crop.obs['cell_type']
ss = pd.DataFrame(p2_res.value_counts()/p2_res.shape[0])
ss.columns = ['NPC1_TransImp_ROI1']
df_res = ss.T
df_res
[49]:
| cell_type | tumor | B | T | normal | Myeloid | fibroblast | Treg |
|---|---|---|---|---|---|---|---|
| NPC1_TransImp_ROI1 | 0.401981 | 0.172221 | 0.167918 | 0.092765 | 0.070349 | 0.060943 | 0.033824 |
[50]:
df_res.columns
# !pwd
df_res.to_csv('celltype_prop_NPC1_Visiun_nuclei_ROI1.csv')
color_dict = ctype_hex_map
plot_columns = np.array(df_res.columns)
plot_colors = [color_dict[_] for _ in plot_columns]
labels = plot_columns
colors = plot_colors
labels = plot_columns#df_res.columns
colors = plot_colors#['#1D2F6F', '#8390FA', '#6EAF46', '#FAC748']
title = 'Video Game Sales By Platform and Region\n'
subtitle = 'Proportion of Games Sold by Region'
[53]:
fstplt.plot_stackedbar_p(df_res, labels, colors, title, subtitle, fig_size=(6, 1.5), save_path='TranImp_nuclei_NPC1_ROI1.pdf')
Reference data
[4]:
####################
# Reference data
####################
## load preprocessed scRNA-seq
import scanpy as sc
RNA_PATH = str(path)+"FineST/FineST_local/Dataset/NPC/TransImp/NPC_rds_reference_rna_4SpatialScope.h5ad"
RNA = sc.read(RNA_PATH)
p2_res_RNA = RNA.obs['Cluster']
ss_RNA = pd.DataFrame(p2_res_RNA.value_counts()/p2_res_RNA.shape[0])
ss_RNA.columns = ['NPC_Reference']
df_res_RNA = ss_RNA.T
df_res_RNA
[4]:
| Cluster | B | Myeloid | T | Treg | tumor | fibroblast | normal |
|---|---|---|---|---|---|---|---|
| NPC_Reference | 0.181554 | 0.181554 | 0.181554 | 0.181554 | 0.181554 | 0.071169 | 0.02106 |
[9]:
os.chdir(str(path)+'FineST/FineST_local/Dataset/NPC/TransImp/')
# !pwd
df_res_RNA.to_csv('celltype_prop_CRC16um_scRNAseq.csv')
[10]:
import matplotlib.pyplot as plt
ctype_hex_map = {'B': '#565DFD',
'normal': '#4fa9ff',
'Treg': '#FE664D',
'fibroblast': '#9f50f9',
'Myeloid': '#009203',
'tumor': '#e5e022',
'T': '#CB6035'}
color_dict = ctype_hex_map
plot_columns = np.array(df_res_RNA.columns)
plot_colors = [color_dict[_] for _ in plot_columns]
labels = plot_columns
colors = plot_colors
title = 'Video Game Sales By Platform and Region\n'
subtitle = 'Proportion of Games Sold by Region'
fstplt.plot_stackedbar_p(df_res_RNA, labels, colors, title, subtitle, fig_size=(6, 1.5))
5. Cell type proportion comparision and correlation
Comparision
[4]:
os.chdir(str(path)+'FineST/FineST_local/Dataset/NPC/TransImp/')
prop_ref = pd.read_csv('celltype_prop_CRC16um_scRNAseq.csv', index_col=0)
prop_sc = pd.read_csv('celltype_prop_NPC1_Visiun_nuclei.csv', index_col=0)
prop_subspot = pd.read_csv('celltype_prop_NPC1_Visiun_spot.csv', index_col=0)
[5]:
prop_ref
[5]:
| B | Myeloid | T | Treg | tumor | fibroblast | normal | |
|---|---|---|---|---|---|---|---|
| NPC_Reference | 0.181554 | 0.181554 | 0.181554 | 0.181554 | 0.181554 | 0.071169 | 0.02106 |
[6]:
data = pd.concat([prop_ref, prop_subspot, prop_sc])
# data.index = ['scRNA-seq', 'spot resolution', 'single-cell resolution']
data.index = ['scRNA-seq', 'spot', 'single-cell']
data
[6]:
| B | Myeloid | T | Treg | tumor | fibroblast | normal | |
|---|---|---|---|---|---|---|---|
| scRNA-seq | 0.181554 | 0.181554 | 0.181554 | 0.181554 | 0.181554 | 0.071169 | 0.021060 |
| spot | 0.180316 | 0.059354 | 0.062359 | 0.003757 | 0.528174 | 0.106687 | 0.059354 |
| single-cell | 0.177748 | 0.115703 | 0.117775 | 0.152066 | 0.323874 | 0.068908 | 0.043925 |
[7]:
import matplotlib.pyplot as plt
ctype_hex_map = {'B': '#565DFD',
'normal': '#4fa9ff',
'Treg': '#FE664D',
'fibroblast': '#9f50f9',
'Myeloid': '#009203',
'tumor': '#e5e022',
'T': '#CB6035'}
[8]:
fstplt.celltype_proportion(data, ctype_hex_map, save_path=None)
Correlation
[5]:
os.chdir(str(path)+'FineST/FineST_local/Dataset/NPC/TransImp/')
prop_ref = pd.read_csv('celltype_prop_CRC16um_scRNAseq.csv', index_col=0).T
prop_sc = pd.read_csv('celltype_prop_NPC1_Visiun_nuclei.csv', index_col=0).T
prop_subspot = pd.read_csv('celltype_prop_NPC1_Visiun_spot.csv', index_col=0).T
[6]:
prop_ref = prop_ref.reset_index()
prop_ref = prop_ref.rename(columns={'NPC_Reference': 'scRNA-seq'})
prop_sc = prop_sc.reset_index()
prop_sc = prop_sc.rename(columns={'NPC1_TransImp': 'single-cell'})
prop_subspot = prop_subspot.reset_index()
prop_subspot = prop_subspot.rename(columns={ 'NPC1_paper': 'spot'})
print(prop_subspot)
index spot
0 tumor 0.528174
1 B 0.180316
2 fibroblast 0.106687
3 T 0.062359
4 normal 0.059354
5 Myeloid 0.059354
6 Treg 0.003757
[29]:
fstplt.plot_half_violin(prop_ref, prop_subspot, prop_sc,
variable_name = ['scRNA-seq', 'spot', 'single-cell'],
value_property='Proportion', property='PCC', fig_size=(2, 3.2), font_size=14,
save_path=None)
# save_path='prop_figure_3_cor.svg')
correlation for scRNA-seq vs spot: 0.4355819387182846
correlation for scRNA-seq vs single-cell: 0.6443514155411412
correlation for spot vs single-cell: 0.9650308876813465