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/__init__.py
ADDED
cellmapper/cellmapper.py
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
1
|
+
"""k-NN based mapping of labels, embeddings, and expression values."""
|
|
2
|
+
|
|
3
|
+
import gc
|
|
4
|
+
from typing import Any, Literal
|
|
5
|
+
|
|
6
|
+
import anndata as ad
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import scanpy as sc
|
|
10
|
+
from anndata import AnnData
|
|
11
|
+
from scipy.sparse import coo_matrix, csc_matrix, csr_matrix
|
|
12
|
+
from sklearn.preprocessing import OneHotEncoder
|
|
13
|
+
|
|
14
|
+
from cellmapper.evaluate import CellMapperEvaluationMixin
|
|
15
|
+
from cellmapper.logging import logger
|
|
16
|
+
|
|
17
|
+
from .knn import Neighbors
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class CellMapper(CellMapperEvaluationMixin):
|
|
21
|
+
"""Mapping of labels, embeddings, and expression values between reference and query datasets."""
|
|
22
|
+
|
|
23
|
+
def __init__(self, ref: AnnData, query: AnnData) -> None:
|
|
24
|
+
"""
|
|
25
|
+
Initialize the CellMapper class.
|
|
26
|
+
|
|
27
|
+
Parameters
|
|
28
|
+
----------
|
|
29
|
+
ref
|
|
30
|
+
Reference dataset.
|
|
31
|
+
query
|
|
32
|
+
Query dataset.
|
|
33
|
+
"""
|
|
34
|
+
self.ref = ref
|
|
35
|
+
self.query = query
|
|
36
|
+
|
|
37
|
+
# Initialize attributes
|
|
38
|
+
self.knn: Neighbors | None = None
|
|
39
|
+
self._mapping_matrix: csr_matrix | None = None
|
|
40
|
+
self.n_neighbors: int | None = None
|
|
41
|
+
self.label_transfer_metrics: dict[str, Any] | None = None
|
|
42
|
+
self.label_transfer_report: pd.DataFrame | None = None
|
|
43
|
+
self.prediction_postfix: str | None = None
|
|
44
|
+
self.confidence_postfix: str | None = None
|
|
45
|
+
self.only_yx: bool | None = None
|
|
46
|
+
self.query_imputed: AnnData | None = None
|
|
47
|
+
self.expression_transfer_metrics: dict[str, Any] | None = None
|
|
48
|
+
|
|
49
|
+
def __repr__(self):
|
|
50
|
+
"""Return a concise string representation of the CellMapper object."""
|
|
51
|
+
ref_summary = f"AnnData(n_obs={self.ref.n_obs:,}, n_vars={self.ref.n_vars:,})"
|
|
52
|
+
query_summary = f"AnnData(n_obs={self.query.n_obs:,}, n_vars={self.query.n_vars:,})"
|
|
53
|
+
return (
|
|
54
|
+
f"CellMapper(ref={ref_summary}, query={query_summary}, "
|
|
55
|
+
f"n_neighbors={self.n_neighbors}, "
|
|
56
|
+
f"prediction_postfix={self.prediction_postfix}, "
|
|
57
|
+
f"confidence_postfix={self.confidence_postfix})"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def mapping_matrix(self):
|
|
62
|
+
"""
|
|
63
|
+
Get the mapping matrix.
|
|
64
|
+
|
|
65
|
+
Returns
|
|
66
|
+
-------
|
|
67
|
+
scipy.sparse.csr_matrix
|
|
68
|
+
The mapping matrix.
|
|
69
|
+
"""
|
|
70
|
+
return self._mapping_matrix
|
|
71
|
+
|
|
72
|
+
@mapping_matrix.setter
|
|
73
|
+
def mapping_matrix(self, value):
|
|
74
|
+
"""
|
|
75
|
+
Set and validate the mapping matrix.
|
|
76
|
+
|
|
77
|
+
Parameters
|
|
78
|
+
----------
|
|
79
|
+
value
|
|
80
|
+
The new mapping matrix to set.
|
|
81
|
+
"""
|
|
82
|
+
if value is not None:
|
|
83
|
+
# Validate and normalize the matrix
|
|
84
|
+
self._mapping_matrix = self._validate_and_normalize_mapping_matrix(value)
|
|
85
|
+
else:
|
|
86
|
+
self._mapping_matrix = None
|
|
87
|
+
|
|
88
|
+
def _validate_and_normalize_mapping_matrix(
|
|
89
|
+
self, mapping_matrix: csr_matrix | coo_matrix | csc_matrix
|
|
90
|
+
) -> csr_matrix:
|
|
91
|
+
"""
|
|
92
|
+
Validate and normalize the mapping matrix.
|
|
93
|
+
|
|
94
|
+
Parameters
|
|
95
|
+
----------
|
|
96
|
+
mapping_matrix
|
|
97
|
+
The mapping matrix to validate and normalize.
|
|
98
|
+
n_ref_cells
|
|
99
|
+
Number of reference cells (rows).
|
|
100
|
+
n_query_cells
|
|
101
|
+
Number of query cells (columns).
|
|
102
|
+
|
|
103
|
+
Returns
|
|
104
|
+
-------
|
|
105
|
+
Validated and row-normalized mapping matrix.
|
|
106
|
+
"""
|
|
107
|
+
# Validate the shape
|
|
108
|
+
if mapping_matrix.shape != (self.query.n_obs, self.ref.n_obs):
|
|
109
|
+
raise ValueError(
|
|
110
|
+
f"Mapping matrix shape mismatch: expected ({self.query.n_obs}, {self.ref.n_obs}), "
|
|
111
|
+
f"but got {mapping_matrix.shape}."
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Row normalize the matrix
|
|
115
|
+
row_sums = mapping_matrix.sum(axis=1).A1 # Convert to 1D array
|
|
116
|
+
if np.any(row_sums == 0):
|
|
117
|
+
logger.warning("Some rows in the mapping matrix have a sum of zero. These rows will be left unchanged.")
|
|
118
|
+
row_sums[row_sums == 0] = 1 # Avoid division by zero
|
|
119
|
+
if not np.allclose(row_sums, 1):
|
|
120
|
+
logger.info("Row-normalizing the mapping matrix.")
|
|
121
|
+
mapping_matrix = mapping_matrix.multiply(1 / row_sums[:, None])
|
|
122
|
+
|
|
123
|
+
# Ensure the matrix is in CSR format
|
|
124
|
+
mapping_matrix = mapping_matrix.tocsr().astype(np.float32)
|
|
125
|
+
|
|
126
|
+
return mapping_matrix
|
|
127
|
+
|
|
128
|
+
def compute_joint_pca(self, n_components: int = 50, key_added: str = "pca_joint", **kwargs) -> None:
|
|
129
|
+
"""
|
|
130
|
+
Compute a joint PCA on the normalized .X matrices of ref and query, using only overlapping genes.
|
|
131
|
+
|
|
132
|
+
Parameters
|
|
133
|
+
----------
|
|
134
|
+
n_components
|
|
135
|
+
Number of principal components to compute.
|
|
136
|
+
key_added
|
|
137
|
+
Key under which to store the joint PCA embeddings in `.obsm` of both ref and query AnnData objects.
|
|
138
|
+
**kwargs
|
|
139
|
+
Additional keyword arguments to pass to scanpy's `pp.pca` function.
|
|
140
|
+
|
|
141
|
+
Notes
|
|
142
|
+
-----
|
|
143
|
+
This method performs an inner join on genes (variables) between the reference and query AnnData objects,
|
|
144
|
+
concatenates the normalized expression matrices, and computes a joint PCA using Scanpy. The resulting
|
|
145
|
+
PCA embeddings are stored in `.obsm[key_added]` for both objects. This is a fallback and not recommended
|
|
146
|
+
for most use cases. Please provide a biologically meaningful representation if possible.
|
|
147
|
+
"""
|
|
148
|
+
logger.warning(
|
|
149
|
+
"No representation provided (use_rep=None). "
|
|
150
|
+
"Falling back to joint PCA on normalized .X of both datasets using only overlapping genes. "
|
|
151
|
+
"This is NOT recommended for most use cases! Please provide a biologically meaningful representation."
|
|
152
|
+
)
|
|
153
|
+
# Concatenate with inner join on genes
|
|
154
|
+
joint = ad.concat([self.ref, self.query], join="inner", label="batch", keys=["ref", "query"])
|
|
155
|
+
|
|
156
|
+
# Compute PCA using scanpy
|
|
157
|
+
sc.pp.pca(joint, n_comps=n_components, **kwargs)
|
|
158
|
+
|
|
159
|
+
# Assign PCA embeddings back to each object using the batch key
|
|
160
|
+
self.ref.obsm[key_added] = joint.obsm["X_pca"][joint.obs["batch"] == "ref"]
|
|
161
|
+
self.query.obsm[key_added] = joint.obsm["X_pca"][joint.obs["batch"] == "query"]
|
|
162
|
+
logger.info(
|
|
163
|
+
"Joint PCA computed and stored as '%s' in both ref.obsm and query.obsm. "
|
|
164
|
+
"Proceeding to use this as the representation for neighbor search.",
|
|
165
|
+
key_added,
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def compute_neighbors(
|
|
169
|
+
self,
|
|
170
|
+
n_neighbors: int = 30,
|
|
171
|
+
use_rep: str | None = None,
|
|
172
|
+
method: Literal["sklearn", "pynndescent", "rapids", "faiss"] = "sklearn",
|
|
173
|
+
metric: str = "euclidean",
|
|
174
|
+
only_yx: bool = False,
|
|
175
|
+
joint_pca_key: str = "pca_joint",
|
|
176
|
+
n_pca_components: int = 50,
|
|
177
|
+
pca_kwargs: dict[str, Any] | None = None,
|
|
178
|
+
) -> None:
|
|
179
|
+
"""
|
|
180
|
+
Compute nearest neighbors between reference and query datasets.
|
|
181
|
+
|
|
182
|
+
Parameters
|
|
183
|
+
----------
|
|
184
|
+
n_neighbors
|
|
185
|
+
Number of nearest neighbors.
|
|
186
|
+
use_rep
|
|
187
|
+
Data representation based on which to find nearest neighbors. If None, a joint PCA will be computed.
|
|
188
|
+
method
|
|
189
|
+
Method to use for computing neighbors. "sklearn" and "pynndescent" run on CPU, "rapids" and "faiss" run on GPU.
|
|
190
|
+
Note that all but "pynndescent" perform exact neighbor search. With GPU acceleration, "faiss" is usually
|
|
191
|
+
fastest and more memory efficient than "rapids".
|
|
192
|
+
metric
|
|
193
|
+
Distance metric to use for nearest neighbors.
|
|
194
|
+
only_yx
|
|
195
|
+
If True, only compute the xy neighbors. This is faster, but not suitable for Jaccard or HNOCA methods.
|
|
196
|
+
joint_pca_key
|
|
197
|
+
Key under which to store the joint PCA embeddings if use_rep is None.
|
|
198
|
+
n_pca_components
|
|
199
|
+
Number of principal components to compute for joint PCA if use_rep is None.
|
|
200
|
+
pca_kwargs
|
|
201
|
+
Additional keyword arguments to pass to scanpy's `pp.pca` function if use_rep is None.
|
|
202
|
+
|
|
203
|
+
Returns
|
|
204
|
+
-------
|
|
205
|
+
Nothing, but updates the following attributes:
|
|
206
|
+
knn
|
|
207
|
+
Nearest neighbors object.
|
|
208
|
+
n_neighbors
|
|
209
|
+
Number of nearest neighbors.
|
|
210
|
+
only_yx
|
|
211
|
+
Whether only yx neighbors were computed.
|
|
212
|
+
"""
|
|
213
|
+
self.n_neighbors = n_neighbors
|
|
214
|
+
self.only_yx = only_yx
|
|
215
|
+
if use_rep is None:
|
|
216
|
+
if pca_kwargs is None:
|
|
217
|
+
pca_kwargs = {}
|
|
218
|
+
self.compute_joint_pca(n_components=n_pca_components, key_added=joint_pca_key, **pca_kwargs)
|
|
219
|
+
use_rep = joint_pca_key
|
|
220
|
+
if use_rep == "X":
|
|
221
|
+
xrep = self.ref.X
|
|
222
|
+
yrep = self.query.X
|
|
223
|
+
else:
|
|
224
|
+
xrep = self.ref.obsm[use_rep]
|
|
225
|
+
yrep = self.query.obsm[use_rep]
|
|
226
|
+
self.knn = Neighbors(np.ascontiguousarray(xrep), np.ascontiguousarray(yrep))
|
|
227
|
+
self.knn.compute_neighbors(n_neighbors=n_neighbors, method=method, metric=metric, only_yx=only_yx)
|
|
228
|
+
|
|
229
|
+
def compute_mappping_matrix(
|
|
230
|
+
self,
|
|
231
|
+
method: Literal["jaccard", "gaussian", "scarches", "inverse_distance", "random", "hnoca"] = "gaussian",
|
|
232
|
+
) -> None:
|
|
233
|
+
"""
|
|
234
|
+
Compute the mapping matrix for label transfer.
|
|
235
|
+
|
|
236
|
+
Parameters
|
|
237
|
+
----------
|
|
238
|
+
method
|
|
239
|
+
Method to use for computing the mapping matrix. Options include:
|
|
240
|
+
- "jaccard": Jaccard similarity. Inspired by GLUE: Cao et al., Nature Biotechnology, 2022: https://www.nature.com/articles/s41587-022-01284-4
|
|
241
|
+
- "gaussian": Gaussian kernel with adaptive bandwith. Loosely inspired by MAGIC: Van Dijk et al., Cell, 2018: https://www.sciencedirect.com/science/article/pii/S0092867418307244?via%3Dihub
|
|
242
|
+
- "scarches": scArches kernel. Inspired by scArches: Lotfollahi et al., Nature Biotechnology, 2021: https://www.nature.com/articles/s41587-021-01001-7
|
|
243
|
+
- "inverse_distance": Inverse distance kernel.
|
|
244
|
+
- "random": Random kernel, useful for testing.
|
|
245
|
+
- "hnoca": HNOCA kernel. Inspired by HNOCA-tools: He et al., Nature 2024: https://www.nature.com/articles/s41586-024-08172-8
|
|
246
|
+
|
|
247
|
+
Returns
|
|
248
|
+
-------
|
|
249
|
+
Nothing, but updates the following attributes:
|
|
250
|
+
mapping_matrix
|
|
251
|
+
Mapping matrix for label transfer.
|
|
252
|
+
"""
|
|
253
|
+
if self.knn is None or self.n_neighbors is None:
|
|
254
|
+
raise ValueError("Neighbors have not been computed. Call compute_neighbors() first.")
|
|
255
|
+
|
|
256
|
+
logger.info("Computing mapping matrix using method '%s'.", method)
|
|
257
|
+
if method in ["jaccard", "hnoca"]:
|
|
258
|
+
if self.only_yx:
|
|
259
|
+
raise ValueError(
|
|
260
|
+
"Jaccard and HNOCa methods require both x and y neighbors to be computed. Set only_yx=False."
|
|
261
|
+
)
|
|
262
|
+
xx, yy, xy, yx = self.knn.get_adjacency_matrices()
|
|
263
|
+
jaccard = (yx @ xx.T) + (yy @ xy.T)
|
|
264
|
+
|
|
265
|
+
if method == "jaccard":
|
|
266
|
+
jaccard.data /= 4 * self.n_neighbors - jaccard.data
|
|
267
|
+
elif method == "hnoca":
|
|
268
|
+
jaccard.data /= 2 * self.n_neighbors - jaccard.data
|
|
269
|
+
jaccard.data = jaccard.data**2
|
|
270
|
+
self.mapping_matrix = jaccard
|
|
271
|
+
elif method in ["gaussian", "scarches", "inverse_distance", "random"]:
|
|
272
|
+
self.mapping_matrix = self.knn.yx.knn_graph_connectivities(kernel=method)
|
|
273
|
+
else:
|
|
274
|
+
raise NotImplementedError(f"Method '{method}' is not implemented.")
|
|
275
|
+
|
|
276
|
+
def transfer_labels(
|
|
277
|
+
self, obs_keys: str | list[str], prediction_postfix: str = "pred", confidence_postfix: str = "conf"
|
|
278
|
+
) -> None:
|
|
279
|
+
"""
|
|
280
|
+
Transfer discrete labels from reference dataset to query dataset for one or more keys
|
|
281
|
+
|
|
282
|
+
Parameters
|
|
283
|
+
----------
|
|
284
|
+
obs_keys
|
|
285
|
+
One or more keys in ``ref.obs`` to be transferred into ``query.obs`` (must be discrete)
|
|
286
|
+
prediction_postfix
|
|
287
|
+
New ``query.obs`` key added for the transferred labels,
|
|
288
|
+
by default ``{obs_key}_pred`` for each obs_key.
|
|
289
|
+
confidence_postfix
|
|
290
|
+
New ``query.obs`` key added for the transferred label confidence,
|
|
291
|
+
by default ``{obs_key}_conf`` for each obs_key.
|
|
292
|
+
|
|
293
|
+
Returns
|
|
294
|
+
-------
|
|
295
|
+
Nothing, but updates the following attributes:
|
|
296
|
+
query.obs
|
|
297
|
+
Contains the transferred labels and their confidence scores.
|
|
298
|
+
"""
|
|
299
|
+
if self.mapping_matrix is None:
|
|
300
|
+
raise ValueError("Mapping matrix has not been computed. Call compute_mapping_matrix() first.")
|
|
301
|
+
if isinstance(obs_keys, str):
|
|
302
|
+
obs_keys = [obs_keys]
|
|
303
|
+
|
|
304
|
+
self.prediction_postfix = prediction_postfix
|
|
305
|
+
self.confidence_postfix = confidence_postfix
|
|
306
|
+
|
|
307
|
+
# Loop over each observation key and perform label transfer
|
|
308
|
+
for key in obs_keys:
|
|
309
|
+
logger.info("Predicting labels for key '%s'.", key)
|
|
310
|
+
onehot = OneHotEncoder(dtype=np.float32)
|
|
311
|
+
xtab = onehot.fit_transform(
|
|
312
|
+
self.ref.obs[[key]],
|
|
313
|
+
) # shape = (n_ref_cells x n_categories), sparse csr matrix, float32
|
|
314
|
+
ytab = self.mapping_matrix @ xtab # shape = (n_query_cells x n_categories), sparse crs matrix, float32
|
|
315
|
+
|
|
316
|
+
pred = pd.Series(
|
|
317
|
+
data=np.array(onehot.categories_[0])[ytab.argmax(axis=1).A1],
|
|
318
|
+
index=self.query.obs_names,
|
|
319
|
+
dtype=self.ref.obs[key].dtype,
|
|
320
|
+
)
|
|
321
|
+
conf = pd.Series(
|
|
322
|
+
ytab.max(axis=1).toarray().ravel(),
|
|
323
|
+
index=self.query.obs_names,
|
|
324
|
+
)
|
|
325
|
+
|
|
326
|
+
self.query.obs[f"{key}_{self.prediction_postfix}"] = pred
|
|
327
|
+
self.query.obs[f"{key}_{self.confidence_postfix}"] = conf
|
|
328
|
+
|
|
329
|
+
# Add colors if available
|
|
330
|
+
if f"{key}_colors" in self.ref.uns:
|
|
331
|
+
color_lookup = dict(zip(self.ref.obs[key].cat.categories, self.ref.uns[f"{key}_colors"], strict=True))
|
|
332
|
+
self.query.uns[f"{key}_{self.prediction_postfix}_colors"] = [
|
|
333
|
+
color_lookup.get(cat, "#000000") for cat in pred.cat.categories
|
|
334
|
+
]
|
|
335
|
+
|
|
336
|
+
logger.info("Labels transferred and stored in query.obs['%s'].", f"{key}_{self.prediction_postfix}")
|
|
337
|
+
|
|
338
|
+
# Free memory explicitly
|
|
339
|
+
del onehot, xtab, ytab, pred, conf
|
|
340
|
+
gc.collect()
|
|
341
|
+
|
|
342
|
+
def transfer_embeddings(self, obsm_keys: str | list[str], prediction_postfix: str = "pred") -> None:
|
|
343
|
+
"""
|
|
344
|
+
Transfer embeddings from reference dataset to query dataset for one or more keys.
|
|
345
|
+
|
|
346
|
+
Parameters
|
|
347
|
+
----------
|
|
348
|
+
obsm_keys
|
|
349
|
+
One or more keys in ``ref.obsm`` storing the embeddings to be transferred.
|
|
350
|
+
prediction_postfix
|
|
351
|
+
Postfix to append to the output keys in ``query.obsm`` where the transferred embeddings will be stored.
|
|
352
|
+
|
|
353
|
+
Returns
|
|
354
|
+
-------
|
|
355
|
+
Nothing, but updates the following attributes:
|
|
356
|
+
query.obsm
|
|
357
|
+
Contains the transferred embeddings.
|
|
358
|
+
"""
|
|
359
|
+
if self.mapping_matrix is None:
|
|
360
|
+
raise ValueError("Mapping matrix has not been computed. Call compute_mapping_matrix() first.")
|
|
361
|
+
|
|
362
|
+
if isinstance(obsm_keys, str):
|
|
363
|
+
obsm_keys = [obsm_keys]
|
|
364
|
+
|
|
365
|
+
for key in obsm_keys:
|
|
366
|
+
logger.info("Transferring embeddings for key '%s'.", key)
|
|
367
|
+
|
|
368
|
+
# Perform matrix multiplication to transfer embeddings
|
|
369
|
+
ref_embeddings = self.ref.obsm[key] # shape = (n_ref_cells x n_embedding_dims)
|
|
370
|
+
query_embeddings = self.mapping_matrix @ ref_embeddings # shape = (n_query_cells x n_embedding_dims)
|
|
371
|
+
|
|
372
|
+
# Store the transferred embeddings in query.obsm
|
|
373
|
+
output_key = f"{key}_{prediction_postfix}"
|
|
374
|
+
self.query.obsm[output_key] = query_embeddings
|
|
375
|
+
|
|
376
|
+
logger.info("Embeddings transferred and stored in query.obsm['%s'].", output_key)
|
|
377
|
+
|
|
378
|
+
def transfer_expression(self, layer_key: str) -> None:
|
|
379
|
+
"""
|
|
380
|
+
Transfer expression values (e.g., .X or entries from .layers) from reference dataset to a new imputed query AnnData object.
|
|
381
|
+
|
|
382
|
+
Parameters
|
|
383
|
+
----------
|
|
384
|
+
layer_key
|
|
385
|
+
Key in ``ref.layers`` to be transferred. Use "X" to transfer ``ref.X``.
|
|
386
|
+
|
|
387
|
+
Returns
|
|
388
|
+
-------
|
|
389
|
+
Nothing, but creates/updates self.query_imputed with the transferred data in .X.
|
|
390
|
+
The new AnnData object will have the same cells as the query, but the features (genes) of the reference.
|
|
391
|
+
"""
|
|
392
|
+
if self.mapping_matrix is None:
|
|
393
|
+
raise ValueError("Mapping matrix has not been computed. Call compute_mapping_matrix() first.")
|
|
394
|
+
|
|
395
|
+
logger.info("Transferring layer for key '%s'.", layer_key)
|
|
396
|
+
# Get the reference layer (or .X if key is "X")
|
|
397
|
+
ref_layer = self.ref.X if layer_key == "X" else self.ref.layers[layer_key]
|
|
398
|
+
query_layer = self.mapping_matrix @ ref_layer # shape = (n_query_cells x n_ref_features)
|
|
399
|
+
|
|
400
|
+
# Always create or update a new AnnData object for the imputed data, placing result in .X
|
|
401
|
+
obs = self.query.obs.copy(deep=False)
|
|
402
|
+
var = self.ref.var.copy(deep=False)
|
|
403
|
+
if self.query_imputed is None:
|
|
404
|
+
self.query_imputed = ad.AnnData(
|
|
405
|
+
X=query_layer,
|
|
406
|
+
obs=obs,
|
|
407
|
+
var=var,
|
|
408
|
+
uns=self.query.uns,
|
|
409
|
+
obsm=self.query.obsm,
|
|
410
|
+
varm=self.ref.varm,
|
|
411
|
+
obsp=None,
|
|
412
|
+
varp=None,
|
|
413
|
+
)
|
|
414
|
+
else:
|
|
415
|
+
self.query_imputed.X = query_layer
|
|
416
|
+
logger.info(
|
|
417
|
+
"Imputed expression for layer '%s' stored in self.query_imputed.X.\n"
|
|
418
|
+
"Note: The feature space now matches the reference (n_vars=%s), not the query (n_vars=%s).",
|
|
419
|
+
layer_key,
|
|
420
|
+
self.ref.n_vars,
|
|
421
|
+
self.query.n_vars,
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
def fit(
|
|
425
|
+
self,
|
|
426
|
+
obs_keys: str | list[str] | None = None,
|
|
427
|
+
obsm_keys: str | list[str] | None = None,
|
|
428
|
+
layer_key: str | None = None,
|
|
429
|
+
n_neighbors: int = 30,
|
|
430
|
+
use_rep: str | None = None,
|
|
431
|
+
knn_method: Literal["sklearn", "pynndescent", "rapids"] = "sklearn",
|
|
432
|
+
metric: str = "euclidean",
|
|
433
|
+
only_yx: bool = False,
|
|
434
|
+
mapping_method: Literal["jaccard", "gaussian", "scarches", "inverse_distance", "random", "hnoca"] = "gaussian",
|
|
435
|
+
prediction_postfix: str = "pred",
|
|
436
|
+
) -> "CellMapper":
|
|
437
|
+
"""
|
|
438
|
+
Fit the CellMapper model.
|
|
439
|
+
|
|
440
|
+
Parameters
|
|
441
|
+
----------
|
|
442
|
+
obs_keys
|
|
443
|
+
One or more keys in ``ref.obs`` to be transferred into ``query.obs`` (must be discrete)
|
|
444
|
+
obsm_keys
|
|
445
|
+
One or more keys in ``ref.obsm`` storing the embeddings to be transferred.
|
|
446
|
+
layer_key
|
|
447
|
+
Key in ``ref.layers`` to be transferred. Use "X" to transfer ``ref.X``.
|
|
448
|
+
n_neighbors
|
|
449
|
+
Number of nearest neighbors.
|
|
450
|
+
use_rep
|
|
451
|
+
Data representation based on which to find nearest neighbors.
|
|
452
|
+
knn_method
|
|
453
|
+
Method to use for computing neighbors.
|
|
454
|
+
metric
|
|
455
|
+
Distance metric to use for nearest neighbors.
|
|
456
|
+
only_yx
|
|
457
|
+
If True, only compute the xy neighbors. This is faster, but not suitable for Jaccard or HNOCA methods.
|
|
458
|
+
mapping_method
|
|
459
|
+
Method to use for computing the mapping matrix.
|
|
460
|
+
prediction_postfix
|
|
461
|
+
Postfix added to create new keys in ``query.obs`` for the transferred labels or in ``query.obsm`` for the transferred embeddings.
|
|
462
|
+
"""
|
|
463
|
+
self.compute_neighbors(
|
|
464
|
+
n_neighbors=n_neighbors, use_rep=use_rep, method=knn_method, metric=metric, only_yx=only_yx
|
|
465
|
+
)
|
|
466
|
+
self.compute_mappping_matrix(method=mapping_method)
|
|
467
|
+
if obs_keys is not None:
|
|
468
|
+
self.transfer_labels(obs_keys=obs_keys, prediction_postfix=prediction_postfix)
|
|
469
|
+
if obsm_keys is not None:
|
|
470
|
+
self.transfer_embeddings(obsm_keys=obsm_keys, prediction_postfix=prediction_postfix)
|
|
471
|
+
if layer_key is not None:
|
|
472
|
+
self.transfer_expression(layer_key=layer_key)
|
|
473
|
+
if obs_keys is None and obsm_keys is None and layer_key is None:
|
|
474
|
+
logger.warning(
|
|
475
|
+
"Neither ``obs_keys``, ``obsm_keys`` or ``layer_key`` provided. No labels, embeddings or layers were transferred. "
|
|
476
|
+
"Please provide at least one of ``obs_keys``, ``obsm_keys`` or ``layer_key``."
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
return self
|
cellmapper/check.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""Dependency checking."""
|
|
2
|
+
|
|
3
|
+
import importlib
|
|
4
|
+
import types
|
|
5
|
+
|
|
6
|
+
from packaging.version import parse
|
|
7
|
+
|
|
8
|
+
from . import version
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Checker:
|
|
12
|
+
"""
|
|
13
|
+
Checks availability and version of a Python module dependency.
|
|
14
|
+
|
|
15
|
+
Adapted from the scGLUE package: https://github.com/gao-lab/GLUE
|
|
16
|
+
|
|
17
|
+
Parameters
|
|
18
|
+
----------
|
|
19
|
+
name
|
|
20
|
+
Name of the dependency
|
|
21
|
+
package_name
|
|
22
|
+
Name of the package to check version for (if different from module name)
|
|
23
|
+
vmin
|
|
24
|
+
Minimal required version
|
|
25
|
+
install_hint
|
|
26
|
+
Install hint message to be printed if dependency is unavailable
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self, name: str, package_name: str | None = None, vmin: str | None = None, install_hint: str | None = None
|
|
31
|
+
) -> None:
|
|
32
|
+
self.name = name
|
|
33
|
+
self.package_name = package_name or name
|
|
34
|
+
self.vmin = parse(vmin) if vmin else vmin
|
|
35
|
+
vreq = f" (>={self.vmin})" if self.vmin else ""
|
|
36
|
+
self.vreq_hint = f"This function relies on {self.name}{vreq}."
|
|
37
|
+
self.install_hint = install_hint
|
|
38
|
+
|
|
39
|
+
def check(self) -> None:
|
|
40
|
+
"""Check if the dependency is available and meets the version requirement."""
|
|
41
|
+
try:
|
|
42
|
+
importlib.import_module(self.name)
|
|
43
|
+
except ModuleNotFoundError as e:
|
|
44
|
+
raise RuntimeError(" ".join(filter(None, [self.vreq_hint, self.install_hint]))) from e
|
|
45
|
+
v = parse(version(self.package_name))
|
|
46
|
+
if self.vmin and v < self.vmin:
|
|
47
|
+
raise RuntimeError(
|
|
48
|
+
" ".join(
|
|
49
|
+
[
|
|
50
|
+
self.vreq_hint,
|
|
51
|
+
f"Detected version is {v}.",
|
|
52
|
+
"Please install a newer version.",
|
|
53
|
+
self.install_hint or "",
|
|
54
|
+
]
|
|
55
|
+
)
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
INSTALL_HINTS = types.SimpleNamespace(
|
|
60
|
+
rapids="To speed up k-NN search on GPU, you may install rapids following the guide from "
|
|
61
|
+
"https://docs.rapids.ai/install/. Note that you will only need cuML.",
|
|
62
|
+
faiss="To speed up k-NN search on GPU, you may install faiss following the guide from "
|
|
63
|
+
"https://github.com/facebookresearch/faiss/blob/main/INSTALL.md",
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
CHECKERS = {
|
|
67
|
+
"rapids": Checker("rapids", vmin=None, install_hint=INSTALL_HINTS.rapids),
|
|
68
|
+
"faiss": Checker("faiss", package_name="faiss", vmin="1.7.0", install_hint=INSTALL_HINTS.faiss),
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def check_deps(*args) -> None:
|
|
73
|
+
"""
|
|
74
|
+
Check whether certain dependencies are installed
|
|
75
|
+
|
|
76
|
+
Parameters
|
|
77
|
+
----------
|
|
78
|
+
args
|
|
79
|
+
A list of dependencies to check
|
|
80
|
+
"""
|
|
81
|
+
for item in args:
|
|
82
|
+
CHECKERS[item].check()
|