-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_cellrank2.py
More file actions
178 lines (164 loc) · 8.26 KB
/
Copy pathrun_cellrank2.py
File metadata and controls
178 lines (164 loc) · 8.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import os
import random
import argparse
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
import pandas as pd
import scanpy as sc
import scvelo as scv
import cellrank as cr
class Experiment:
def __init__(self, args):
adata = sc.read_h5ad(args.adata_file)
self.args = args
self.seed_everything(args.seed)
self.adata = adata
self.preprocess()
self.predict_key = 'louvain'
self.nclasses = len(self.adata.obs['cluster'].unique())
def seed_everything(self, seed):
np.random.seed(seed)
random.seed(seed)
sc.settings.verbosity = 2
cr.settings.verbosity = 2
scv.settings.verbosity = 3
scv.settings.set_figure_params('scvelo', dpi_save=400, dpi=80, transparent=True, fontsize=20,
color_map='viridis')
scv.settings.plot_prefix = ""
def preprocess(self):
if 'cluster' not in self.adata.obs.keys():
gt_clusters = pd.Series(index=self.adata.obs_names)
for obs_name in self.adata.obs_names:
res = (self.adata.uns['milestone_percentages']['cell_id'] == obs_name)
milestones = self.adata.uns['milestone_percentages'].loc[res, 'milestone_id']
percentages = self.adata.uns['milestone_percentages'].loc[res, 'percentage']
cluster_id = milestones.loc[percentages.idxmax()]
gt_clusters.loc[obs_name] = cluster_id
self.adata.obs['cluster'] = gt_clusters
def run_velocity(self):
sc.pp.filter_genes(self.adata, min_cells=10)
sc.pp.normalize_total(self.adata, target_sum=1e4)
sc.pp.log1p(self.adata)
sc.pp.highly_variable_genes(self.adata, flavor='cell_ranger', n_top_genes=1500)
sc.pp.pca(self.adata, use_highly_variable=True, n_comps=50, random_state=self.args.seed)
sc.pp.neighbors(self.adata, n_pcs=30, n_neighbors=self.args.n_neighbors, random_state=self.args.seed)
sc.tl.umap(self.adata)
def load_params(self):
if self.args.dataname == 'loh':
return 4
elif self.args.dataname == 'zhang':
return 2
elif self.args.dataname == 'guo':
return 2
elif self.args.dataname == 'sloan':
return 2
else:
raise ValueError(f'Unknown dataset: {self.args.dataname}')
def run_cellrank(self):
self.adata.obs['cluster'] = self.adata.obs['cluster'].astype('category')
vk = cr.kernels.ConnectivityKernel(self.adata)
vk.compute_transition_matrix()
clusters = self.adata.obs['cluster'].cat.categories
paired_colors = sns.color_palette("Paired", n_colors=len(clusters))
hex_colors = [mcolors.rgb2hex(color) for color in paired_colors]
color_map = dict(zip(clusters, hex_colors))
self.adata.obs['timecourse'] = pd.Categorical(self.adata.uns['timecourse'])
sc.pl.embedding(self.adata, basis="umap", color="cluster", legend_loc="on data", frameon=False, show=True,
save=f'_{self.args.dataname}.png', palette=color_map)
g = cr.estimators.GPCCA(vk)
g.fit(cluster_key="cluster", n_states=self.load_params())
g.plot_macrostates(which="all", discrete=True, legend_loc="right", s=100,
show=True, save=f'{self.args.dataname}_all_states.png')
g.predict_initial_states(n_states=1, n_cells=1)
g.plot_macrostates(which="initial", legend_loc="right", s=100,
show=True, save=f'{self.args.dataname}_initial.png')
def plot_initial_cells(self, method='CellRank'):
from scipy.stats import spearmanr
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 12))
pseudotime1 = self.adata.obs[f'{method}_pseudotime']
pseudotime2 = self.adata.obs[f'{method}_pseudotime_predict']
timecourse = self.adata.obs['timecourse']
bins = 6
pseudotime1_binned = pd.cut(pseudotime1, bins=bins, labels=range(bins), include_lowest=True)
pseudotime2_binned = pd.cut(pseudotime2, bins=bins, labels=range(bins), include_lowest=True)
scatter1 = ax1.scatter(self.adata.obsm['X_umap'][:, 0], self.adata.obsm['X_umap'][:, 1],
c=pseudotime1_binned, cmap='Paired', s=30)
start_idx = self.adata.obs_names.tolist().index(self.adata.uns['start_id'])
ax1.scatter(self.adata.obsm['X_umap'][start_idx, 0], self.adata.obsm['X_umap'][start_idx, 1],c='red', s=100, label='Start Cell')
sr_p1_timecourse, pval_p1_timecourse = spearmanr(pseudotime1_binned, timecourse)
sr_p2_timecourse, pval_p2_timecourse = spearmanr(pseudotime2_binned, timecourse)
print(
f"Spearman Correlation (pseudotime1 vs timecourse): {sr_p1_timecourse:.4f}, p-value: {pval_p1_timecourse:.4e}")
print(
f"Spearman Correlation (pseudotime2 vs timecourse): {sr_p2_timecourse:.4f}, p-value: {pval_p2_timecourse:.4e}")
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_xlabel('')
ax1.set_ylabel('')
ax1.spines['top'].set_visible(False)
ax1.spines['right'].set_visible(False)
ax1.spines['left'].set_visible(False)
ax1.spines['bottom'].set_visible(False)
ax1.set_title(f'{method} Pseudotime SR={sr_p1_timecourse:.4f}', fontsize=25)
scatter2 = ax2.scatter(self.adata.obsm['X_umap'][:, 0], self.adata.obsm['X_umap'][:, 1],
c=pseudotime2_binned, cmap='Paired', s=30)
start_idx = self.adata.obs_names.tolist().index(self.adata.uns['start_id_2'])
ax2.scatter(self.adata.obsm['X_umap'][start_idx, 0], self.adata.obsm['X_umap'][start_idx, 1], c='blue', s=100,
label='Predict Start Cell')
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_xlabel('')
ax2.set_ylabel('')
ax2.spines['top'].set_visible(False)
ax2.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax2.spines['bottom'].set_visible(False)
ax2.set_title(f'{method} Pseudotime SR={sr_p2_timecourse:.4f}', fontsize=25)
plt.tight_layout()
plt.savefig(f'./figures/{method}_pseudotime_comparison.png', bbox_inches='tight')
plt.show()
def load_pseudotimes(self):
files = os.listdir("./pseudotimes")
print("Files in pseudotimes directory:", files)
methods = set(f.split('_')[0] for f in files if f.endswith('.npy'))
print("Methods found:", methods)
for m in methods:
file_path = f"./pseudotimes/{m}_start.npy"
if os.path.exists(file_path):
pseudotime = np.load(file_path)
self.adata.obs[m + '_pseudotime'] = pseudotime
print(f"Loaded {m} pseudotime with shape: {pseudotime.shape}")
else:
print(f"File {file_path} does not exist.")
file_path = f"./pseudotimes/{m}_start_2.npy"
if os.path.exists(file_path):
pseudotime = np.load(file_path)
self.adata.obs[m + '_pseudotime_predict'] = pseudotime
print(f"Loaded {m} pseudotime with shape: {pseudotime.shape}")
else:
print(f"File {file_path} does not exist.")
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--dataname', type=str, default="zhang")
parser.add_argument('--adata_file', type=str, default='../dataset/scdata/')
parser.add_argument('--img_path', type=str, default='../img/scimg/')
parser.add_argument('--out_path', type=str, default='./result/')
parser.add_argument('--n_neighbors', type=int, default=30)
parser.add_argument('--seed', type=int, default=1)
return parser.parse_args()
if __name__ == '__main__':
args = parse_arguments()
args.adata_file = args.adata_file + args.dataname + '/data.h5ad'
exp = Experiment(args)
exp.run_velocity()
exp.run_cellrank()
# exp.load_pseudotimes()
# exp.plot_initial_cells(method='PAGA')
# exp.plot_initial_cells(method='Palantir')
# exp.plot_initial_cells(method='VIA')
# exp.plot_initial_cells(method='Monocle3')
# exp.plot_initial_cells(method='Margaret')
# exp.plot_initial_cells(method='CASCAT')
# exp.plot_initial_cells(method='CellRank')