cc-mapping 0.1.0__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.
- cc_mapping/__init__.py +23 -0
- cc_mapping/core.py +360 -0
- cc_mapping/manifold.py +314 -0
- cc_mapping/plot.py +495 -0
- cc_mapping/preprocess.py +38 -0
- cc_mapping/pseudotime.py +284 -0
- cc_mapping/thresholding/__init__.py +60 -0
- cc_mapping/thresholding/base.py +1446 -0
- cc_mapping/thresholding/sequential.py +1441 -0
- cc_mapping/thresholding/single.py +828 -0
- cc_mapping/utils.py +192 -0
- cc_mapping/utils_v0.py +385 -0
- cc_mapping-0.1.0.dist-info/LICENSE +19 -0
- cc_mapping-0.1.0.dist-info/METADATA +226 -0
- cc_mapping-0.1.0.dist-info/RECORD +16 -0
- cc_mapping-0.1.0.dist-info/WHEEL +4 -0
cc_mapping/plot.py
ADDED
|
@@ -0,0 +1,495 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import itertools
|
|
4
|
+
import os
|
|
5
|
+
from math import ceil, floor
|
|
6
|
+
|
|
7
|
+
import anndata as ad
|
|
8
|
+
import matplotlib as mpl
|
|
9
|
+
import matplotlib._pylab_helpers
|
|
10
|
+
import matplotlib.patches as mpatches
|
|
11
|
+
import matplotlib.pyplot as plt
|
|
12
|
+
import numpy as np
|
|
13
|
+
import pandas as pd
|
|
14
|
+
|
|
15
|
+
from .utils import get_str_idx
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def plot_row_partitions(
|
|
19
|
+
adata: ad.AnnData,
|
|
20
|
+
obs_search_term: str,
|
|
21
|
+
colors: list | np.ndarray = None,
|
|
22
|
+
column_labels: list | np.ndarray = None,
|
|
23
|
+
obs_embedding_key: str = "X_phate",
|
|
24
|
+
kwargs: dict = None,
|
|
25
|
+
plot_all: bool = True,
|
|
26
|
+
plot_background: bool = True,
|
|
27
|
+
unit_size: int = 20,
|
|
28
|
+
save_path: str = None,
|
|
29
|
+
):
|
|
30
|
+
"""
|
|
31
|
+
Plot row partitions of the given AnnData object.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
adata (ad.AnnData): The AnnData object containing the data.
|
|
35
|
+
obs_search_term (str): The search term for selecting the observations.
|
|
36
|
+
colors (list | np.ndarray, optional): List or array of colors for the plot. Defaults to None.
|
|
37
|
+
column_labels (list | np.ndarray, optional): List or array of column labels. Defaults to None.
|
|
38
|
+
obs_embedding_key (str, optional): The key for the observation embedding. Defaults to 'X_phate'.
|
|
39
|
+
kwargs (dict, optional): Additional keyword arguments for the plotting function. Defaults to None.
|
|
40
|
+
plot_all (bool, optional): Whether to plot all partitions. Defaults to True.
|
|
41
|
+
plot_background (bool, optional): Whether to plot the background. Defaults to True.
|
|
42
|
+
unit_size (int, optional): The size of each unit in the plot. Defaults to 20.
|
|
43
|
+
save_path (str, optional): The path to save the plot. Defaults to None.
|
|
44
|
+
|
|
45
|
+
Raises:
|
|
46
|
+
ValueError: If the save directory does not exist.
|
|
47
|
+
|
|
48
|
+
Returns:
|
|
49
|
+
None
|
|
50
|
+
"""
|
|
51
|
+
if save_path is not None:
|
|
52
|
+
save_dir = os.path.dirname(save_path)
|
|
53
|
+
if not os.path.exists(save_dir):
|
|
54
|
+
raise ValueError(f"{save_dir} does not exist")
|
|
55
|
+
|
|
56
|
+
plotting_function = row_partition_plotting_function
|
|
57
|
+
|
|
58
|
+
if kwargs is None:
|
|
59
|
+
kwargs = {}
|
|
60
|
+
|
|
61
|
+
plotting_dict = {
|
|
62
|
+
"adata": adata,
|
|
63
|
+
"Lof_colors": colors,
|
|
64
|
+
"obs_search_term": obs_search_term,
|
|
65
|
+
"obs_embedding_key": obs_embedding_key,
|
|
66
|
+
"plot_background": plot_background,
|
|
67
|
+
"kwargs": kwargs,
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if column_labels is not None:
|
|
71
|
+
plotting_dict["column_labels"] = column_labels
|
|
72
|
+
|
|
73
|
+
fig = general_plotting_function(
|
|
74
|
+
plotting_function, {}, plotting_dict, unit_size=unit_size, plot_all=plot_all
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
if save_path is not None:
|
|
78
|
+
fig.savefig(save_path, dpi=300, bbox_inches="tight")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def row_partition_plotting_function(ax, idx_dict, plotting_dict):
|
|
82
|
+
"""
|
|
83
|
+
Plotting function for row partition.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
ax (matplotlib.axes.Axes): The axes on which to plot.
|
|
87
|
+
idx_dict (dict): A dictionary containing row and column indices.
|
|
88
|
+
plotting_dict (dict): A dictionary containing plotting parameters.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
matplotlib.axes.Axes: The modified axes object.
|
|
92
|
+
"""
|
|
93
|
+
Lof_colors = plotting_dict["Lof_colors"]
|
|
94
|
+
column_labels = plotting_dict["column_labels"]
|
|
95
|
+
|
|
96
|
+
kwargs = plotting_dict["kwargs"].copy()
|
|
97
|
+
|
|
98
|
+
adata = plotting_dict["adata"].copy()
|
|
99
|
+
obs_embedding_key = plotting_dict["obs_embedding_key"]
|
|
100
|
+
phate_df = adata.obsm[obs_embedding_key]
|
|
101
|
+
|
|
102
|
+
obs_search_term = plotting_dict["obs_search_term"]
|
|
103
|
+
|
|
104
|
+
row_idx = idx_dict["row_idx"]
|
|
105
|
+
col_idx = idx_dict["col_idx"]
|
|
106
|
+
|
|
107
|
+
color_name = Lof_colors[row_idx - 1]
|
|
108
|
+
|
|
109
|
+
if plotting_dict["plot_background"]:
|
|
110
|
+
ax.scatter(phate_df[:, 0], phate_df[:, 1], c="lightgrey", **kwargs)
|
|
111
|
+
|
|
112
|
+
colors = adata.obs_vector(color_name)
|
|
113
|
+
|
|
114
|
+
if colors.dtype != "object" and not isinstance(colors, pd.Categorical):
|
|
115
|
+
vmin = np.percentile(colors, 1)
|
|
116
|
+
vmax = np.percentile(colors, 99)
|
|
117
|
+
kwargs.update(
|
|
118
|
+
{
|
|
119
|
+
"vmin": vmin,
|
|
120
|
+
"vmax": vmax,
|
|
121
|
+
"cmap": "rainbow",
|
|
122
|
+
}
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
plotting_df = phate_df
|
|
126
|
+
|
|
127
|
+
Lof_label_idxs = [
|
|
128
|
+
get_str_idx(label, adata.obs[obs_search_term])[0]
|
|
129
|
+
for label in column_labels
|
|
130
|
+
if label != "ALL"
|
|
131
|
+
]
|
|
132
|
+
|
|
133
|
+
current_plotting_label = column_labels[col_idx - 1]
|
|
134
|
+
|
|
135
|
+
if current_plotting_label == "ALL":
|
|
136
|
+
condition_df = plotting_df
|
|
137
|
+
else:
|
|
138
|
+
label_idxs = Lof_label_idxs[col_idx - 1]
|
|
139
|
+
condition_df = plotting_df[label_idxs, :]
|
|
140
|
+
colors = colors[label_idxs]
|
|
141
|
+
|
|
142
|
+
ax.scatter(condition_df[:, 0], condition_df[:, 1], c=colors, **kwargs)
|
|
143
|
+
|
|
144
|
+
ax.set_yticklabels([])
|
|
145
|
+
ax.set_xticklabels([])
|
|
146
|
+
ax.get_xaxis().set_ticks([])
|
|
147
|
+
ax.get_yaxis().set_ticks([])
|
|
148
|
+
ax.axis("off")
|
|
149
|
+
ax.axis("tight")
|
|
150
|
+
|
|
151
|
+
return ax
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def general_plotting_function(
|
|
155
|
+
plotting_function,
|
|
156
|
+
param_info_dict=None,
|
|
157
|
+
plotting_dict=None,
|
|
158
|
+
hyperparam_search=False,
|
|
159
|
+
plot_all=False,
|
|
160
|
+
blank=False,
|
|
161
|
+
fontsize=35,
|
|
162
|
+
unit_size=10,
|
|
163
|
+
param_plot_proportion=0.20,
|
|
164
|
+
):
|
|
165
|
+
"""
|
|
166
|
+
A general plotting function that creates a grid of subplots for visualization.
|
|
167
|
+
|
|
168
|
+
Args:
|
|
169
|
+
plotting_function (callable): The function used to plot on each subplot.
|
|
170
|
+
param_info_dict (dict, optional): A dictionary containing information about the parameters for hyperparameter search. Defaults to None.
|
|
171
|
+
plotting_dict (dict, optional): A dictionary containing information for plotting. Defaults to None.
|
|
172
|
+
hyperparam_search (bool, optional): A boolean indicating whether hyperparameter search is enabled. Defaults to False.
|
|
173
|
+
plot_all (bool, optional): A boolean indicating whether to plot all partitions. Defaults to False.
|
|
174
|
+
blank (bool, optional): A boolean indicating whether to return a blank figure. Defaults to False.
|
|
175
|
+
fontsize (int, optional): The fontsize for the annotations. Defaults to 35.
|
|
176
|
+
unit_size (int, optional): The size of each subplot in units. Defaults to 10.
|
|
177
|
+
param_plot_proportion (float, optional): The proportion of the plot dedicated to parameter labels. Defaults to 0.20.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
matplotlib.figure.Figure: The created figure object.
|
|
181
|
+
"""
|
|
182
|
+
if hyperparam_search is True:
|
|
183
|
+
param_dict = param_info_dict["param_dict"]
|
|
184
|
+
|
|
185
|
+
row_param_name = param_info_dict["row_label"]
|
|
186
|
+
col_param_name = param_info_dict["col_label"]
|
|
187
|
+
constant_param_name = param_info_dict["constant_label"]
|
|
188
|
+
|
|
189
|
+
row_param_list = param_dict[row_param_name]
|
|
190
|
+
col_param_list = param_dict[col_param_name]
|
|
191
|
+
|
|
192
|
+
num_rows = len(row_param_list)
|
|
193
|
+
num_cols = len(col_param_list)
|
|
194
|
+
|
|
195
|
+
else:
|
|
196
|
+
adata = plotting_dict["adata"].copy()
|
|
197
|
+
search_obs_term = plotting_dict["obs_search_term"]
|
|
198
|
+
color_names = plotting_dict["Lof_colors"]
|
|
199
|
+
|
|
200
|
+
row_labels = color_names
|
|
201
|
+
|
|
202
|
+
if not plotting_dict.get("column_labels"):
|
|
203
|
+
col_labels = np.unique(adata.obs[search_obs_term])
|
|
204
|
+
|
|
205
|
+
if plot_all:
|
|
206
|
+
col_labels = np.append(col_labels, "ALL")
|
|
207
|
+
|
|
208
|
+
plotting_dict["column_labels"] = col_labels
|
|
209
|
+
|
|
210
|
+
else:
|
|
211
|
+
col_labels = plotting_dict["column_labels"]
|
|
212
|
+
|
|
213
|
+
num_cols = len(col_labels)
|
|
214
|
+
num_rows = len(row_labels)
|
|
215
|
+
|
|
216
|
+
row_cmap = plt.cm.get_cmap("tab20")
|
|
217
|
+
col_cmap = plt.cm.get_cmap("Dark2")
|
|
218
|
+
|
|
219
|
+
width_ratios = [param_plot_proportion] + np.repeat(1, num_cols).tolist()
|
|
220
|
+
height_ratios = [param_plot_proportion] + np.repeat(1, num_rows).tolist()
|
|
221
|
+
|
|
222
|
+
anno_opts = dict(
|
|
223
|
+
xycoords="axes fraction", va="center", ha="center", fontsize=5 * unit_size
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
col_param_limits = np.linspace(0, 1, num_cols + 1)
|
|
227
|
+
row_param_limits = np.linspace(0, 1, num_rows + 1)
|
|
228
|
+
|
|
229
|
+
fig = plt.figure(
|
|
230
|
+
figsize=(unit_size * num_cols, unit_size * num_rows), constrained_layout=True
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
if blank:
|
|
234
|
+
return fig
|
|
235
|
+
|
|
236
|
+
gs = fig.add_gridspec(
|
|
237
|
+
num_rows + 1,
|
|
238
|
+
num_cols + 1,
|
|
239
|
+
width_ratios=width_ratios,
|
|
240
|
+
height_ratios=height_ratios,
|
|
241
|
+
)
|
|
242
|
+
|
|
243
|
+
plot_idx = 0
|
|
244
|
+
first = True
|
|
245
|
+
for row_idx, col_idx in itertools.product(range(num_rows + 1), range(num_cols + 1)):
|
|
246
|
+
# this creates the labels on the first row and first column
|
|
247
|
+
if row_idx == 0 or col_idx == 0:
|
|
248
|
+
if first:
|
|
249
|
+
# this makes one long plot that spans the first row
|
|
250
|
+
init_row = fig.add_subplot(gs[0, 1:])
|
|
251
|
+
# this splits the first row into multiple labels based on the number of columns and annotates each one
|
|
252
|
+
for col_num in range(num_cols):
|
|
253
|
+
left_limit = col_param_limits[col_num]
|
|
254
|
+
right_limit = col_param_limits[col_num + 1]
|
|
255
|
+
|
|
256
|
+
annotate_xy = (((left_limit + right_limit) / 2), 0.5)
|
|
257
|
+
anno_opts["xy"] = annotate_xy
|
|
258
|
+
|
|
259
|
+
init_row.axvspan(
|
|
260
|
+
left_limit, right_limit, facecolor=row_cmap(col_num), alpha=0.5
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
if hyperparam_search is True:
|
|
264
|
+
init_row.annotate(
|
|
265
|
+
f"{col_param_name} = {col_param_list[col_num]}", **anno_opts
|
|
266
|
+
)
|
|
267
|
+
else:
|
|
268
|
+
init_row.annotate(f"{col_labels[col_num]}", **anno_opts)
|
|
269
|
+
|
|
270
|
+
init_row.set_yticks([])
|
|
271
|
+
init_row.set_xticks([])
|
|
272
|
+
init_row.set_xlim(0, 1)
|
|
273
|
+
|
|
274
|
+
# this makes one long plot that spans the first column
|
|
275
|
+
init_col = fig.add_subplot(gs[1:, 0])
|
|
276
|
+
|
|
277
|
+
# this splits the first column into multiple labels based on the number of rows and annotates each one
|
|
278
|
+
for row_num in range(num_rows):
|
|
279
|
+
upper_limit = row_param_limits[row_num]
|
|
280
|
+
lower_limit = row_param_limits[row_num + 1]
|
|
281
|
+
|
|
282
|
+
annotate_xy = (0.5, ((lower_limit + upper_limit) / 2))
|
|
283
|
+
anno_opts["xy"] = annotate_xy
|
|
284
|
+
|
|
285
|
+
init_col.axhspan(
|
|
286
|
+
lower_limit, upper_limit, facecolor=col_cmap(row_num), alpha=0.5
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
# Indexing is -(row_num+1) to make the plots go from top to bottom
|
|
290
|
+
if hyperparam_search is True:
|
|
291
|
+
init_col.annotate(
|
|
292
|
+
f"{row_param_name} = {row_param_list[-(row_num+1)]}",
|
|
293
|
+
rotation=90,
|
|
294
|
+
**anno_opts,
|
|
295
|
+
)
|
|
296
|
+
else:
|
|
297
|
+
init_col.annotate(
|
|
298
|
+
f"{row_labels[-(row_num+1)]}", rotation=90, **anno_opts
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
init_col.set_yticks([])
|
|
302
|
+
init_col.set_xticks([])
|
|
303
|
+
init_col.set_ylim(0, 1)
|
|
304
|
+
|
|
305
|
+
# add a small box in the upper right corner to indicate what the constant parameter is for the hyperparameter search
|
|
306
|
+
if hyperparam_search == True:
|
|
307
|
+
constant_var_name = param_info_dict["constant_label"]
|
|
308
|
+
constant_param = fig.add_subplot(gs[0, 0])
|
|
309
|
+
anno_opts["xy"] = (0.5, 0.5)
|
|
310
|
+
anno_opts["fontsize"] = 25
|
|
311
|
+
constant_param.annotate(
|
|
312
|
+
f"{constant_var_name}={param_dict[constant_param_name]}",
|
|
313
|
+
**anno_opts,
|
|
314
|
+
)
|
|
315
|
+
constant_param.set_xticks([])
|
|
316
|
+
constant_param.set_yticks([])
|
|
317
|
+
|
|
318
|
+
first == False
|
|
319
|
+
continue
|
|
320
|
+
|
|
321
|
+
ax = fig.add_subplot(gs[row_idx, col_idx])
|
|
322
|
+
|
|
323
|
+
idx_dict = {"row_idx": row_idx, "col_idx": col_idx, "plot_idx": plot_idx}
|
|
324
|
+
|
|
325
|
+
ax = plotting_function(ax, idx_dict, plotting_dict)
|
|
326
|
+
plot_idx += 1
|
|
327
|
+
return fig
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def get_legend(adata: ad.AnnData, color_name: str, label_name: str = None):
|
|
331
|
+
"""
|
|
332
|
+
Get patches from adata.obs[color_name] to be used for creating a legend and returns the list of colors as well.
|
|
333
|
+
|
|
334
|
+
Args:
|
|
335
|
+
adata (ad.AnnData): AnnData object.
|
|
336
|
+
color_name (str): Name of the anndata obs column to use for coloring (i.e., 'cell_line_colors').
|
|
337
|
+
label_name (str, optional): The name of the label column. Defaults to None.
|
|
338
|
+
|
|
339
|
+
Returns:
|
|
340
|
+
tuple: A tuple containing a list of patches for the legend and the list of colors.
|
|
341
|
+
"""
|
|
342
|
+
colors = adata.obs_vector(color_name)
|
|
343
|
+
|
|
344
|
+
if label_name is None:
|
|
345
|
+
label_name = color_name.removesuffix("_colors")
|
|
346
|
+
|
|
347
|
+
labels = adata.obs[label_name].values
|
|
348
|
+
|
|
349
|
+
col_lab_array = np.array([colors, labels], dtype=str).T
|
|
350
|
+
uni_col_lab_matches = np.unique(col_lab_array, axis=0)
|
|
351
|
+
|
|
352
|
+
patch_list = []
|
|
353
|
+
for color, label in uni_col_lab_matches:
|
|
354
|
+
patch = mpatches.Patch(color=color, label=label)
|
|
355
|
+
patch_list.append(patch)
|
|
356
|
+
|
|
357
|
+
return patch_list, colors
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def combine_Lof_plots(
|
|
361
|
+
list_of_plots: list[mpl.figure.Figure] = None,
|
|
362
|
+
fig_dims: tuple = None,
|
|
363
|
+
default_padding: tuple = (0, 0),
|
|
364
|
+
default_padding_color: tuple = 255,
|
|
365
|
+
unit_size: int = 5,
|
|
366
|
+
save_path: str = None,
|
|
367
|
+
title_kwargs: dict = None,
|
|
368
|
+
title: str = None,
|
|
369
|
+
inline: bool = False,
|
|
370
|
+
):
|
|
371
|
+
"""
|
|
372
|
+
Combines a list of matplotlib figures into a single figure with specified dimensions.
|
|
373
|
+
|
|
374
|
+
Args:
|
|
375
|
+
list_of_plots (list[mpl.figure.Figure], optional): List of matplotlib figures to be combined. Defaults to None.
|
|
376
|
+
fig_dims (tuple, optional): Dimensions of the final combined figure in terms of number of rows and columns. Defaults to None.
|
|
377
|
+
default_padding (tuple, optional): Padding to be applied to each figure in terms of number of rows and columns. Defaults to (0, 0).
|
|
378
|
+
default_padding_color (tuple, optional): Color value (RGB) to be used for the default padding. Defaults to 255.
|
|
379
|
+
unit_size (int, optional): The size of each unit in the plot. Defaults to 5.
|
|
380
|
+
save_path (str, optional): Path to save the combined figure. Defaults to None.
|
|
381
|
+
title_kwargs (dict, optional): Keyword arguments for customizing the title of the combined figure. Defaults to None.
|
|
382
|
+
title (str, optional): Title of the combined figure. Defaults to None.
|
|
383
|
+
inline (bool, optional): If True, the function will automatically retrieve all open figures and combine them. Defaults to False.
|
|
384
|
+
|
|
385
|
+
Returns:
|
|
386
|
+
None
|
|
387
|
+
"""
|
|
388
|
+
if inline:
|
|
389
|
+
list_of_plots = [
|
|
390
|
+
manager.canvas.figure
|
|
391
|
+
for manager in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()
|
|
392
|
+
]
|
|
393
|
+
|
|
394
|
+
# converts the figures into numpy arrays
|
|
395
|
+
for fig_idx, fig in enumerate(list_of_plots):
|
|
396
|
+
if isinstance(fig, tuple):
|
|
397
|
+
fig = fig[0]
|
|
398
|
+
|
|
399
|
+
canvas = fig.canvas
|
|
400
|
+
canvas.draw()
|
|
401
|
+
|
|
402
|
+
element = np.array(canvas.buffer_rgba())
|
|
403
|
+
|
|
404
|
+
list_of_plots[fig_idx] = element
|
|
405
|
+
|
|
406
|
+
if inline:
|
|
407
|
+
for fig in plt.get_fignums():
|
|
408
|
+
plt.close(fig)
|
|
409
|
+
|
|
410
|
+
max_figure_dims = np.max(
|
|
411
|
+
[(fig.shape[0], fig.shape[1]) for fig in list_of_plots], axis=0
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
for fig_idx, fig in enumerate(list_of_plots):
|
|
415
|
+
row_diff = max_figure_dims[0] - fig.shape[0]
|
|
416
|
+
col_diff = max_figure_dims[1] - fig.shape[1]
|
|
417
|
+
|
|
418
|
+
if row_diff > 0:
|
|
419
|
+
fig = np.pad(
|
|
420
|
+
fig,
|
|
421
|
+
((floor(row_diff / 2), ceil(row_diff / 2)), (0, 0), (0, 0)),
|
|
422
|
+
"constant",
|
|
423
|
+
constant_values=255,
|
|
424
|
+
)
|
|
425
|
+
if col_diff > 0:
|
|
426
|
+
fig = np.pad(
|
|
427
|
+
fig,
|
|
428
|
+
((0, 0), (floor(col_diff / 2), ceil(col_diff / 2)), (0, 0)),
|
|
429
|
+
"constant",
|
|
430
|
+
constant_values=255,
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
default_row_padding = default_padding[0]
|
|
434
|
+
default_col_padding = default_padding[1]
|
|
435
|
+
|
|
436
|
+
fig = np.pad(
|
|
437
|
+
fig,
|
|
438
|
+
(
|
|
439
|
+
(default_row_padding, default_row_padding),
|
|
440
|
+
(default_col_padding, default_col_padding),
|
|
441
|
+
(0, 0),
|
|
442
|
+
),
|
|
443
|
+
"constant",
|
|
444
|
+
constant_values=default_padding_color,
|
|
445
|
+
)
|
|
446
|
+
|
|
447
|
+
list_of_plots[fig_idx] = fig
|
|
448
|
+
|
|
449
|
+
final_num_rows = fig_dims[0]
|
|
450
|
+
final_num_cols = fig_dims[1]
|
|
451
|
+
|
|
452
|
+
if len(list_of_plots) < final_num_rows * final_num_cols:
|
|
453
|
+
fig_num_diff = final_num_rows * final_num_cols - len(list_of_plots)
|
|
454
|
+
for _ in range(fig_num_diff):
|
|
455
|
+
list_of_plots.append(np.ones_like(fig) * default_padding_color)
|
|
456
|
+
|
|
457
|
+
# shapes the figures generated above into the final figure dimensions
|
|
458
|
+
counter = 0
|
|
459
|
+
fig_rows = []
|
|
460
|
+
for _ in range(final_num_rows):
|
|
461
|
+
fig_row = list_of_plots[counter : counter + final_num_cols]
|
|
462
|
+
fig_row = np.hstack(fig_row)
|
|
463
|
+
fig_rows.append(fig_row)
|
|
464
|
+
counter += final_num_cols
|
|
465
|
+
|
|
466
|
+
fig_rows = tuple(fig_rows)
|
|
467
|
+
|
|
468
|
+
plot_array = np.vstack(fig_rows)
|
|
469
|
+
|
|
470
|
+
# plots the final figure
|
|
471
|
+
fig, ax = plt.subplots(
|
|
472
|
+
figsize=(unit_size * final_num_cols, unit_size * final_num_rows),
|
|
473
|
+
constrained_layout=True,
|
|
474
|
+
dpi=600,
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
ax.matshow(plot_array)
|
|
478
|
+
|
|
479
|
+
if title:
|
|
480
|
+
if title_kwargs is None:
|
|
481
|
+
title_kwargs = {
|
|
482
|
+
"fontsize": unit_size * final_num_cols,
|
|
483
|
+
"fontweight": "bold",
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
ax.set_title(title, **title_kwargs)
|
|
487
|
+
|
|
488
|
+
ax.axis("off")
|
|
489
|
+
if save_path:
|
|
490
|
+
plt.savefig(save_path, dpi=600, bbox_inches="tight")
|
|
491
|
+
elif inline:
|
|
492
|
+
plt.show()
|
|
493
|
+
plt.close()
|
|
494
|
+
else:
|
|
495
|
+
return fig
|
cc_mapping/preprocess.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import anndata as ad
|
|
3
|
+
|
|
4
|
+
from .utils import get_str_idx
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def row_data_partitioning(
|
|
8
|
+
adata: ad.AnnData,
|
|
9
|
+
search_str: str,
|
|
10
|
+
search_obs: str,
|
|
11
|
+
regex: bool = False,
|
|
12
|
+
regex_flags: list[str] = None,
|
|
13
|
+
reset_idx: bool = True,
|
|
14
|
+
):
|
|
15
|
+
"""
|
|
16
|
+
Partition the rows of the input AnnData object based on a search string and observation column.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
adata (ad.AnnData): The input AnnData object.
|
|
20
|
+
search_str (str): The search string used to filter the rows.
|
|
21
|
+
search_obs (str): The name of the observation column used for filtering.
|
|
22
|
+
regex (bool, optional): Whether to use regular expressions for searching. Defaults to False.
|
|
23
|
+
regex_flags (list[str], optional): List of regex flags to use if regex is True. Defaults to None.
|
|
24
|
+
reset_idx (bool, optional): Whether to reset the index of the resulting AnnData object. Defaults to True.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
ad.AnnData: The partitioned AnnData object.
|
|
28
|
+
"""
|
|
29
|
+
search_idxs, _ = get_str_idx(
|
|
30
|
+
search_str, adata.obs[search_obs], regex=regex, regex_flags=regex_flags
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
adata = adata[search_idxs, :].copy()
|
|
34
|
+
|
|
35
|
+
if reset_idx is True:
|
|
36
|
+
adata.obs.index = np.arange(adata.shape[0]).astype(str)
|
|
37
|
+
|
|
38
|
+
return adata
|