comflow 0.0.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- comflow/__init__.py +10 -0
- comflow/_optimal_transport/__init__.py +13 -0
- comflow/_optimal_transport/_cot.py +850 -0
- comflow/_optimal_transport/_cot_preRevise.py +850 -0
- comflow/_optimal_transport/_unot.py +485 -0
- comflow/_optimal_transport/_usot.py +117 -0
- comflow/_utils/__init__.py +20 -0
- comflow/_utils/_binarization.py +43 -0
- comflow/_utils/_clustering.py +57 -0
- comflow/_utils/_plotting.py +398 -0
- comflow/_utils/_similarity.py +479 -0
- comflow/plotting/__init__.py +5 -0
- comflow/plotting/_plotting.py +794 -0
- comflow/preprocessing/__init__.py +3 -0
- comflow/preprocessing/_infer_spatial.py +161 -0
- comflow/preprocessing/_ligand_receptor_database.py +153 -0
- comflow/tools/__init__.py +12 -0
- comflow/tools/_downstream_analysis.py +870 -0
- comflow/tools/_spatial_communication.py +1250 -0
- comflow-0.0.3.dist-info/LICENSE.md +21 -0
- comflow-0.0.3.dist-info/METADATA +113 -0
- comflow-0.0.3.dist-info/RECORD +24 -0
- comflow-0.0.3.dist-info/WHEEL +5 -0
- comflow-0.0.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# %%
|
|
2
|
+
from xml.etree.ElementInclude import include
|
|
3
|
+
import igraph
|
|
4
|
+
import leidenalg
|
|
5
|
+
import numpy as np
|
|
6
|
+
from sklearn.neighbors import kneighbors_graph
|
|
7
|
+
|
|
8
|
+
def knn_graph(D,k):
|
|
9
|
+
"""Construct a k-nearest-neighbor graph as igraph object.
|
|
10
|
+
:param D: a distance matrix for constructing the knn graph
|
|
11
|
+
:type D: class:`numpy.ndarray`
|
|
12
|
+
:param k: number of nearest neighbors
|
|
13
|
+
:type k: int
|
|
14
|
+
:return: a knn graph object
|
|
15
|
+
:rtype: class:`igraph.Graph`
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
n = D.shape[0]
|
|
19
|
+
G = igraph.Graph()
|
|
20
|
+
G.add_vertices(n)
|
|
21
|
+
edges = []
|
|
22
|
+
weights = []
|
|
23
|
+
for i in range(n):
|
|
24
|
+
sorted_ind = np.argsort(D[i,:])
|
|
25
|
+
for j in range(1,1+k):
|
|
26
|
+
# if i < sorted_ind[j]:
|
|
27
|
+
edges.append( (i, sorted_ind[j]) )
|
|
28
|
+
weights.append(D[i, sorted_ind[j]])
|
|
29
|
+
# weights.append(1.)
|
|
30
|
+
G.add_edges(edges)
|
|
31
|
+
G.es['weight'] = weights
|
|
32
|
+
return G
|
|
33
|
+
|
|
34
|
+
def knn_graph_embedding(X, k):
|
|
35
|
+
A = kneighbors_graph(X, k, include_self=False, mode='distance')
|
|
36
|
+
G = igraph.Graph.Weighted_Adjacency(A)
|
|
37
|
+
return (G)
|
|
38
|
+
|
|
39
|
+
def leiden_clustering(
|
|
40
|
+
D,
|
|
41
|
+
k = 5,
|
|
42
|
+
resolution = 1.0,
|
|
43
|
+
random_seed = 1,
|
|
44
|
+
n_iterations = -1,
|
|
45
|
+
input = 'distance'
|
|
46
|
+
):
|
|
47
|
+
if input == 'distance':
|
|
48
|
+
G = knn_graph(D, k)
|
|
49
|
+
elif input == 'embedding':
|
|
50
|
+
G = knn_graph_embedding(D, k)
|
|
51
|
+
partition_kwargs = {'resolution_parameter':resolution,
|
|
52
|
+
'seed': random_seed,
|
|
53
|
+
'n_iterations': n_iterations}
|
|
54
|
+
part = leidenalg.find_partition(G, leidenalg.RBConfigurationVertexPartition,
|
|
55
|
+
**partition_kwargs)
|
|
56
|
+
return np.array( part.membership, int )
|
|
57
|
+
# %%
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
import plotly
|
|
4
|
+
import os
|
|
5
|
+
import matplotlib as mpl
|
|
6
|
+
import matplotlib.pyplot as plt
|
|
7
|
+
import networkx as nx
|
|
8
|
+
from sklearn.neighbors import NearestNeighbors
|
|
9
|
+
from sklearn.preprocessing import normalize
|
|
10
|
+
from scipy.stats import norm
|
|
11
|
+
from networkx.drawing.nx_agraph import to_agraph
|
|
12
|
+
|
|
13
|
+
def get_cmap_qualitative(cmap_name):
|
|
14
|
+
if cmap_name == "Plotly":
|
|
15
|
+
cmap = plotly.colors.qualitative.Plotly
|
|
16
|
+
elif cmap_name == "Alphabet":
|
|
17
|
+
cmap = plotly.colors.qualitative.Alphabet
|
|
18
|
+
elif cmap_name == "Light24":
|
|
19
|
+
cmap = plotly.colors.qualitative.Light24
|
|
20
|
+
elif cmap_name == "Dark24":
|
|
21
|
+
cmap = plotly.colors.qualitative.Dark24
|
|
22
|
+
# Safe and Vivid are strings of form "rbg(...)"
|
|
23
|
+
# Handle this later.
|
|
24
|
+
elif cmap_name == "Safe":
|
|
25
|
+
cmap = plotly.colors.qualitative.Safe
|
|
26
|
+
elif cmap_name == "Vivid":
|
|
27
|
+
cmap = plotly.colors.qualitative.Vivid
|
|
28
|
+
return cmap
|
|
29
|
+
|
|
30
|
+
def linear_clamp_value(x, lower_bound, upper_bound, out_min, out_max):
|
|
31
|
+
if x <= lower_bound:
|
|
32
|
+
y = out_min
|
|
33
|
+
elif x >= upper_bound:
|
|
34
|
+
y = out_max
|
|
35
|
+
else:
|
|
36
|
+
y = out_min + (x - lower_bound)/(upper_bound-lower_bound) * (out_max-out_min)
|
|
37
|
+
return y
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def plot_cluster_signaling_chord(S, p_values, label_name=None, colormap='Plotly', quantile_cutoff=None, p_value_cutoff=None, cutoff=0, separate=False, filename="chord_plot.pdf", diagonal_off=False):
|
|
41
|
+
cmap = get_cmap_qualitative(colormap)
|
|
42
|
+
data_all = np.empty([0,3], str)
|
|
43
|
+
if not quantile_cutoff is None:
|
|
44
|
+
cutoff = np.quantile(S.reshape(-1), quantile_cutoff)
|
|
45
|
+
for i in range(S.shape[0]):
|
|
46
|
+
for j in range(S.shape[1]):
|
|
47
|
+
if diagonal_off and i==j: continue
|
|
48
|
+
if S[i,j] >= cutoff or p_values[i,j] <= p_value_cutoff:
|
|
49
|
+
if not label_name is None:
|
|
50
|
+
if separate:
|
|
51
|
+
data = np.array([['S'+label_name[i], 'T'+label_name[j], str(S[i,j])]], str)
|
|
52
|
+
else:
|
|
53
|
+
data = np.array([[label_name[i], label_name[j], str(S[i,j])]], str)
|
|
54
|
+
else:
|
|
55
|
+
if separate:
|
|
56
|
+
data = np.array([['S'+str(i), 'T'+str(j), str(S[i,j])]], str)
|
|
57
|
+
else:
|
|
58
|
+
data = np.array([[str(i), str(j), str(S[i,j])]], str)
|
|
59
|
+
data_all = np.concatenate((data_all, data), axis=0)
|
|
60
|
+
df = pd.DataFrame(data=data_all, columns=['from','to','value'])
|
|
61
|
+
df.to_csv("./plot_chord_data.csv", index=False)
|
|
62
|
+
|
|
63
|
+
data_cmap = np.empty([0, 2], str)
|
|
64
|
+
for i in range(S.shape[0]):
|
|
65
|
+
if not label_name is None:
|
|
66
|
+
if separate:
|
|
67
|
+
data_tmp = np.array([['S'+label_name[i], cmap[i % len(cmap)]],['T'+label_name[i], cmap[i % len(cmap)]]], str)
|
|
68
|
+
else:
|
|
69
|
+
data_tmp = np.array([[label_name[i], cmap[i % len(cmap)]]], str)
|
|
70
|
+
else:
|
|
71
|
+
if separate:
|
|
72
|
+
data_tmp = np.array([['S'+str(i), cmap[i % len(cmap)]],['T'+str(i), cmap[i % len(cmap)]]], str)
|
|
73
|
+
else:
|
|
74
|
+
data_tmp = np.array([[str(i), cmap[i % len(cmap)]]], str)
|
|
75
|
+
data_cmap = np.concatenate((data_cmap, data_tmp), axis=0)
|
|
76
|
+
df = pd.DataFrame(data=data_cmap)
|
|
77
|
+
df.to_csv("./plot_chord_cmap.csv", index=False, header=False)
|
|
78
|
+
|
|
79
|
+
os.system("Rscript plot_chord.R")
|
|
80
|
+
os.system("mv Rplots.pdf "+filename)
|
|
81
|
+
os.system("pdfcrop %s %s" % (filename, filename))
|
|
82
|
+
filename_png = filename[:-4]
|
|
83
|
+
filename_png = filename_png + ".png"
|
|
84
|
+
os.system("convert -density 800 %s -quality 100 %s" % (filename, filename_png))
|
|
85
|
+
|
|
86
|
+
def plot_cluster_signaling_network(S,
|
|
87
|
+
labels = None,
|
|
88
|
+
node_size = 0.2,
|
|
89
|
+
node_colormap = "Plotly",
|
|
90
|
+
node_cluster_colormap = None,
|
|
91
|
+
node_pos = None,
|
|
92
|
+
edge_width_lb_quantile = 0.05,
|
|
93
|
+
edge_width_ub_quantile = 0.95,
|
|
94
|
+
edge_width_min = 1,
|
|
95
|
+
edge_width_max = 4,
|
|
96
|
+
edge_color = None, # expect to range from 0 to 1
|
|
97
|
+
edge_colormap = None,
|
|
98
|
+
background_pos = None,
|
|
99
|
+
background_ndcolor = "lavender",
|
|
100
|
+
background_ndsize = 1,
|
|
101
|
+
filename = "network_plot.pdf",
|
|
102
|
+
):
|
|
103
|
+
if labels is None:
|
|
104
|
+
labels = [str(i) for i in range(S.shape[0])]
|
|
105
|
+
node_cmap = get_cmap_qualitative(node_colormap)
|
|
106
|
+
G = nx.MultiDiGraph()
|
|
107
|
+
|
|
108
|
+
edge_width_lb = np.quantile(S.reshape(-1), edge_width_lb_quantile)
|
|
109
|
+
edge_width_ub = np.quantile(S.reshape(-1), edge_width_ub_quantile)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# Draw the background geometry
|
|
113
|
+
if not background_pos is None:
|
|
114
|
+
for i in range(background_pos.shape[0]):
|
|
115
|
+
G.add_node("cell_"+str(i), shape='point', color=background_ndcolor, fillcolor=background_ndcolor, width=background_ndsize)
|
|
116
|
+
G.nodes["cell_"+str(i)]["pos"] = "%f,%f!" %(background_pos[i,0],background_pos[i,1])
|
|
117
|
+
|
|
118
|
+
# Draw the nodes (cluster)
|
|
119
|
+
for i in range(len(labels)):
|
|
120
|
+
if node_cluster_colormap is None:
|
|
121
|
+
G.add_node(labels[i], shape="point", fillcolor=node_cmap[i], color=node_cmap[i])
|
|
122
|
+
elif not node_cluster_colormap is None:
|
|
123
|
+
G.add_node(labels[i], shape="point", fillcolor=node_cluster_colormap[labels[i]], color=node_cmap[i])
|
|
124
|
+
if not node_pos is None:
|
|
125
|
+
G.nodes[labels[i]]["pos"] = "%f,%f!" % (node_pos[i,0],node_pos[i,1])
|
|
126
|
+
G.nodes[labels[i]]["width"] = str(node_size)
|
|
127
|
+
|
|
128
|
+
# Draw the edges
|
|
129
|
+
for i in range(S.shape[0]):
|
|
130
|
+
for j in range(S.shape[1]):
|
|
131
|
+
if S[i,j] > 0:
|
|
132
|
+
G.add_edge(labels[i], labels[j], splines="curved")
|
|
133
|
+
G[labels[i]][labels[j]][0]["penwidth"] = str(linear_clamp_value(S[i,j],edge_width_lb,edge_width_ub,edge_width_min,edge_width_max))
|
|
134
|
+
if edge_color == "node":
|
|
135
|
+
G[labels[i]][labels[j]][0]['color'] = node_cmap[i]
|
|
136
|
+
elif isinstance(edge_color, np.ndarray):
|
|
137
|
+
G[labels[i]][labels[j]][0]['color'] = mpl.colors.to_hex( edge_colormap(edge_color[i,j]) )
|
|
138
|
+
else:
|
|
139
|
+
G[labels[i]][labels[j]][0]['color'] = edge_color
|
|
140
|
+
|
|
141
|
+
# Draw the network
|
|
142
|
+
A = to_agraph(G)
|
|
143
|
+
if node_pos is None:
|
|
144
|
+
A.layout("dot")
|
|
145
|
+
else:
|
|
146
|
+
A.layout()
|
|
147
|
+
A.draw(filename)
|
|
148
|
+
|
|
149
|
+
# Recommend plotting at most three LR species
|
|
150
|
+
def plot_cluster_signaling_network_multipair(S_list,
|
|
151
|
+
p_values_list,
|
|
152
|
+
labels = None,
|
|
153
|
+
quantile_cutoff = None,
|
|
154
|
+
p_value_cutoff = 0.05,
|
|
155
|
+
node_size = 0.2,
|
|
156
|
+
node_colormap = "Plotly",
|
|
157
|
+
node_pos = None,
|
|
158
|
+
edge_width_lb_quantile = 0.05,
|
|
159
|
+
edge_width_ub_quantile = 0.95,
|
|
160
|
+
edge_width_min = 1,
|
|
161
|
+
edge_width_max = 4,
|
|
162
|
+
edge_colors = ["blue","red","green","grey","yellow"],
|
|
163
|
+
background_pos = None,
|
|
164
|
+
background_ndcolor = "darkseagreen1",
|
|
165
|
+
background_ndsize = 1,
|
|
166
|
+
filename = "network_plot.pdf"
|
|
167
|
+
):
|
|
168
|
+
tmp_all_S = []
|
|
169
|
+
for S in S_list:
|
|
170
|
+
tmp_all_S.extend( list( S.reshape(-1) ) )
|
|
171
|
+
tmp_all_S = np.array(tmp_all_S)
|
|
172
|
+
if labels is None:
|
|
173
|
+
labels = [str(i) for i in range(S.shape[0])]
|
|
174
|
+
node_cmap = get_cmap_qualitative(node_colormap)
|
|
175
|
+
G = nx.MultiDiGraph()
|
|
176
|
+
if not quantile_cutoff is None:
|
|
177
|
+
cutoff = np.quantile(tmp_all_S.reshape(-1), quantile_cutoff)
|
|
178
|
+
else:
|
|
179
|
+
cutoff = 0.0
|
|
180
|
+
edge_width_lb = np.quantile(tmp_all_S.reshape(-1), edge_width_lb_quantile)
|
|
181
|
+
edge_width_ub = np.quantile(tmp_all_S.reshape(-1), edge_width_ub_quantile)
|
|
182
|
+
|
|
183
|
+
# Draw the background geometry
|
|
184
|
+
if not background_pos is None:
|
|
185
|
+
for i in range(background_pos.shape[0]):
|
|
186
|
+
G.add_node("cell_"+str(i), shape='point', color=background_ndcolor, fillcolor=background_ndcolor, width=background_ndsize)
|
|
187
|
+
G.nodes["cell_"+str(i)]["pos"] = "%f,%f!" %(background_pos[i,0],background_pos[i,1])
|
|
188
|
+
|
|
189
|
+
# Draw the nodes (cluster)
|
|
190
|
+
for i in range(len(labels)):
|
|
191
|
+
G.add_node(labels[i], shape="point", fillcolor=node_cmap[i], color=node_cmap[i])
|
|
192
|
+
if not node_pos is None:
|
|
193
|
+
G.nodes[labels[i]]["pos"] = "%f,%f!" % (node_pos[i,0],node_pos[i,1])
|
|
194
|
+
G.nodes[labels[i]]["width"] = str(node_size)
|
|
195
|
+
|
|
196
|
+
# Draw the edges
|
|
197
|
+
for k in range(len(S_list)):
|
|
198
|
+
S = S_list[k]
|
|
199
|
+
p_values = p_values_list[k]
|
|
200
|
+
for i in range(S.shape[0]):
|
|
201
|
+
for j in range(S.shape[1]):
|
|
202
|
+
if S[i,j] >= cutoff or p_values[i,j] <= p_value_cutoff:
|
|
203
|
+
penwidth = str(linear_clamp_value(S[i,j],edge_width_lb,edge_width_ub,edge_width_min,edge_width_max))
|
|
204
|
+
color = edge_colors[k]
|
|
205
|
+
G.add_edge(labels[i], labels[j], splines="curved", penwidth=penwidth, color=color)
|
|
206
|
+
|
|
207
|
+
# Draw the network
|
|
208
|
+
A = to_agraph(G)
|
|
209
|
+
if node_pos is None:
|
|
210
|
+
A.layout("dot")
|
|
211
|
+
else:
|
|
212
|
+
A.layout()
|
|
213
|
+
A.draw(filename)
|
|
214
|
+
|
|
215
|
+
def plot_cell_signaling(X,
|
|
216
|
+
V,
|
|
217
|
+
signal_sum,
|
|
218
|
+
cmap="coolwarm",
|
|
219
|
+
cluster_cmap = None,
|
|
220
|
+
arrow_color="tab:blue",
|
|
221
|
+
plot_method="cell",
|
|
222
|
+
background='summary',
|
|
223
|
+
clustering=None,
|
|
224
|
+
background_legend=False,
|
|
225
|
+
adata=None,
|
|
226
|
+
summary='sender',
|
|
227
|
+
ndsize = 1,
|
|
228
|
+
scale = 1.0,
|
|
229
|
+
grid_density = 1,
|
|
230
|
+
grid_knn = None,
|
|
231
|
+
grid_scale = 1.0,
|
|
232
|
+
grid_thresh = 1.0,
|
|
233
|
+
grid_width = 0.005,
|
|
234
|
+
stream_density = 1.0,
|
|
235
|
+
stream_linewidth = 1,
|
|
236
|
+
stream_cutoff_perc = 5,
|
|
237
|
+
filename=None,
|
|
238
|
+
ax = None,
|
|
239
|
+
fig = None
|
|
240
|
+
):
|
|
241
|
+
ndcolor = signal_sum
|
|
242
|
+
ncell = X.shape[0]
|
|
243
|
+
|
|
244
|
+
V_cell = V.copy()
|
|
245
|
+
V_cell_sum = np.sum(V_cell, axis=1)
|
|
246
|
+
V_cell[np.where(V_cell_sum==0)[0],:] = np.nan
|
|
247
|
+
if summary == "sender":
|
|
248
|
+
X_vec = X
|
|
249
|
+
elif summary == "receiver":
|
|
250
|
+
X_vec = X - V / scale
|
|
251
|
+
|
|
252
|
+
if plot_method == "grid" or plot_method == "stream":
|
|
253
|
+
# Get a rectangular grid
|
|
254
|
+
xl, xr = np.min(X[:,0]), np.max(X[:,0])
|
|
255
|
+
epsilon = 0.02*(xr-xl); xl -= epsilon; xr += epsilon
|
|
256
|
+
yl, yr = np.min(X[:,1]), np.max(X[:,1])
|
|
257
|
+
epsilon = 0.02*(yr-yl); yl -= epsilon; yr += epsilon
|
|
258
|
+
ngrid_x = int(50 * grid_density)
|
|
259
|
+
gridsize = (xr-xl) / float(ngrid_x)
|
|
260
|
+
ngrid_y = int((yr-yl)/gridsize)
|
|
261
|
+
meshgrid = np.meshgrid(np.linspace(xl,xr,ngrid_x), np.linspace(yl,yr,ngrid_y))
|
|
262
|
+
grid_pts = np.concatenate((meshgrid[0].reshape(-1,1), meshgrid[1].reshape(-1,1)), axis=1)
|
|
263
|
+
|
|
264
|
+
if grid_knn is None:
|
|
265
|
+
grid_knn = int( X.shape[0] / 50 )
|
|
266
|
+
nn_mdl = NearestNeighbors()
|
|
267
|
+
nn_mdl.fit(X)
|
|
268
|
+
dis, nbs = nn_mdl.kneighbors(grid_pts, n_neighbors=grid_knn)
|
|
269
|
+
w = norm.pdf(x=dis, scale=gridsize * grid_scale)
|
|
270
|
+
w_sum = w.sum(axis=1)
|
|
271
|
+
|
|
272
|
+
V_grid = (V[nbs] * w[:,:,None]).sum(axis=1)
|
|
273
|
+
V_grid /= np.maximum(1, w_sum)[:,None]
|
|
274
|
+
|
|
275
|
+
if plot_method == "grid":
|
|
276
|
+
grid_thresh *= np.percentile(w_sum, 99) / 100
|
|
277
|
+
grid_pts, V_grid = grid_pts[w_sum > grid_thresh], V_grid[w_sum > grid_thresh]
|
|
278
|
+
elif plot_method == "stream":
|
|
279
|
+
x_grid = np.linspace(xl, xr, ngrid_x)
|
|
280
|
+
y_grid = np.linspace(yl, yr, ngrid_y)
|
|
281
|
+
V_grid = V_grid.T.reshape(2, ngrid_y, ngrid_x)
|
|
282
|
+
vlen = np.sqrt((V_grid ** 2).sum(0))
|
|
283
|
+
grid_thresh = 10 ** (grid_thresh - 6)
|
|
284
|
+
grid_thresh = np.clip(grid_thresh, None, np.max(vlen) * 0.9)
|
|
285
|
+
cutoff = vlen.reshape(V_grid[0].shape) < grid_thresh
|
|
286
|
+
length = np.sum(np.mean(np.abs(V[nbs]),axis=1),axis=1).T
|
|
287
|
+
length = length.reshape(ngrid_y, ngrid_x)
|
|
288
|
+
cutoff |= length < np.percentile(length, stream_cutoff_perc)
|
|
289
|
+
|
|
290
|
+
V_grid[0][cutoff] = np.nan
|
|
291
|
+
|
|
292
|
+
if cmap == 'Plotly':
|
|
293
|
+
cmap = plotly.colors.qualitative.Plotly
|
|
294
|
+
elif cmap == 'Light24':
|
|
295
|
+
cmap = plotly.colors.qualitative.Light24
|
|
296
|
+
elif cmap == 'Dark24':
|
|
297
|
+
cmap = plotly.colors.qualitative.Dark24
|
|
298
|
+
elif cmap == 'Alphabet':
|
|
299
|
+
cmap = plotly.colors.qualitative.Alphabet
|
|
300
|
+
|
|
301
|
+
idx = np.argsort(ndcolor)
|
|
302
|
+
if background == 'summary' or background == 'cluster':
|
|
303
|
+
if not ndsize==0:
|
|
304
|
+
if background == 'summary':
|
|
305
|
+
ax.scatter(X[idx,0], X[idx,1], s=ndsize, c=ndcolor[idx], cmap=cmap, linewidth=0)
|
|
306
|
+
elif background == 'cluster':
|
|
307
|
+
labels = np.array( adata.obs[clustering], str )
|
|
308
|
+
unique_labels = np.sort(list(set(list(labels))))
|
|
309
|
+
for i_label in range(len(unique_labels)):
|
|
310
|
+
idx = np.where(labels == unique_labels[i_label])[0]
|
|
311
|
+
if cluster_cmap is None:
|
|
312
|
+
ax.scatter(X[idx,0], X[idx,1], s=ndsize, c=cmap[i_label], linewidth=0, label=unique_labels[i_label])
|
|
313
|
+
elif not cluster_cmap is None:
|
|
314
|
+
ax.scatter(X[idx,0], X[idx,1], s=ndsize, c=cluster_cmap[unique_labels[i_label]], linewidth=0, label=unique_labels[i_label])
|
|
315
|
+
if background_legend:
|
|
316
|
+
ax.legend(markerscale=2.0, loc=[1.0,0.0])
|
|
317
|
+
if plot_method == "cell":
|
|
318
|
+
ax.quiver(X_vec[:,0], X_vec[:,1], V_cell[:,0], V_cell[:,1], scale=scale, scale_units='x', color=arrow_color)
|
|
319
|
+
elif plot_method == "grid":
|
|
320
|
+
ax.quiver(grid_pts[:,0], grid_pts[:,1], V_grid[:,0], V_grid[:,1], scale=scale, scale_units='x', width=grid_width, color=arrow_color)
|
|
321
|
+
elif plot_method == "stream":
|
|
322
|
+
lengths = np.sqrt((V_grid ** 2).sum(0))
|
|
323
|
+
stream_linewidth *= 2 * lengths / lengths[~np.isnan(lengths)].max()
|
|
324
|
+
ax.streamplot(x_grid, y_grid, V_grid[0], V_grid[1], color=arrow_color, density=stream_density, linewidth=stream_linewidth)
|
|
325
|
+
elif background == 'image':
|
|
326
|
+
spatial_mapping = adata.uns.get("spatial", {})
|
|
327
|
+
library_id = list(spatial_mapping.keys())[0]
|
|
328
|
+
spatial_data = spatial_mapping[library_id]
|
|
329
|
+
img = spatial_data['images']['hires']
|
|
330
|
+
sf = spatial_data['scalefactors']['tissue_hires_scalef']
|
|
331
|
+
ax.imshow(img, origin='lower')
|
|
332
|
+
if plot_method == "cell":
|
|
333
|
+
ax.quiver(X_vec[:,0]*sf, X_vec[:,1]*sf, V_cell[:,0]*sf, V_cell[:,1]*sf, scale=scale, scale_units='x', color=arrow_color)
|
|
334
|
+
elif plot_method == "grid":
|
|
335
|
+
ax.quiver(grid_pts[:,0]*sf, grid_pts[:,1]*sf, V_grid[:,0]*sf, V_grid[:,1]*sf, scale=scale, scale_units='x', width=grid_width, color=arrow_color)
|
|
336
|
+
elif plot_method == "stream":
|
|
337
|
+
lengths = np.sqrt((V_grid ** 2).sum(0))
|
|
338
|
+
stream_linewidth *= 2 * lengths / lengths[~np.isnan(lengths)].max()
|
|
339
|
+
ax.streamplot(x_grid*sf, y_grid*sf, V_grid[0]*sf, V_grid[1]*sf, color=arrow_color, density=stream_density, linewidth=stream_linewidth)
|
|
340
|
+
|
|
341
|
+
ax.axis("equal")
|
|
342
|
+
ax.axis("off")
|
|
343
|
+
if not filename is None:
|
|
344
|
+
plt.savefig(filename, dpi=500, bbox_inches = 'tight', transparent=True)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def plot_cell_signaling_compare(X,
|
|
348
|
+
V,
|
|
349
|
+
ax,
|
|
350
|
+
arrow_color="tab:blue",
|
|
351
|
+
plot_method="cell",
|
|
352
|
+
summary='sender',
|
|
353
|
+
scale = 1.0,
|
|
354
|
+
grid_density = 1,
|
|
355
|
+
grid_knn = None,
|
|
356
|
+
grid_scale = 1.0,
|
|
357
|
+
grid_thresh = 1.0,
|
|
358
|
+
):
|
|
359
|
+
V_cell = V.copy()
|
|
360
|
+
V_cell_sum = np.sum(V_cell, axis=1)
|
|
361
|
+
V_cell[np.where(V_cell_sum==0)[0],:] = np.nan
|
|
362
|
+
if summary == "sender":
|
|
363
|
+
X_vec = X
|
|
364
|
+
elif summary == "receiver":
|
|
365
|
+
X_vec = X - V / scale
|
|
366
|
+
|
|
367
|
+
if plot_method == "grid":
|
|
368
|
+
# Get a rectangular grid
|
|
369
|
+
xl, xr = np.min(X[:,0]), np.max(X[:,0])
|
|
370
|
+
epsilon = 0.02*(xr-xl); xl -= epsilon; xr += epsilon
|
|
371
|
+
yl, yr = np.min(X[:,1]), np.max(X[:,1])
|
|
372
|
+
epsilon = 0.02*(yr-yl); yl -= epsilon; yr += epsilon
|
|
373
|
+
ngrid_x = int(50 * grid_density)
|
|
374
|
+
gridsize = (xr-xl) / float(ngrid_x)
|
|
375
|
+
ngrid_y = int((yr-yl)/gridsize)
|
|
376
|
+
meshgrid = np.meshgrid(np.linspace(xl,xr,ngrid_x), np.linspace(yl,yr,ngrid_y))
|
|
377
|
+
grid_pts = np.concatenate((meshgrid[0].reshape(-1,1), meshgrid[1].reshape(-1,1)), axis=1)
|
|
378
|
+
|
|
379
|
+
if grid_knn is None:
|
|
380
|
+
grid_knn = int( X.shape[0] / 50 )
|
|
381
|
+
nn_mdl = NearestNeighbors()
|
|
382
|
+
nn_mdl.fit(X)
|
|
383
|
+
dis, nbs = nn_mdl.kneighbors(grid_pts, n_neighbors=grid_knn)
|
|
384
|
+
w = norm.pdf(x=dis, scale=gridsize * grid_scale)
|
|
385
|
+
w_sum = w.sum(axis=1)
|
|
386
|
+
|
|
387
|
+
V_grid = (V[nbs] * w[:,:,None]).sum(axis=1)
|
|
388
|
+
V_grid /= np.maximum(1, w_sum)[:,None]
|
|
389
|
+
|
|
390
|
+
if plot_method == "grid":
|
|
391
|
+
grid_thresh *= np.percentile(w_sum, 99) / 100
|
|
392
|
+
grid_pts, V_grid = grid_pts[w_sum > grid_thresh], V_grid[w_sum > grid_thresh]
|
|
393
|
+
|
|
394
|
+
if plot_method == "cell":
|
|
395
|
+
ax.quiver(X_vec[:,0], X_vec[:,1], V_cell[:,0], V_cell[:,1], scale=scale, scale_units='x', color=arrow_color, alpha=1.0)
|
|
396
|
+
elif plot_method == "grid":
|
|
397
|
+
ax.quiver(grid_pts[:,0], grid_pts[:,1], V_grid[:,0], V_grid[:,1], scale=scale, scale_units='x', color=arrow_color, alpha=1.0)
|
|
398
|
+
return ax
|