-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy path_distance.py
More file actions
353 lines (311 loc) · 11.5 KB
/
_distance.py
File metadata and controls
353 lines (311 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
from __future__ import annotations
import warnings
from typing import TYPE_CHECKING, Literal, NamedTuple
if TYPE_CHECKING:
from collections.abc import Sequence
import cupy as cp
import numpy as np
import pandas as pd
from anndata import AnnData
class MeanVar(NamedTuple):
"""Result of bootstrap computation containing mean and variance."""
mean: float
variance: float
class Distance:
"""
GPU-accelerated distance computation between groups of cells.
API compatible with pertpy's Distance class.
Currently supported metrics:
- ``"edistance"``: Energy distance (default).
Twice the mean pairwise distance between cells of two groups minus
the mean pairwise distance between cells within each group. See
`Peidli et al. (2023) <https://doi.org/10.1101/2022.08.20.504663>`__.
Parameters
----------
metric
Distance metric to use. Currently only ``"edistance"`` is supported.
layer_key
Key in adata.layers for cell data. Mutually exclusive with ``obsm_key``.
obsm_key
Key in adata.obsm for embeddings. Mutually exclusive with ``layer_key``.
Defaults to ``"X_pca"`` if neither is specified.
Notes
-----
The bootstrap implementation differs from pertpy: rather than precomputing
an n×n cell distance matrix and sampling from it, this implementation
resamples cells and recomputes distances from scratch each iteration.
This scales better for large datasets (O(n) vs O(n²) memory) and leverages
multi-GPU parallelism for each bootstrap iteration.
Examples
--------
>>> import rapids_singlecell as rsc
>>> distance = rsc.ptg.Distance(metric='edistance')
>>> result = distance.pairwise(adata, groupby='perturbation')
>>> # Direct computation on arrays
>>> d = distance(X, Y)
"""
def __init__(
self,
metric: Literal["edistance"] = "edistance",
layer_key: str | None = None,
obsm_key: str | None = None,
):
"""Initialize Distance calculator with specified metric."""
if layer_key is not None and obsm_key is not None:
raise ValueError(
"Cannot use 'layer_key' and 'obsm_key' at the same time.\n"
"Please provide only one of the two keys."
)
if layer_key is None and obsm_key is None:
obsm_key = "X_pca"
self.metric = metric
self.layer_key = layer_key
self.obsm_key = obsm_key
self._metric_impl = None
self._initialize_metric()
def _initialize_metric(self):
"""Initialize the metric implementation based on the metric type."""
if self.metric == "edistance":
from rapids_singlecell.pertpy_gpu._metrics._edistance import (
EDistanceMetric,
)
self._metric_impl = EDistanceMetric(
layer_key=self.layer_key,
obsm_key=self.obsm_key,
)
else:
raise ValueError(
f"Unknown metric: {self.metric}. Supported metrics: ['edistance']"
)
def _check_multi_gpu_support(
self, *, multi_gpu: bool | list[int] | str | None
) -> bool | list[int] | str:
"""Check if metric supports multi-GPU and resolve None default.
Parameters
----------
multi_gpu
The multi_gpu parameter passed by the user. None means use default
(True if supported, False otherwise).
Returns
-------
multi_gpu
Returns False if metric doesn't support multi-GPU, otherwise
returns the resolved value (True if None was passed and supported).
"""
# If None, default to True if supported, False otherwise
if multi_gpu is None:
return self._metric_impl.supports_multi_gpu
if not self._metric_impl.supports_multi_gpu:
# Check if user explicitly requested multi-GPU
uses_multi_gpu = (
multi_gpu is True
or (isinstance(multi_gpu, list) and len(multi_gpu) > 1)
or (isinstance(multi_gpu, str) and "," in multi_gpu)
)
if uses_multi_gpu:
warnings.warn(
f"Metric '{self.metric}' does not support multi-GPU. "
"Falling back to single GPU (device 0).",
UserWarning,
stacklevel=3,
)
return False
return multi_gpu
def __call__(
self,
X: np.ndarray | cp.ndarray,
Y: np.ndarray | cp.ndarray,
) -> float:
"""
Compute distance between two cell groups directly from arrays.
This provides pertpy-compatible API for direct distance computation.
Parameters
----------
X
First array of shape (n_samples_x, n_features)
Y
Second array of shape (n_samples_y, n_features)
Returns
-------
float
Distance between X and Y
Examples
--------
>>> distance = Distance(metric='edistance')
>>> X = adata.obsm["X_pca"][adata.obs["group"] == "A"]
>>> Y = adata.obsm["X_pca"][adata.obs["group"] == "B"]
>>> d = distance(X, Y)
"""
if not hasattr(self._metric_impl, "compute_distance"):
raise NotImplementedError(
f"Metric '{self.metric}' does not support direct distance computation"
)
return self._metric_impl.compute_distance(X, Y)
def pairwise(
self,
adata: AnnData,
groupby: str,
*,
groups: Sequence[str] | None = None,
bootstrap: bool = False,
n_bootstrap: int = 100,
random_state: int = 0,
multi_gpu: bool | list[int] | str | None = None,
):
"""
Compute pairwise distances between all cell groups.
Parameters
----------
adata
Annotated data matrix
groupby
Key in adata.obs for grouping cells
groups
Specific groups to compute (if None, use all)
bootstrap
Whether to compute bootstrap variance estimates
n_bootstrap
Number of bootstrap iterations (if bootstrap=True)
random_state
Random seed for reproducibility
multi_gpu
GPU selection:
- None: Use all GPUs if metric supports it, else GPU 0 (default)
- True: Use all available GPUs
- False: Use only GPU 0
- list[int]: Use specific GPU IDs (e.g., [0, 2])
- str: Comma-separated GPU IDs (e.g., "0,2")
Returns
-------
result
DataFrame with pairwise distances. If bootstrap=True, returns
tuple of (distances, distances_var) DataFrames.
Examples
--------
>>> distance = Distance(metric='edistance')
>>> result = distance.pairwise(adata, groupby='condition')
"""
multi_gpu = self._check_multi_gpu_support(multi_gpu=multi_gpu)
return self._metric_impl.pairwise(
adata=adata,
groupby=groupby,
groups=groups,
bootstrap=bootstrap,
n_bootstrap=n_bootstrap,
random_state=random_state,
multi_gpu=multi_gpu,
)
def onesided_distances(
self,
adata: AnnData,
groupby: str,
selected_group: Sequence[str] | str,
*,
groups: Sequence[str] | None = None,
bootstrap: bool = False,
n_bootstrap: int = 100,
random_state: int = 0,
multi_gpu: bool | list[int] | str | None = None,
) -> pd.Series | tuple[pd.Series, pd.Series]:
"""
Compute distances from one selected group to all other groups.
Parameters
----------
adata
Annotated data matrix
groupby
Key in adata.obs for grouping cells
selected_group
Reference group to compute distances from
groups
Specific groups to compute distances to (if None, use all)
bootstrap
Whether to compute bootstrap variance estimates
n_bootstrap
Number of bootstrap iterations (if bootstrap=True)
random_state
Random seed for reproducibility
multi_gpu
GPU selection:
- None: Use all GPUs if metric supports it, else GPU 0 (default)
- True: Use all available GPUs
- False: Use only GPU 0
- list[int]: Use specific GPU IDs (e.g., [0, 2])
- str: Comma-separated GPU IDs (e.g., "0,2")
Returns
-------
distances
Series containing distances from selected_group to all other groups.
If bootstrap=True, returns tuple of (distances, distances_var).
Examples
--------
>>> distance = Distance(metric='edistance')
>>> distances = distance.onesided_distances(
... adata, groupby='condition', selected_group='control'
... )
"""
if not hasattr(self._metric_impl, "onesided_distances"):
raise NotImplementedError(
f"Metric '{self.metric}' does not support onesided_distances"
)
multi_gpu = self._check_multi_gpu_support(multi_gpu=multi_gpu)
return self._metric_impl.onesided_distances(
adata=adata,
groupby=groupby,
selected_group=selected_group,
groups=groups,
bootstrap=bootstrap,
n_bootstrap=n_bootstrap,
random_state=random_state,
multi_gpu=multi_gpu,
)
def bootstrap(
self,
X: np.ndarray | cp.ndarray,
Y: np.ndarray | cp.ndarray,
*,
n_bootstrap: int = 100,
random_state: int = 0,
) -> MeanVar:
"""
Compute bootstrap mean and variance for distance between two arrays.
This provides pertpy-compatible API for bootstrap computation directly
on arrays without requiring an AnnData object.
Parameters
----------
X
First array of shape (n_samples_x, n_features)
Y
Second array of shape (n_samples_y, n_features)
n_bootstrap
Number of bootstrap iterations
random_state
Random seed for reproducibility
Returns
-------
result
Named tuple containing mean and variance of bootstrapped distances
Examples
--------
>>> distance = Distance(metric='edistance')
>>> X = adata.obsm["X_pca"][adata.obs["group"] == "A"]
>>> Y = adata.obsm["X_pca"][adata.obs["group"] == "B"]
>>> result = distance.bootstrap(X, Y, n_bootstrap=100)
>>> print(f"Distance: {result.mean:.3f} ± {result.variance**0.5:.3f}")
"""
if not hasattr(self._metric_impl, "bootstrap_arrays"):
raise NotImplementedError(
f"Metric '{self.metric}' does not support bootstrap"
)
mean, variance = self._metric_impl.bootstrap_arrays(
X=X,
Y=Y,
n_bootstrap=n_bootstrap,
random_state=random_state,
)
return MeanVar(mean=mean, variance=variance)
def __repr__(self) -> str:
"""String representation of Distance object."""
if self.layer_key:
return f"Distance(metric='{self.metric}', layer_key='{self.layer_key}')"
return f"Distance(metric='{self.metric}', obsm_key='{self.obsm_key}')"