cellmapper 0.0.1__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.
- cellmapper/__init__.py +8 -0
- cellmapper/cellmapper.py +479 -0
- cellmapper/check.py +82 -0
- cellmapper/evaluate.py +323 -0
- cellmapper/knn.py +300 -0
- cellmapper/logging.py +25 -0
- cellmapper-0.0.1.dist-info/METADATA +127 -0
- cellmapper-0.0.1.dist-info/RECORD +10 -0
- cellmapper-0.0.1.dist-info/WHEEL +4 -0
- cellmapper-0.0.1.dist-info/licenses/LICENSE +21 -0
cellmapper/evaluate.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Literal
|
|
3
|
+
|
|
4
|
+
import matplotlib.pyplot as plt
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from scipy.sparse import issparse
|
|
8
|
+
from scipy.spatial.distance import jensenshannon
|
|
9
|
+
from scipy.stats import pearsonr, spearmanr
|
|
10
|
+
from sklearn.metrics import (
|
|
11
|
+
ConfusionMatrixDisplay,
|
|
12
|
+
accuracy_score,
|
|
13
|
+
classification_report,
|
|
14
|
+
f1_score,
|
|
15
|
+
precision_score,
|
|
16
|
+
recall_score,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
from cellmapper.logging import logger
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _jensen_shannon_divergence(p: np.ndarray, q: np.ndarray) -> float:
|
|
23
|
+
"""Compute the Jensen-Shannon divergence between two expression vectors.
|
|
24
|
+
|
|
25
|
+
Parameters
|
|
26
|
+
----------
|
|
27
|
+
p, q
|
|
28
|
+
Expression vectors.
|
|
29
|
+
|
|
30
|
+
Returns
|
|
31
|
+
-------
|
|
32
|
+
The Jensen-Shannon divergence between p and q.
|
|
33
|
+
"""
|
|
34
|
+
p = np.clip(p, 0, None)
|
|
35
|
+
q = np.clip(q, 0, None)
|
|
36
|
+
if p.sum() == 0 or q.sum() == 0:
|
|
37
|
+
return np.nan
|
|
38
|
+
p = p / p.sum()
|
|
39
|
+
q = q / q.sum()
|
|
40
|
+
return jensenshannon(p, q, base=10)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _rmse_zscore(a: np.ndarray, b: np.ndarray) -> float:
|
|
44
|
+
"""
|
|
45
|
+
Compute the RMSE between z-scored versions of two arrays (per gene).
|
|
46
|
+
|
|
47
|
+
Both a and b are 1D arrays of the same length (spots/cells for a single gene).
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
a, b
|
|
52
|
+
Expression vectors (1D arrays) to compare.
|
|
53
|
+
|
|
54
|
+
Returns
|
|
55
|
+
-------
|
|
56
|
+
The RMSE between the z-scored versions of a and b.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def zscore(x):
|
|
60
|
+
mean = np.mean(x)
|
|
61
|
+
std = np.std(x, ddof=0)
|
|
62
|
+
if std == 0:
|
|
63
|
+
std = 1
|
|
64
|
+
return (x - mean) / std
|
|
65
|
+
|
|
66
|
+
a_z = zscore(a)
|
|
67
|
+
b_z = zscore(b)
|
|
68
|
+
return np.sqrt(np.mean((a_z - b_z) ** 2))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class CellMapperEvaluationMixin:
|
|
72
|
+
"""Mixin class for evaluation-related methods for CellMapper."""
|
|
73
|
+
|
|
74
|
+
def evaluate_label_transfer(
|
|
75
|
+
self,
|
|
76
|
+
label_key: str,
|
|
77
|
+
confidence_cutoff: float = 0.0,
|
|
78
|
+
zero_division: int | Literal["warn"] = 0,
|
|
79
|
+
) -> None:
|
|
80
|
+
"""
|
|
81
|
+
Evaluate label transfer using a k-NN classifier.
|
|
82
|
+
|
|
83
|
+
Parameters
|
|
84
|
+
----------
|
|
85
|
+
label_key
|
|
86
|
+
Key in .obs storing ground-truth cell type annotations.
|
|
87
|
+
confidence_cutoff
|
|
88
|
+
Minimum confidence score required to include a cell in the evaluation.
|
|
89
|
+
zero_divisions
|
|
90
|
+
How to handle zero divisions in sklearn metrics comptuation.
|
|
91
|
+
|
|
92
|
+
Returns
|
|
93
|
+
-------
|
|
94
|
+
Nothing, but updates the following attributes:
|
|
95
|
+
label_transfer_metrics
|
|
96
|
+
Dictionary containing accuracy, precision, recall, F1 scores, and excluded fraction.
|
|
97
|
+
"""
|
|
98
|
+
if self.prediction_postfix is None or self.confidence_postfix is None:
|
|
99
|
+
raise ValueError("Label transfer has not been performed. Call transfer_labels() first.")
|
|
100
|
+
|
|
101
|
+
# Extract ground-truth and predicted labels
|
|
102
|
+
y_true = self.query.obs[label_key].dropna()
|
|
103
|
+
y_pred = self.query.obs.loc[y_true.index, f"{label_key}_{self.prediction_postfix}"]
|
|
104
|
+
confidence = self.query.obs.loc[y_true.index, f"{label_key}_{self.confidence_postfix}"]
|
|
105
|
+
|
|
106
|
+
# Apply confidence cutoff
|
|
107
|
+
valid_indices = confidence >= confidence_cutoff
|
|
108
|
+
y_true = y_true[valid_indices]
|
|
109
|
+
y_pred = y_pred[valid_indices]
|
|
110
|
+
excluded_fraction = 1 - valid_indices.mean()
|
|
111
|
+
|
|
112
|
+
# Compute classification metrics
|
|
113
|
+
accuracy = accuracy_score(y_true, y_pred)
|
|
114
|
+
precision = precision_score(y_true, y_pred, average="weighted", zero_division=zero_division)
|
|
115
|
+
recall = recall_score(y_true, y_pred, average="weighted", zero_division=zero_division)
|
|
116
|
+
f1_weighted = f1_score(y_true, y_pred, average="weighted", zero_division=zero_division)
|
|
117
|
+
f1_macro = f1_score(y_true, y_pred, average="macro", zero_division=zero_division)
|
|
118
|
+
|
|
119
|
+
# Log and store results
|
|
120
|
+
self.label_transfer_metrics = {
|
|
121
|
+
"accuracy": accuracy,
|
|
122
|
+
"precision": precision,
|
|
123
|
+
"recall": recall,
|
|
124
|
+
"f1_weighted": f1_weighted,
|
|
125
|
+
"f1_macro": f1_macro,
|
|
126
|
+
"excluded_fraction": excluded_fraction,
|
|
127
|
+
}
|
|
128
|
+
logger.info(
|
|
129
|
+
"Accuracy: %.4f, Precision: %.4f, Recall: %.4f, Weighted F1-Score: %.4f, Macro F1-Score: %.4f, Excluded Fraction: %.4f",
|
|
130
|
+
accuracy,
|
|
131
|
+
precision,
|
|
132
|
+
recall,
|
|
133
|
+
f1_weighted,
|
|
134
|
+
f1_macro,
|
|
135
|
+
excluded_fraction,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
# Optional: Save a detailed classification report
|
|
139
|
+
report = classification_report(y_true, y_pred, output_dict=True, zero_division=zero_division)
|
|
140
|
+
self.label_transfer_report = pd.DataFrame(report).transpose()
|
|
141
|
+
|
|
142
|
+
def plot_confusion_matrix(
|
|
143
|
+
self, label_key: str, figsize=(10, 8), cmap="viridis", save: str | Path | None = None, **kwargs
|
|
144
|
+
) -> None:
|
|
145
|
+
"""
|
|
146
|
+
Plot the confusion matrix as a heatmap using sklearn's ConfusionMatrixDisplay.
|
|
147
|
+
|
|
148
|
+
Parameters
|
|
149
|
+
----------
|
|
150
|
+
figsize
|
|
151
|
+
Size of the figure (width, height). Default is (10, 8).
|
|
152
|
+
cmap
|
|
153
|
+
Colormap to use for the heatmap. Default is "viridis".
|
|
154
|
+
label_key
|
|
155
|
+
Key in .obs storing ground-truth cell type annotations.
|
|
156
|
+
**kwargs
|
|
157
|
+
Additional keyword arguments to pass to ConfusionMatrixDisplay.
|
|
158
|
+
"""
|
|
159
|
+
if self.prediction_postfix is None or self.confidence_postfix is None:
|
|
160
|
+
raise ValueError("Label transfer has not been performed. Call transfer_labels() first.")
|
|
161
|
+
|
|
162
|
+
# Extract true and predicted labels
|
|
163
|
+
y_true = self.query.obs[label_key].dropna()
|
|
164
|
+
y_pred = self.query.obs.loc[y_true.index, f"{label_key}_pred"]
|
|
165
|
+
|
|
166
|
+
# Plot confusion matrix using sklearn's ConfusionMatrixDisplay
|
|
167
|
+
_, ax = plt.subplots(1, 1, figsize=figsize)
|
|
168
|
+
ConfusionMatrixDisplay.from_predictions(y_true, y_pred, cmap=cmap, xticks_rotation="vertical", ax=ax, **kwargs)
|
|
169
|
+
plt.title("Confusion Matrix")
|
|
170
|
+
|
|
171
|
+
if save:
|
|
172
|
+
plt.savefig(save, bbox_inches="tight")
|
|
173
|
+
|
|
174
|
+
def evaluate_expression_transfer(
|
|
175
|
+
self,
|
|
176
|
+
layer_key: str = "X",
|
|
177
|
+
method: Literal["pearson", "spearman", "js", "rmse"] = "pearson",
|
|
178
|
+
) -> None:
|
|
179
|
+
"""
|
|
180
|
+
Evaluate the agreement between imputed and original expression in the query dataset.
|
|
181
|
+
|
|
182
|
+
These metrics are inspired by Li et al., Nature Methods 2022 (https://www.nature.com/articles/s41592-022-01480-9).
|
|
183
|
+
|
|
184
|
+
Parameters
|
|
185
|
+
----------
|
|
186
|
+
layer_key
|
|
187
|
+
Key in `self.query.layers` to use as the original expression. Use "X" to use `self.query.X`.
|
|
188
|
+
method
|
|
189
|
+
Method to quantify agreement. Currently supported: "pearson" (average Pearson correlation across shared genes).
|
|
190
|
+
|
|
191
|
+
Returns
|
|
192
|
+
-------
|
|
193
|
+
Nothing, but updates the following attributes:
|
|
194
|
+
expression_transfer_metrics
|
|
195
|
+
Dictionary containing the average correlation and number of genes used for the evaluation.
|
|
196
|
+
"""
|
|
197
|
+
imputed_x, original_x, shared_genes = self._get_aligned_expression_arrays(layer_key)
|
|
198
|
+
log_msg = "Expression transfer evaluation (%s): average value = %.4f (n_genes=%d, n_valid_genes=%d)"
|
|
199
|
+
if method == "pearson" or method == "spearman":
|
|
200
|
+
if method == "pearson":
|
|
201
|
+
corr_func = pearsonr
|
|
202
|
+
elif method == "spearman":
|
|
203
|
+
corr_func = spearmanr
|
|
204
|
+
|
|
205
|
+
# Compute per-gene correlation
|
|
206
|
+
corrs = np.array([corr_func(original_x[:, i], imputed_x[:, i])[0] for i in range(imputed_x.shape[1])])
|
|
207
|
+
|
|
208
|
+
# Store per-gene correlation in query_imputed.var, only for shared genes
|
|
209
|
+
self._store_expression_metric(
|
|
210
|
+
shared_genes,
|
|
211
|
+
corrs,
|
|
212
|
+
f"metric_{method}",
|
|
213
|
+
"average_correlation",
|
|
214
|
+
method,
|
|
215
|
+
log_msg,
|
|
216
|
+
)
|
|
217
|
+
elif method in ("js", "jensen-shannon"):
|
|
218
|
+
jsds = np.array(
|
|
219
|
+
[_jensen_shannon_divergence(imputed_x[:, i], original_x[:, i]) for i in range(imputed_x.shape[1])]
|
|
220
|
+
)
|
|
221
|
+
self._store_expression_metric(
|
|
222
|
+
shared_genes,
|
|
223
|
+
jsds,
|
|
224
|
+
"metric_js",
|
|
225
|
+
"average_jsd",
|
|
226
|
+
"js",
|
|
227
|
+
log_msg,
|
|
228
|
+
)
|
|
229
|
+
elif method == "rmse":
|
|
230
|
+
rmses = np.array([_rmse_zscore(imputed_x[:, i], original_x[:, i]) for i in range(imputed_x.shape[1])])
|
|
231
|
+
self._store_expression_metric(
|
|
232
|
+
shared_genes,
|
|
233
|
+
rmses,
|
|
234
|
+
"metric_rmse",
|
|
235
|
+
"average_rmse",
|
|
236
|
+
"rmse",
|
|
237
|
+
log_msg,
|
|
238
|
+
)
|
|
239
|
+
else:
|
|
240
|
+
raise NotImplementedError(f"Method '{method}' is not implemented.")
|
|
241
|
+
|
|
242
|
+
def _get_aligned_expression_arrays(self, layer_key: str) -> tuple[np.ndarray, np.ndarray, list[str]]:
|
|
243
|
+
"""
|
|
244
|
+
Extract and align imputed and original expression arrays for shared genes between query_imputed and query.
|
|
245
|
+
|
|
246
|
+
Parameters
|
|
247
|
+
----------
|
|
248
|
+
layer_key : Key in self.query.layers to use as the original expression. Use "X" to use self.query.X.
|
|
249
|
+
|
|
250
|
+
Returns
|
|
251
|
+
-------
|
|
252
|
+
imputed_x, original_x, shared_genes
|
|
253
|
+
"""
|
|
254
|
+
if self.query_imputed is None:
|
|
255
|
+
raise ValueError("Imputed query data not found. Run transfer_expression() first.")
|
|
256
|
+
shared_genes = list(self.query_imputed.var_names.intersection(self.query.var_names))
|
|
257
|
+
if len(shared_genes) == 0:
|
|
258
|
+
raise ValueError("No shared genes between query_imputed and query.")
|
|
259
|
+
imputed_x = self.query_imputed[:, shared_genes].X
|
|
260
|
+
if layer_key == "X":
|
|
261
|
+
original_x = self.query[:, shared_genes].X
|
|
262
|
+
else:
|
|
263
|
+
original_x = self.query[:, shared_genes].layers[layer_key]
|
|
264
|
+
if issparse(imputed_x):
|
|
265
|
+
imputed_x = imputed_x.toarray()
|
|
266
|
+
if issparse(original_x):
|
|
267
|
+
original_x = original_x.toarray()
|
|
268
|
+
return imputed_x, original_x, shared_genes
|
|
269
|
+
|
|
270
|
+
def _store_expression_metric(
|
|
271
|
+
self,
|
|
272
|
+
shared_genes: list[str],
|
|
273
|
+
values: np.ndarray,
|
|
274
|
+
metric_name: str,
|
|
275
|
+
summary_key: str,
|
|
276
|
+
method_label: str,
|
|
277
|
+
log_msg: str,
|
|
278
|
+
) -> None:
|
|
279
|
+
"""
|
|
280
|
+
Store per-gene and summary expression transfer metrics in the query_imputed AnnData object and log the results.
|
|
281
|
+
|
|
282
|
+
Parameters
|
|
283
|
+
----------
|
|
284
|
+
shared_genes
|
|
285
|
+
List of shared gene names.
|
|
286
|
+
values
|
|
287
|
+
Array of per-gene metric values (e.g., correlation, JSD).
|
|
288
|
+
metric_name
|
|
289
|
+
Name of the column to store per-gene values in query_imputed.var.
|
|
290
|
+
summary_key
|
|
291
|
+
Key for the average metric in self.expression_transfer_metrics.
|
|
292
|
+
method_label
|
|
293
|
+
Name of the method/metric (for logging and summary dict).
|
|
294
|
+
log_msg
|
|
295
|
+
Logging message format string, should accept (avg_value, n_genes, n_valid_genes).
|
|
296
|
+
|
|
297
|
+
Returns
|
|
298
|
+
-------
|
|
299
|
+
Nothing, but updates the following attributes:
|
|
300
|
+
query_imputed.var[metric_name]
|
|
301
|
+
DataFrame column with per-gene metric values.
|
|
302
|
+
expression_transfer_metrics
|
|
303
|
+
Dictionary containing the average metric value and number of genes used for the evaluation.
|
|
304
|
+
"""
|
|
305
|
+
self.query_imputed.var[metric_name] = None
|
|
306
|
+
self.query_imputed.var.loc[shared_genes, metric_name] = values
|
|
307
|
+
valid_values = values[~np.isnan(values)]
|
|
308
|
+
if valid_values.size == 0:
|
|
309
|
+
raise ValueError(f"No valid genes for {method_label} calculation.")
|
|
310
|
+
avg_value = float(np.mean(valid_values))
|
|
311
|
+
self.expression_transfer_metrics = {
|
|
312
|
+
"method": method_label,
|
|
313
|
+
summary_key: avg_value,
|
|
314
|
+
"n_genes": len(shared_genes),
|
|
315
|
+
"n_valid_genes": int(valid_values.size),
|
|
316
|
+
}
|
|
317
|
+
logger.info(
|
|
318
|
+
log_msg,
|
|
319
|
+
method_label,
|
|
320
|
+
avg_value,
|
|
321
|
+
len(shared_genes),
|
|
322
|
+
int(valid_values.size),
|
|
323
|
+
)
|
cellmapper/knn.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from functools import cached_property
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import sklearn.neighbors
|
|
7
|
+
from pynndescent import NNDescent
|
|
8
|
+
from scipy.sparse import csr_matrix
|
|
9
|
+
|
|
10
|
+
from cellmapper.logging import logger
|
|
11
|
+
|
|
12
|
+
from .check import check_deps
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class NeighborsResults:
|
|
17
|
+
"""Nearest neighbors results data store.
|
|
18
|
+
|
|
19
|
+
Adapted from the scib-metrics package: https://github.com/YosefLab/scib-metrics
|
|
20
|
+
|
|
21
|
+
Attributes
|
|
22
|
+
----------
|
|
23
|
+
distances
|
|
24
|
+
Array of distances to the nearest neighbors.
|
|
25
|
+
indices
|
|
26
|
+
Array of indices of the nearest neighbors. Self should always
|
|
27
|
+
be included here; however, some approximate algorithms may not return
|
|
28
|
+
the self edge.
|
|
29
|
+
n_targets
|
|
30
|
+
Number of target samples. If None, it is assumed to be the same as
|
|
31
|
+
the number of samples in the indices array.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
distances: np.ndarray
|
|
35
|
+
indices: np.ndarray
|
|
36
|
+
n_targets: int | None = None
|
|
37
|
+
|
|
38
|
+
def __post_init__(self):
|
|
39
|
+
"""
|
|
40
|
+
Post-initialization logic for NeighborsResults.
|
|
41
|
+
|
|
42
|
+
Ensures that `n_targets` is set correctly and validates the shape of
|
|
43
|
+
`distances` and `indices`.
|
|
44
|
+
"""
|
|
45
|
+
if self.indices.shape != self.distances.shape:
|
|
46
|
+
raise ValueError("Indices and distances must have the same shape.")
|
|
47
|
+
|
|
48
|
+
if self.n_targets is None:
|
|
49
|
+
# Assume square adjacency matrix if `n_targets` is not provided
|
|
50
|
+
self.n_targets = self.indices.shape[0]
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def n_samples(self) -> int:
|
|
54
|
+
"""Number of samples (cells)."""
|
|
55
|
+
return self.indices.shape[0]
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def n_neighbors(self) -> int:
|
|
59
|
+
"""Number of neighbors."""
|
|
60
|
+
return self.indices.shape[1]
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def shape(self) -> tuple[int, int]:
|
|
64
|
+
"""Shape of the adjacency/graph matrices (n_samples, n_targets)."""
|
|
65
|
+
return (self.n_samples, self.n_targets or self.n_samples)
|
|
66
|
+
|
|
67
|
+
@cached_property
|
|
68
|
+
def knn_graph_distances(self, dtype=np.float64) -> csr_matrix:
|
|
69
|
+
"""
|
|
70
|
+
Return the sparse weighted adjacency matrix of distances.
|
|
71
|
+
|
|
72
|
+
Parameters
|
|
73
|
+
----------
|
|
74
|
+
dtype
|
|
75
|
+
Data type for the matrix values.
|
|
76
|
+
|
|
77
|
+
Returns
|
|
78
|
+
-------
|
|
79
|
+
csr_matrix
|
|
80
|
+
Sparse matrix of distances (shape: n_samples x n_targets).
|
|
81
|
+
"""
|
|
82
|
+
rowptr = np.arange(0, self.n_samples * self.n_neighbors + 1, self.n_neighbors)
|
|
83
|
+
return csr_matrix((self.distances.ravel().astype(dtype), self.indices.ravel(), rowptr), shape=self.shape)
|
|
84
|
+
|
|
85
|
+
def knn_graph_connectivities(
|
|
86
|
+
self,
|
|
87
|
+
kernel: Literal["gaussian", "scarches", "random", "inverse_distance"] = "gaussian",
|
|
88
|
+
dtype=np.float64,
|
|
89
|
+
**kwargs,
|
|
90
|
+
) -> csr_matrix:
|
|
91
|
+
"""
|
|
92
|
+
Compute connectivities using the specified kernel.
|
|
93
|
+
|
|
94
|
+
Parameters
|
|
95
|
+
----------
|
|
96
|
+
kernel
|
|
97
|
+
Connectivity kernel to use. Supported: 'gaussian', 'scarches', 'random', 'inverse_distance'.
|
|
98
|
+
dtype
|
|
99
|
+
Data type for the matrix values.
|
|
100
|
+
**kwargs
|
|
101
|
+
Additional keyword arguments for kernel computation.
|
|
102
|
+
|
|
103
|
+
Returns
|
|
104
|
+
-------
|
|
105
|
+
csr_matrix
|
|
106
|
+
Sparse matrix of connectivities (shape: n_samples x n_targets).
|
|
107
|
+
"""
|
|
108
|
+
if kernel == "gaussian":
|
|
109
|
+
sigma = np.mean(self.distances)
|
|
110
|
+
connectivities = np.exp(-(self.distances**2) / (2 * sigma**2))
|
|
111
|
+
elif kernel == "scarches":
|
|
112
|
+
sigma = np.std(self.distances)
|
|
113
|
+
sigma = (2.0 / sigma) ** 2
|
|
114
|
+
connectivities = np.exp(-self.distances / sigma)
|
|
115
|
+
elif kernel == "random": # this is for testing purposes
|
|
116
|
+
connectivities = np.random.rand(*self.distances.shape) # Random values for connectivities
|
|
117
|
+
elif kernel == "inverse_distance":
|
|
118
|
+
epsilon = kwargs.get("epsilon", 1e-8)
|
|
119
|
+
connectivities = 1.0 / (self.distances + epsilon)
|
|
120
|
+
else:
|
|
121
|
+
raise ValueError(f"Unknown kernel: {kernel}. Supported kernels are 'gaussian' and 'scarches'.")
|
|
122
|
+
rowptr = np.arange(0, self.n_samples * self.n_neighbors + 1, self.n_neighbors)
|
|
123
|
+
return csr_matrix((connectivities.ravel().astype(dtype), self.indices.ravel(), rowptr), shape=self.shape)
|
|
124
|
+
|
|
125
|
+
def boolean_adjacency(self, dtype=np.float64) -> csr_matrix:
|
|
126
|
+
"""
|
|
127
|
+
Construct a boolean adjacency matrix from neighbor indices using the same rowptr mechanism as other graph methods.
|
|
128
|
+
|
|
129
|
+
Parameters
|
|
130
|
+
----------
|
|
131
|
+
dtype
|
|
132
|
+
Data type for the matrix values.
|
|
133
|
+
|
|
134
|
+
Returns
|
|
135
|
+
-------
|
|
136
|
+
csr_matrix
|
|
137
|
+
Boolean adjacency matrix (shape: n_samples x n_targets), with 1 for each neighbor relationship.
|
|
138
|
+
"""
|
|
139
|
+
rowptr = np.arange(0, self.n_samples * self.n_neighbors + 1, self.n_neighbors)
|
|
140
|
+
data = np.ones(self.indices.size, dtype=dtype)
|
|
141
|
+
return csr_matrix((data, self.indices.ravel(), rowptr), shape=self.shape)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class Neighbors:
|
|
145
|
+
"""Class to compute and store nearest neighbors."""
|
|
146
|
+
|
|
147
|
+
def __init__(self, xrep: np.ndarray, yrep: np.ndarray):
|
|
148
|
+
"""
|
|
149
|
+
Initialize the Neighbors class.
|
|
150
|
+
|
|
151
|
+
Parameters
|
|
152
|
+
----------
|
|
153
|
+
xrep
|
|
154
|
+
Representation of the reference dataset.
|
|
155
|
+
yrep
|
|
156
|
+
Representation of the query dataset.
|
|
157
|
+
"""
|
|
158
|
+
self.xrep = xrep
|
|
159
|
+
self.yrep = yrep
|
|
160
|
+
|
|
161
|
+
self.xx: NeighborsResults | None = None
|
|
162
|
+
self.yy: NeighborsResults | None = None
|
|
163
|
+
self.xy: NeighborsResults | None = None
|
|
164
|
+
self.yx: NeighborsResults | None = None
|
|
165
|
+
|
|
166
|
+
def compute_neighbors(
|
|
167
|
+
self,
|
|
168
|
+
n_neighbors: int = 30,
|
|
169
|
+
method: Literal["sklearn", "pynndescent", "rapids", "faiss"] = "sklearn",
|
|
170
|
+
metric: str = "euclidean",
|
|
171
|
+
random_state: int = 0,
|
|
172
|
+
only_yx: bool = False,
|
|
173
|
+
):
|
|
174
|
+
"""
|
|
175
|
+
Compute nearest neighbors using either sklearn or rapids.
|
|
176
|
+
|
|
177
|
+
Parameters
|
|
178
|
+
----------
|
|
179
|
+
n_neighbors
|
|
180
|
+
Number of nearest neighbors.
|
|
181
|
+
method
|
|
182
|
+
Method to use for computing neighbors.
|
|
183
|
+
metric
|
|
184
|
+
Distance metric to use for nearest neighbors.
|
|
185
|
+
random_state
|
|
186
|
+
Random state for reproducibility.
|
|
187
|
+
only_yx
|
|
188
|
+
If True, only compute the xy neighbors.
|
|
189
|
+
"""
|
|
190
|
+
if method in ["rapids", "sklearn", "pynndescent", "faiss"]:
|
|
191
|
+
logger.info("Using %s to compute %d neighbors.", method, n_neighbors)
|
|
192
|
+
|
|
193
|
+
if method == "rapids":
|
|
194
|
+
check_deps("rapids")
|
|
195
|
+
import cuml as cm
|
|
196
|
+
import cupy as cp
|
|
197
|
+
|
|
198
|
+
xrep_gpu = cp.asarray(self.xrep)
|
|
199
|
+
yrep_gpu = cp.asarray(self.yrep)
|
|
200
|
+
|
|
201
|
+
xnn = cm.neighbors.NearestNeighbors(n_neighbors=n_neighbors, output_type="numpy", metric=metric).fit(
|
|
202
|
+
xrep_gpu
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
if only_yx:
|
|
206
|
+
self.yx = NeighborsResults(*xnn.kneighbors(yrep_gpu), n_targets=self.xrep.shape[0])
|
|
207
|
+
return
|
|
208
|
+
|
|
209
|
+
ynn = cm.neighbors.NearestNeighbors(n_neighbors=n_neighbors, output_type="numpy", metric=metric).fit(
|
|
210
|
+
yrep_gpu
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
x_results = xnn.kneighbors(xrep_gpu)
|
|
214
|
+
y_results = ynn.kneighbors(yrep_gpu)
|
|
215
|
+
xy_results = ynn.kneighbors(xrep_gpu)
|
|
216
|
+
yx_results = xnn.kneighbors(yrep_gpu)
|
|
217
|
+
|
|
218
|
+
elif method == "faiss":
|
|
219
|
+
check_deps("faiss")
|
|
220
|
+
import faiss
|
|
221
|
+
|
|
222
|
+
res = faiss.StandardGpuResources()
|
|
223
|
+
xnn = faiss.IndexFlatL2(self.xrep.shape[1])
|
|
224
|
+
xnn_gpu = faiss.index_cpu_to_gpu(res, 0, xnn)
|
|
225
|
+
xnn_gpu.add(self.xrep)
|
|
226
|
+
|
|
227
|
+
if only_yx:
|
|
228
|
+
self.yx = NeighborsResults(*xnn_gpu.search(self.yrep, n_neighbors), n_targets=self.xrep.shape[0])
|
|
229
|
+
return
|
|
230
|
+
|
|
231
|
+
ynn = faiss.IndexFlatL2(self.yrep.shape[1])
|
|
232
|
+
ynn_gpu = faiss.index_cpu_to_gpu(res, 0, ynn)
|
|
233
|
+
ynn_gpu.add(self.yrep)
|
|
234
|
+
|
|
235
|
+
x_results = xnn_gpu.search(self.xrep, n_neighbors)
|
|
236
|
+
y_results = ynn_gpu.search(self.yrep, n_neighbors)
|
|
237
|
+
xy_results = ynn_gpu.search(self.xrep, n_neighbors)
|
|
238
|
+
yx_results = xnn_gpu.search(self.yrep, n_neighbors)
|
|
239
|
+
|
|
240
|
+
elif method == "sklearn":
|
|
241
|
+
xnn = sklearn.neighbors.NearestNeighbors(n_neighbors=n_neighbors, metric=metric).fit(self.xrep)
|
|
242
|
+
|
|
243
|
+
if only_yx:
|
|
244
|
+
self.yx = NeighborsResults(*xnn.kneighbors(self.yrep), n_targets=self.xrep.shape[0])
|
|
245
|
+
return
|
|
246
|
+
|
|
247
|
+
ynn = sklearn.neighbors.NearestNeighbors(n_neighbors=n_neighbors, metric=metric).fit(self.yrep)
|
|
248
|
+
|
|
249
|
+
x_results = xnn.kneighbors(self.xrep)
|
|
250
|
+
y_results = ynn.kneighbors(self.yrep)
|
|
251
|
+
xy_results = ynn.kneighbors(self.xrep)
|
|
252
|
+
yx_results = xnn.kneighbors(self.yrep)
|
|
253
|
+
|
|
254
|
+
elif method == "pynndescent":
|
|
255
|
+
xnn = NNDescent(self.xrep, metric=metric, n_jobs=-1, random_state=random_state)
|
|
256
|
+
|
|
257
|
+
if only_yx:
|
|
258
|
+
self.yx = NeighborsResults(*xnn.query(self.yrep, k=n_neighbors)[::-1], n_targets=self.xrep.shape[0])
|
|
259
|
+
return
|
|
260
|
+
|
|
261
|
+
ynn = NNDescent(self.yrep, metric=metric, n_jobs=-1, random_state=random_state)
|
|
262
|
+
|
|
263
|
+
x_results = xnn.query(self.xrep, k=n_neighbors)[::-1]
|
|
264
|
+
y_results = ynn.query(self.yrep, k=n_neighbors)[::-1]
|
|
265
|
+
xy_results = ynn.query(self.xrep, k=n_neighbors)[::-1]
|
|
266
|
+
yx_results = xnn.query(self.yrep, k=n_neighbors)[::-1]
|
|
267
|
+
|
|
268
|
+
self.xx = NeighborsResults(*x_results, n_targets=None)
|
|
269
|
+
self.yy = NeighborsResults(*y_results, n_targets=None)
|
|
270
|
+
self.xy = NeighborsResults(*xy_results, n_targets=self.yrep.shape[0])
|
|
271
|
+
self.yx = NeighborsResults(*yx_results, n_targets=self.xrep.shape[0])
|
|
272
|
+
|
|
273
|
+
else:
|
|
274
|
+
raise ValueError(f"Unknown method: {method}. Supported methods are 'sklearn', 'pynndescent', and 'rapids'.")
|
|
275
|
+
|
|
276
|
+
def get_adjacency_matrices(self) -> tuple[csr_matrix, csr_matrix, csr_matrix, csr_matrix]:
|
|
277
|
+
"""
|
|
278
|
+
Compute unweighted adjacency matrices for all k-NN graphs.
|
|
279
|
+
|
|
280
|
+
Returns
|
|
281
|
+
-------
|
|
282
|
+
tuple
|
|
283
|
+
Unweighted adjacency matrices (xx, yy, xy, yx).
|
|
284
|
+
"""
|
|
285
|
+
if self.xx is None or self.yy is None or self.xy is None or self.yx is None:
|
|
286
|
+
raise ValueError("Neighbors must be computed before accessing adjacency matrices.")
|
|
287
|
+
xx_adj = self.xx.boolean_adjacency()
|
|
288
|
+
yy_adj = self.yy.boolean_adjacency()
|
|
289
|
+
xy_adj = self.xy.boolean_adjacency()
|
|
290
|
+
yx_adj = self.yx.boolean_adjacency()
|
|
291
|
+
|
|
292
|
+
return xx_adj, yy_adj, xy_adj, yx_adj
|
|
293
|
+
|
|
294
|
+
def __repr__(self):
|
|
295
|
+
"""Return a string representation of the Neighbors object."""
|
|
296
|
+
return (
|
|
297
|
+
f"Neighbors(xrep_shape={self.xrep.shape}, yrep_shape={self.yrep.shape}, "
|
|
298
|
+
f"xx={self.xx is not None}, yy={self.yy is not None}, "
|
|
299
|
+
f"xy={self.xy is not None}, yx={self.yx is not None})"
|
|
300
|
+
)
|
cellmapper/logging.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Logging setup for the package."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _setup_logger() -> "logging.Logger":
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.logging import RichHandler
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
level = os.environ.get("LOGLEVEL", logging.INFO)
|
|
13
|
+
logger.setLevel(level=level)
|
|
14
|
+
console = Console(force_terminal=True)
|
|
15
|
+
if console.is_jupyter is True:
|
|
16
|
+
console.is_jupyter = False
|
|
17
|
+
ch = RichHandler(show_path=False, console=console, show_time=logger.level == logging.DEBUG)
|
|
18
|
+
logger.addHandler(ch)
|
|
19
|
+
|
|
20
|
+
# this prevents double outputs
|
|
21
|
+
logger.propagate = False
|
|
22
|
+
return logger
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
logger = _setup_logger()
|