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.
@@ -0,0 +1,284 @@
1
+ import contextlib
2
+ import os
3
+ from collections import Counter
4
+
5
+ import anndata as ad
6
+ import matplotlib as mpl
7
+ import matplotlib.pyplot as plt
8
+ import numpy as np
9
+ import palantir
10
+ from tqdm import tqdm
11
+
12
+ from .plot import combine_Lof_plots, general_plotting_function
13
+
14
+
15
+ def run_palantir_pseudotime(
16
+ adata: ad.AnnData,
17
+ root_cell: str,
18
+ data_key: str,
19
+ n_components: int,
20
+ num_waypoints: int,
21
+ knn: int,
22
+ obsm_embedding: str = "X_phate",
23
+ seed: int = 0,
24
+ plot: bool = True,
25
+ kwargs: dict = None,
26
+ ):
27
+ """
28
+ Runs the Palantir pseudotime analysis on the provided AnnData object.
29
+
30
+ Args:
31
+ adata (ad.AnnData): The AnnData object containing the data.
32
+ root_cell (str): The name of the root cell for pseudotime analysis.
33
+ data_key (str): The key in `adata.obsm` where the data is stored.
34
+ n_components (int): The number of diffusion components to compute.
35
+ num_waypoints (int): The number of waypoints to compute.
36
+ knn (int): The number of nearest neighbors to use for constructing the kNN graph.
37
+ obsm_embedding (str, optional): The key in `adata.obsm` where the embedding is stored. Defaults to 'X_phate'.
38
+ seed (int, optional): The random seed for reproducibility. Defaults to 0.
39
+ plot (bool, optional): Whether to plot the results. Defaults to True.
40
+ kwargs (dict, optional): Additional keyword arguments to pass to `palantir.plot.plot_palantir_results`.
41
+
42
+ Returns:
43
+ matplotlib.figure.Figure or None: The generated plot figure, or None if an error occurred.
44
+ """
45
+ if kwargs is None:
46
+ kwargs = {}
47
+
48
+ try:
49
+ with open(os.devnull, "w") as devnull:
50
+ with contextlib.redirect_stdout(devnull):
51
+
52
+ palantir.utils.run_diffusion_maps(
53
+ adata, n_components=n_components, pca_key=data_key, seed=seed
54
+ )
55
+ palantir.utils.determine_multiscale_space(adata)
56
+
57
+ palantir.core.run_palantir(
58
+ adata, root_cell, num_waypoints=num_waypoints, knn=knn, seed=seed
59
+ )
60
+ except Exception as e:
61
+ print(
62
+ f"n_components: {n_components}, num_waypoints: {num_waypoints}, knn: {knn}"
63
+ )
64
+ print(e)
65
+
66
+ if plot:
67
+ fig = plt.figure(figsize=(10, 10))
68
+ plt.tight_layout()
69
+ return fig
70
+
71
+ if plot:
72
+ fig = palantir.plot.plot_palantir_results(
73
+ adata, embedding_basis=obsm_embedding, **kwargs
74
+ )
75
+ plt.tight_layout()
76
+ return fig
77
+
78
+
79
+ def palantir_pseudotime_hyperparam_plotting_function(
80
+ axe, idx_dict, plotting_dict, unit_size=10, s=10
81
+ ):
82
+ """
83
+ Plotting function for palantir pseudotime hyperparameters.
84
+
85
+ Args:
86
+ axe (matplotlib.axes.Axes): The axes on which to plot the pseudotime hyperparameters.
87
+ idx_dict (dict): A dictionary containing the row and column indices.
88
+ plotting_dict (dict): A dictionary containing the plotting information.
89
+ unit_size (int, optional): The size of the units in the plot. Defaults to 10.
90
+ s (int, optional): The size of the markers in the plot. Defaults to 10.
91
+
92
+ Returns:
93
+ matplotlib.axes.Axes: The modified axes object.
94
+ numpy.ndarray: The plot as a numpy array.
95
+ """
96
+ col_idx = idx_dict["col_idx"] - 1
97
+ row_idx = idx_dict["row_idx"] - 1
98
+
99
+ hyperparam_dict = plotting_dict["hyperparam_dict"].copy()
100
+ random_seed = hyperparam_dict["random_seed"]
101
+ hyperparam_dict.pop("random_seed")
102
+
103
+ hyperparam_info_dict = plotting_dict["hyperparam_info_dict"].copy()
104
+ kwargs = plotting_dict["kwargs"].copy()
105
+
106
+ obsm_embedding = plotting_dict["obsm_embedding"]
107
+
108
+ row_param_name = hyperparam_info_dict["row_label"]
109
+ col_param_name = hyperparam_info_dict["col_label"]
110
+
111
+ row_param_list = hyperparam_dict[row_param_name]
112
+ col_param_list = hyperparam_dict[col_param_name]
113
+
114
+ if row_param_name == "num_waypoints":
115
+ num_waypoints = row_param_list[row_idx]
116
+ knn = col_param_list[col_idx]
117
+ elif row_param_name == "knns":
118
+ knn = row_param_list[row_idx]
119
+ num_waypoints = col_param_list[col_idx]
120
+ else:
121
+ raise KeyError("row_param_name must equal num_waypoints or knns")
122
+
123
+ n_components = hyperparam_dict["n_components"]
124
+
125
+ adata = plotting_dict["adata"]
126
+ root_cell = plotting_dict["root_cell"]
127
+ data_key = plotting_dict["data_key"]
128
+
129
+ fig = run_palantir_pseudotime(
130
+ adata,
131
+ root_cell,
132
+ data_key,
133
+ n_components,
134
+ num_waypoints,
135
+ knn,
136
+ obsm_embedding=obsm_embedding,
137
+ seed=random_seed,
138
+ kwargs=kwargs,
139
+ )
140
+
141
+ canvas = fig.canvas
142
+ canvas.draw()
143
+
144
+ # this is a numpy array of the plot
145
+ element = np.array(canvas.buffer_rgba())
146
+ axe.imshow(element)
147
+
148
+ if not np.all(element == 255):
149
+
150
+ def get_plot_limits(element, type):
151
+ if type == "right":
152
+ element = np.flip(element, axis=1)
153
+
154
+ truth_bool_array = np.repeat(True, element.shape[1])
155
+
156
+ white_cols = np.where(np.all(np.isclose(element, 255), axis=0))[0]
157
+ cols = list(Counter(white_cols).keys())
158
+ counts = list(Counter(white_cols).values())
159
+ white_cols = np.where(np.array(counts) == 4)[0]
160
+ white_col_idxs = [cols[idx] for idx in white_cols]
161
+ truth_bool_array[white_col_idxs] = False
162
+
163
+ return truth_bool_array
164
+
165
+ left_truth_bool_array = get_plot_limits(element, "left")
166
+ right_truth_bool_array = get_plot_limits(element, "right")
167
+
168
+ fig = plt.figure(figsize=(10, 10))
169
+ xll = np.argwhere(left_truth_bool_array == True)[0]
170
+ xul = element.shape[1] - np.argwhere(right_truth_bool_array == True)[0]
171
+ axe.set_xlim(xll, xul)
172
+
173
+ axe.axis("off")
174
+ return axe, element
175
+
176
+
177
+ def perform_palantir_hyperparameter_search(
178
+ adata: ad.AnnData,
179
+ data_key: str,
180
+ root_cell: str,
181
+ hyperparam_dict: dict,
182
+ hyperparam_info_dict: dict,
183
+ additional_plotting_dict_params: dict,
184
+ plotting_function: callable = palantir_pseudotime_hyperparam_plotting_function,
185
+ obsm_embedding: str = "X_phate",
186
+ save_path: str = None,
187
+ unit_size: int = 10,
188
+ kwargs: dict = {},
189
+ ):
190
+ """
191
+ Perform hyperparameter search for Palantir pseudotime analysis.
192
+
193
+ Args:
194
+ adata (ad.AnnData): Annotated data object.
195
+ data_key (str): Key for accessing the data in `adata`.
196
+ root_cell (str): Name of the root cell for pseudotime analysis.
197
+ hyperparam_dict (dict): Dictionary containing hyperparameters to be searched.
198
+ hyperparam_info_dict (dict): Dictionary containing information about hyperparameters.
199
+ additional_plotting_dict_params (dict): Additional parameters for plotting.
200
+ plotting_function (callable, optional): Function to use for plotting. Defaults to palantir_pseudotime_hyperparam_plotting_function.
201
+ obsm_embedding (str, optional): Key for accessing the embedding in `adata.obsm`. Defaults to 'X_phate'.
202
+ save_path (str, optional): Path to save the final figure. Defaults to None.
203
+ unit_size (int, optional): Size of each subplot in the final figure. Defaults to 10.
204
+ kwargs (dict, optional): Additional keyword arguments for plotting functions. Defaults to {}.
205
+
206
+ Returns:
207
+ matplotlib.axes.Axes: The matplotlib axis object containing the final figure.
208
+ """
209
+ if save_path is not None:
210
+ save_dir = os.path.dirname(save_path)
211
+ if not os.path.exists(save_dir):
212
+ raise ValueError(f"{save_dir} does not exist")
213
+
214
+ constant_param_name = hyperparam_info_dict["constant_label"]
215
+
216
+ backend = mpl.get_backend()
217
+ mpl.use("agg")
218
+
219
+ final_figure_dims = hyperparam_info_dict["final_figure_dims"]
220
+ number_param_plots = len(hyperparam_dict[constant_param_name])
221
+ final_num_rows = final_figure_dims[0]
222
+ final_num_cols = final_figure_dims[1]
223
+
224
+ total_num_plots = final_num_rows * final_num_cols
225
+
226
+ if total_num_plots < number_param_plots:
227
+ raise ValueError(
228
+ f"Number of plots ({number_param_plots}) exceeds the number of subplots ({total_num_plots})"
229
+ )
230
+
231
+ fig_list = []
232
+ for idx in tqdm(
233
+ range(total_num_plots),
234
+ total=number_param_plots,
235
+ desc="Generating hyperparameter search plots",
236
+ ):
237
+
238
+ plotting_dict = {
239
+ "adata": adata.copy(),
240
+ "data_key": data_key,
241
+ "unit_size": unit_size,
242
+ "root_cell": root_cell,
243
+ "obsm_embedding": obsm_embedding,
244
+ "kwargs": kwargs,
245
+ }
246
+
247
+ if additional_plotting_dict_params:
248
+ plotting_dict.update(additional_plotting_dict_params)
249
+
250
+ # -1 is needed for correct indexing
251
+ if idx <= number_param_plots - 1:
252
+ temp_hyperparam_dict = hyperparam_dict.copy()
253
+ temp_hyperparam_info_dict = hyperparam_info_dict.copy()
254
+ temp_hyperparam_dict[constant_param_name] = hyperparam_dict[
255
+ constant_param_name
256
+ ][idx]
257
+ temp_hyperparam_info_dict["param_dict"] = temp_hyperparam_dict
258
+
259
+ plotting_dict["hyperparam_dict"] = temp_hyperparam_dict
260
+ plotting_dict["hyperparam_info_dict"] = temp_hyperparam_info_dict
261
+
262
+ fig = general_plotting_function(
263
+ plotting_function,
264
+ temp_hyperparam_info_dict,
265
+ plotting_dict,
266
+ hyperparam_search=True,
267
+ unit_size=unit_size,
268
+ )
269
+
270
+ else:
271
+ # generate a blank plot to fill in the empty space
272
+ fig = general_plotting_function(
273
+ plotting_function,
274
+ temp_hyperparam_info_dict,
275
+ plotting_dict,
276
+ blank=True,
277
+ hyperparam_search=True,
278
+ )
279
+
280
+ fig_list.append(fig)
281
+
282
+ combined_fig = combine_Lof_plots(fig_list, final_figure_dims, save_path=save_path)
283
+
284
+ return combined_fig
@@ -0,0 +1,60 @@
1
+ """
2
+ GMM-based thresholding package for single-cell analysis.
3
+
4
+ This package provides classes for performing Gaussian Mixture Model (GMM) based
5
+ thresholding on gene expression data within AnnData objects. It supports both
6
+ single-feature thresholding and sequential refinement operations.
7
+
8
+ Main Classes:
9
+ GMMThresholding: Single-feature GMM thresholding
10
+ SequentialGMM: Sequential refinement (Phase 2)
11
+
12
+ Pydantic Models:
13
+ _GaussianMixtureModelInfo: GMM parameters and results storage
14
+ _DecisionBoundariesModel: Decision boundary thresholds storage
15
+ _SingleThresholdingEventModel: Complete thresholding event data
16
+
17
+ Base Classes:
18
+ GaussianMixtureModelBase: Shared utilities for GMM operations
19
+
20
+ Usage::
21
+
22
+ from cc_mapping.thresholding import GMMThresholding
23
+
24
+ gmm = GMMThresholding(
25
+ adata=adata,
26
+ feature='gene1',
27
+ label_obs_save_str='gene1_categories'
28
+ )
29
+ gmm.fit(n_components=2)
30
+ gmm.categorize_samples(ordered_labels=['Low', 'High'])
31
+ adata = gmm.return_adata()
32
+ """
33
+
34
+ from .base import (
35
+ _GaussianMixtureModelInfo,
36
+ _DecisionBoundariesModel,
37
+ _SingleThresholdingEventModel,
38
+ GaussianMixtureModelBase,
39
+ )
40
+
41
+ from .single import GMMThresholding
42
+
43
+ from .sequential import SequentialGMM
44
+
45
+
46
+ __all__ = [
47
+ # Main classes
48
+ 'GMMThresholding',
49
+ 'SequentialGMM',
50
+
51
+ # Base class
52
+ 'GaussianMixtureModelBase',
53
+
54
+ # Pydantic models (private but exposed for advanced usage)
55
+ '_GaussianMixtureModelInfo',
56
+ '_DecisionBoundariesModel',
57
+ '_SingleThresholdingEventModel',
58
+ ]
59
+
60
+ __version__ = '0.1.0'