symphonypy 0.2.3__tar.gz → 0.2.5__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: symphonypy
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: Porting of Symphony R package to Python
5
5
  Home-page: https://github.com/potulabe/symphonypy
6
6
  Author: Kseniya Petrova, Sergey Isaev
@@ -8,7 +8,7 @@ Author-email: praefrontalis@gmail.com, serj.hoop@gmail.com
8
8
  Classifier: Programming Language :: Python :: 3
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.8
11
+ Requires-Python: >=3.10
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
14
  Requires-Dist: harmonypy
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = symphonypy
3
- version = 0.2.3
3
+ version = attr: symphonypy.__version__
4
4
  author = Kseniya Petrova, Sergey Isaev
5
5
  author_email = praefrontalis@gmail.com, serj.hoop@gmail.com
6
6
  description = Porting of Symphony R package to Python
@@ -14,7 +14,7 @@ classifiers =
14
14
 
15
15
  [options]
16
16
  packages = find:
17
- python_requires = >=3.8
17
+ python_requires = >=3.10
18
18
  include_package_data = True
19
19
  install_requires =
20
20
  harmonypy
@@ -32,6 +32,8 @@ Symphony algorithm:
32
32
  5*. Count mapping confidence metrics
33
33
  """
34
34
 
35
+ __version__ = "0.2.5"
36
+
35
37
  from . import pp
36
38
  from . import tl
37
39
  from . import datasets
@@ -12,11 +12,76 @@ from harmonypy import run_harmony
12
12
  from scipy.sparse import issparse
13
13
  from sklearn.cluster import KMeans
14
14
 
15
- from scanpy.tools._ingest import Ingest, _DimDict
15
+ from collections.abc import MutableMapping
16
+ from scanpy.tools._ingest import Ingest
17
+
18
+ try:
19
+ from scanpy.tools._ingest import _DimDict
20
+ except ImportError:
21
+ class _DimDict(MutableMapping):
22
+ def __init__(self, dim, axis=0, vals=None):
23
+ self._data = {}
24
+ self._dim = dim
25
+ self._axis = axis
26
+ if vals is not None:
27
+ self.update(vals)
28
+
29
+ def __setitem__(self, key, value):
30
+ if value.shape[self._axis] != self._dim:
31
+ raise ValueError(
32
+ f"Value passed for key {key!r} is of incorrect shape. "
33
+ f"Value has shape {value.shape[self._axis]} "
34
+ f"for dimension {self._axis} while it should have {self._dim}."
35
+ )
36
+ self._data[key] = value
37
+
38
+ def __getitem__(self, key):
39
+ return self._data[key]
40
+
41
+ def __delitem__(self, key):
42
+ del self._data[key]
43
+
44
+ def __iter__(self):
45
+ return iter(self._data)
46
+
47
+ def __len__(self):
48
+ return len(self._data)
16
49
 
17
50
  logger = logging.getLogger("symphonypy")
18
51
 
19
52
 
53
+ def _harmony_sigma(ref_ho, harmony_kwargs, K):
54
+ """Extract sigma from a harmony result, falling back to the input
55
+ parameter when the backend (cpp) does not expose it."""
56
+ sigma = getattr(ref_ho, "sigma", None)
57
+ if sigma is not None:
58
+ return np.asarray(sigma, dtype=np.float32).ravel()
59
+ s = harmony_kwargs.get("sigma", 0.1)
60
+ if np.isscalar(s):
61
+ return np.full(int(K), float(s), dtype=np.float32)
62
+ return np.asarray(s, dtype=np.float32).ravel()
63
+
64
+
65
+ def _harmony_converged(ref_ho, harmony_kwargs):
66
+ """Backend-agnostic convergence flag. Returns True/False, or None
67
+ if it cannot be determined."""
68
+ if hasattr(ref_ho, "check_convergence"):
69
+ try:
70
+ return bool(ref_ho.check_convergence(1))
71
+ except Exception:
72
+ pass
73
+ obj = list(getattr(ref_ho, "objective_harmony", []) or [])
74
+ if len(obj) < 2:
75
+ return None
76
+ # Replicate torch backend's i_type=1 criterion.
77
+ eps = float(harmony_kwargs.get("epsilon_harmony", 1e-2))
78
+ max_iter = int(harmony_kwargs.get("max_iter_harmony", 10))
79
+ rel = (obj[-2] - obj[-1]) / (abs(obj[-2]) + 1e-12)
80
+ converged_by_eps = rel < eps
81
+ # If the loop stopped before max_iter, by construction it converged.
82
+ return bool(converged_by_eps or (len(obj) - 1) < max_iter)
83
+
84
+
20
85
  def _harmony_integrate_python(
21
86
  adata: AnnData,
22
87
  key: list[str] | str,
@@ -35,51 +100,42 @@ def _harmony_integrate_python(
35
100
  **harmony_kwargs,
36
101
  )
37
102
 
38
- # compatibility with old harmonypy implementations:
103
+ # Orientation: legacy harmonypy returned (d, N); both new backends
104
+ # return (N, d). The check disambiguates without relying on backend type.
39
105
  if ref_ho.Z_corr.shape[0] != adata.shape[0] or force_transpose_output:
40
- logger.info(
41
- "Assuming that the second dimension of Z_corr is the number of cells, transposing the output of harmonypy. "
42
- )
43
106
  Z_corr = ref_ho.Z_corr.T
44
107
  R = ref_ho.R
45
108
  else:
46
- logger.info(
47
- "Assuming that the first dimension of Z_corr is the number of cells, not transposing the output of harmonypy. "
48
- )
49
109
  if ref_ho.Z_corr.shape[0] == ref_ho.Z_corr.shape[1]:
50
110
  logger.warning(
51
- "Number of cells in the output of harmonypy is equal to the number of dimensions, can't automatically determine if transposition is needed. Use force_transpose_output parameter to specify the correct orientation of the output."
111
+ "Z_corr is square (%d x %d); orientation is ambiguous. "
112
+ "Pass force_transpose_output=True if results look wrong.",
113
+ ref_ho.Z_corr.shape[0], ref_ho.Z_corr.shape[1],
52
114
  )
53
115
  Z_corr = ref_ho.Z_corr
54
116
  R = ref_ho.R.T
55
117
 
56
- adata.obsm[ref_basis_adjusted] = Z_corr
118
+ K = int(ref_ho.K)
119
+ converged = _harmony_converged(ref_ho, harmony_kwargs)
120
+ sigma = _harmony_sigma(ref_ho, harmony_kwargs, K)
57
121
 
58
- converged = ref_ho.check_convergence(1)
59
-
60
- # [K, d] = [K, Nref] x [N_ref, d]
61
- C = R @ Z_corr
122
+ adata.obsm[ref_basis_adjusted] = Z_corr
123
+ C = R @ Z_corr # [K, d]
62
124
 
63
125
  adata.uns["harmony"] = {
64
- # [K] the number of cells softly belonging to each cluster
65
126
  "Nr": R.sum(axis=1),
66
- # ref cluster centroids
67
- # [K, d]
68
127
  "C": C,
69
- # number of clusters
70
- "K": ref_ho.K,
71
- # sigma [K] (cluster cross entropy regularization coef)
72
- "sigma": ref_ho.sigma,
128
+ "K": K,
129
+ "sigma": sigma,
73
130
  "ref_basis_loadings": ref_basis_loadings,
74
131
  "ref_basis_adjusted": ref_basis_adjusted,
75
132
  "vars_use": key,
76
133
  "harmony_kwargs": harmony_kwargs,
77
134
  "converged": converged,
78
- # [K, Nref]
79
135
  "R": R,
80
136
  }
81
137
 
82
- if not converged:
138
+ if converged is False:
83
139
  logger.warning(
84
140
  "Harmony didn't converge. "
85
141
  "Consider increasing max_iter_harmony parameter value"
@@ -361,7 +417,7 @@ def _run_soft_kmeans(
361
417
  # number of clusters
362
418
  "K": K,
363
419
  # sigma [K] (cluster cross enthropy regularization coef)
364
- "sigma": None,
420
+ "sigma": np.full(int(K), float(sigma), dtype=np.float32) if np.isscalar(sigma) else np.asarray(sigma, dtype=np.float32).ravel(),
365
421
  "ref_basis_loadings": ref_basis_loadings,
366
422
  "ref_basis_adjusted": ref_basis,
367
423
  "vars_use": None,
@@ -378,6 +434,81 @@ class Ingest_sp(Ingest):
378
434
 
379
435
  super().__init__(*args, **kwargs)
380
436
 
437
+ def _init_pynndescent(self, distances, *args, **kwargs):
438
+ if args or kwargs:
439
+ return super()._init_pynndescent(distances, *args, **kwargs)
440
+
441
+ from pynndescent import NNDescent
442
+
443
+ first_col = np.arange(distances.shape[0])[:, None]
444
+ init_indices = np.hstack((first_col, np.stack(distances.tolil().rows)))
445
+
446
+ self._nnd_idx = NNDescent(
447
+ data=self._rep,
448
+ metric=self._metric,
449
+ metric_kwds=self._metric_kwds,
450
+ n_neighbors=self._n_neighbors,
451
+ init_graph=init_indices,
452
+ random_state=self._neigh_random_state,
453
+ )
454
+
455
+ # Needed only for legacy pynndescent (<0.6); in pynndescent >=0.8 n_search_trees is None
456
+ if getattr(self._nnd_idx, "n_search_trees", None) is not None:
457
+ from pynndescent.rp_trees import make_forest
458
+ from sklearn.utils import check_random_state
459
+
460
+ current_random_state = check_random_state(self._nnd_idx.random_state)
461
+ self._nnd_idx._rp_forest = make_forest(
462
+ self._nnd_idx._raw_data,
463
+ self._nnd_idx.n_neighbors,
464
+ self._nnd_idx.n_search_trees,
465
+ self._nnd_idx.leaf_size,
466
+ self._nnd_idx.rng_state,
467
+ current_random_state,
468
+ self._nnd_idx.n_jobs,
469
+ self._nnd_idx._angular_trees,
470
+ )
471
+
472
+ def _init_umap(self, adata, *args, **kwargs):
473
+ if args or kwargs:
474
+ return super()._init_umap(adata, *args, **kwargs)
475
+
476
+ from inspect import signature
477
+ from umap import UMAP
478
+
479
+ compat = (
480
+ {"compatibility_layout": True}
481
+ if "compatibility_layout" in signature(UMAP).parameters
482
+ else {}
483
+ )
484
+ self._umap = UMAP(
485
+ **compat,
486
+ metric=self._metric,
487
+ random_state=adata.uns["umap"]["params"].get("random_state", 0),
488
+ n_jobs=1,
489
+ )
490
+
491
+ self._umap._initial_alpha = self._umap.learning_rate
492
+ self._umap._raw_data = self._rep
493
+ self._umap.knn_dists = None
494
+
495
+ self._umap._validate_parameters()
496
+
497
+ self._umap.embedding_ = adata.obsm["X_umap"]
498
+ self._umap._sparse_data = issparse(self._rep)
499
+ self._umap._small_data = self._rep.shape[0] < 4096
500
+ self._umap._metric_kwds = self._metric_kwds
501
+
502
+ self._umap._n_neighbors = self._n_neighbors
503
+ self._umap.n_neighbors = self._n_neighbors
504
+
505
+ self._umap._knn_search_index = self._nnd_idx
506
+
507
+ self._umap._a = adata.uns["umap"]["params"]["a"]
508
+ self._umap._b = adata.uns["umap"]["params"]["b"]
509
+
510
+ self._umap._input_hash = None
511
+
381
512
  def fit(self, adata_new: AnnData):
382
513
  self._obs = pd.DataFrame(index=adata_new.obs.index)
383
514
  self._obsm = _DimDict(adata_new.n_obs, axis=0)
@@ -406,14 +537,22 @@ class Ingest_sp(Ingest):
406
537
  )
407
538
  return adata.X
408
539
 
409
- if self._use_rep in adata.obsm.keys():
540
+ if isinstance(self._use_rep, str) and self._use_rep in adata.obsm.keys():
410
541
  return adata.obsm[self._use_rep]
411
542
 
543
+ if not isinstance(self._use_rep, str):
544
+ return super()._same_rep()
545
+
412
546
  return adata.X
413
547
 
414
548
  def _pca(self, n_pcs=None):
415
-
416
- if self._pca_use_hvg:
549
+ if hasattr(self, "_pca_mask"):
550
+ use_genes_list = (
551
+ self._adata_ref.var_names[self._pca_mask]
552
+ if self._pca_mask is not None
553
+ else self._adata_ref.var_names
554
+ )
555
+ elif getattr(self, "_pca_use_hvg", False):
417
556
  use_genes_list = self._adata_ref.var_names[
418
557
  self._adata_ref.var["highly_variable"]
419
558
  ]
@@ -437,6 +576,18 @@ class Ingest_sp(Ingest):
437
576
 
438
577
  return X_pca
439
578
 
579
+ def to_adata(self, inplace: bool = False) -> AnnData | None:
580
+ adata = self._adata_new if inplace else self._adata_new.copy()
581
+
582
+ adata.obsm.update(self._obsm)
583
+
584
+ for key in self._obs:
585
+ adata.obs[key] = self._obs[key]
586
+
587
+ if not inplace:
588
+ return adata
589
+ return None
590
+
440
591
 
441
592
  def _cluster_maha_dist(
442
593
  adata_query_cluster_obs: pd.DataFrame,
@@ -4,17 +4,18 @@ from __future__ import annotations
4
4
  import logging
5
5
  import warnings
6
6
 
7
- from typing import Iterable, List, Optional, Union
7
+ from typing import Iterable, List, Optional, Union, TYPE_CHECKING
8
+ if TYPE_CHECKING:
9
+ from openTSNE import TSNEEmbedding
8
10
 
9
11
  import numpy as np
10
12
  import pandas as pd
11
13
 
12
14
  from anndata import AnnData
15
+ from importlib.metadata import version as _pkg_version
13
16
  from packaging import version
14
17
  from sklearn.neighbors import KNeighborsClassifier
15
18
 
16
- from scanpy._compat import pkg_version
17
-
18
19
  from ._utils import (
19
20
  _assign_clusters,
20
21
  _correct_query,
@@ -158,15 +159,21 @@ def per_cluster_confidence(
158
159
  reference_cluster_centroids, ord=2, axis=1, keepdims=True
159
160
  )
160
161
  grouped = adata_query.obs.groupby(cluster_key, observed=True)
161
- dists = grouped.apply(
162
- _cluster_maha_dist,
163
- adata_query,
164
- transferred_primary_basis=transferred_primary_basis,
165
- reference_cluster_centroids=reference_cluster_centroids,
166
- reference_cluster_centroids_norm=reference_cluster_centroids_norm,
167
- u=u,
168
- lamb=lamb,
169
- )
162
+
163
+ def _apply(g):
164
+ return _cluster_maha_dist(
165
+ g, adata_query,
166
+ transferred_primary_basis=transferred_primary_basis,
167
+ reference_cluster_centroids=reference_cluster_centroids,
168
+ reference_cluster_centroids_norm=reference_cluster_centroids_norm,
169
+ u=u, lamb=lamb,
170
+ )
171
+
172
+ try:
173
+ dists = grouped.apply(_apply, include_groups=False)
174
+ except TypeError:
175
+ # pandas < 2.2
176
+ dists = grouped.apply(_apply)
170
177
 
171
178
  if uns is not None:
172
179
  adata_query.uns[uns] = {
@@ -212,7 +219,7 @@ def ingest(
212
219
  :type use_rep: str | None, optional
213
220
  :return: if ``inplace=False`` returns a copy of ``adata_query`` with additional slots, otherwise adds to ``adata_query``.
214
221
  """
215
- anndata_version = pkg_version("anndata")
222
+ anndata_version = version.parse(_pkg_version("anndata"))
216
223
  if anndata_version < ANNDATA_MIN_VERSION:
217
224
  raise ValueError(
218
225
  f"ingest only works correctly with anndata>={ANNDATA_MIN_VERSION} "
@@ -220,7 +227,7 @@ def ingest(
220
227
  "`AnnData.concatenate` did not concatenate `.obsm`."
221
228
  )
222
229
 
223
- start = logger.info("running ingest")
230
+ logger.info("running ingest")
224
231
  obs = [obs] if isinstance(obs, str) else obs
225
232
  embedding_method = (
226
233
  [embedding_method] if isinstance(embedding_method, str) else embedding_method
@@ -236,16 +243,19 @@ def ingest(
236
243
  if neighbors_key is None:
237
244
  neighbors_key = "neighbors"
238
245
  if neighbors_key in adata_ref.uns:
246
+ params = adata_ref.uns[neighbors_key].get("params", {})
239
247
  if use_rep is None:
240
- if "use_rep" not in adata_ref.uns[neighbors_key]["params"]:
248
+ if "use_rep" not in params and "layer" not in params:
241
249
  warnings.warn(
242
250
  "'X_pca' representation will be used for neighbors search in adata_query"
243
251
  )
244
- adata_ref.uns[neighbors_key]["params"]["use_rep"] = "X_pca"
245
- else:
252
+ adata_ref.uns[neighbors_key].setdefault("params", {})[
253
+ "use_rep"
254
+ ] = "X_pca"
255
+ elif "use_rep" in params:
246
256
  logger.info(
247
257
  "'%s' representation will be used for neighbors search in adata_query",
248
- adata_ref.uns[neighbors_key]["params"]["use_rep"],
258
+ params["use_rep"],
249
259
  )
250
260
 
251
261
  ing = Ingest_sp(adata_ref, neighbors_key, use_representation=use_rep)
@@ -264,7 +274,7 @@ def ingest(
264
274
  if "rep" in ing._obsm:
265
275
  del ing._obsm["rep"]
266
276
 
267
- return ing.to_adata(inplace)
277
+ return ing.to_adata(inplace=inplace)
268
278
 
269
279
 
270
280
  def map_embedding(
@@ -293,7 +303,7 @@ def map_embedding(
293
303
  :type key: list[str] | str | None, optional
294
304
  :param lamb: Entropy regularization parameter for soft k-means, defaults to None
295
305
  :type lamb: float | np.array | None, optional
296
- :param sigma: Ridge regularization parameter for the linear model, defaults to 0.1
306
+ :param sigma: Soft k-means kernel bandwidth. Only used when the reference Harmony object does not carry its own sigma (i.e. the no-batch soft-kmeans path). When ``adata_ref`` was produced by ``pp.harmony_integrate``, the reference's sigma is reused, as Symphony requires. Default 0.1.
297
307
  :type sigma: float | np.array, optional
298
308
  :param use_genes_column: ``adata_ref.var[use_genes_column]`` genes will be used to map query embeddings to reference, defaults to "highly_variable"
299
309
  :type use_genes_column: str | None, optional
@@ -360,7 +370,15 @@ def map_embedding(
360
370
  C = harmony_ref["C"]
361
371
  Y = C / np.linalg.norm(C, ord=2, axis=1, keepdims=True)
362
372
 
363
- R = _assign_clusters(X, sigma, Y, harmony_ref["K"])
373
+ K_eff = int(harmony_ref["K"])
374
+ ref_sigma = harmony_ref.get("sigma")
375
+ if ref_sigma is not None:
376
+ sigma_eff = np.asarray(ref_sigma, dtype=np.float64).ravel()
377
+ if sigma_eff.size == 1:
378
+ sigma_eff = np.repeat(sigma_eff, K_eff)
379
+ else:
380
+ sigma_eff = sigma
381
+ R = _assign_clusters(X, sigma_eff, Y, K_eff)
364
382
 
365
383
  # 3. correct query embeddings
366
384
  # likewise harmonypy
@@ -376,7 +394,9 @@ def map_embedding(
376
394
  # [B + 1, N]
377
395
  phi_ = np.concatenate([np.ones((1, phi.shape[1])), phi], axis=0)
378
396
 
379
- phi_n = batch_data.describe().loc["unique"].to_numpy().astype(int)
397
+ phi_n = np.array(
398
+ [batch_data[col].nunique() for col in batch_data.columns], dtype=int
399
+ )
380
400
  # lambda (ridge regularization coef)
381
401
  if lamb is None:
382
402
  lamb = np.repeat([1] * len(phi_n), phi_n)
@@ -439,7 +459,7 @@ def tsne(
439
459
  adata: AnnData,
440
460
  use_rep: str = "X_pca",
441
461
  t_sne_slot: str = "X_tsne",
442
- use_model: "openTSNE.TSNEEmbedding" | str | None = None,
462
+ use_model: TSNEEmbedding | str | None = None,
443
463
  save_path: str | None = None,
444
464
  use_raw: bool | None = None,
445
465
  return_model: bool = False,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: symphonypy
3
- Version: 0.2.3
3
+ Version: 0.2.5
4
4
  Summary: Porting of Symphony R package to Python
5
5
  Home-page: https://github.com/potulabe/symphonypy
6
6
  Author: Kseniya Petrova, Sergey Isaev
@@ -8,7 +8,7 @@ Author-email: praefrontalis@gmail.com, serj.hoop@gmail.com
8
8
  Classifier: Programming Language :: Python :: 3
9
9
  Classifier: License :: OSI Approved :: MIT License
10
10
  Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.8
11
+ Requires-Python: >=3.10
12
12
  Description-Content-Type: text/markdown
13
13
  License-File: LICENSE
14
14
  Requires-Dist: harmonypy
@@ -0,0 +1,113 @@
1
+ import warnings
2
+
3
+ import numpy as np
4
+ import scanpy as sc
5
+ import symphonypy as sp
6
+
7
+
8
+ class TestTools:
9
+ adata_query_fp = "tests/data/PBMC_Satija.query_subsample.h5ad"
10
+ adata_query_res_fp = "tests/data/PBMC_Satija.symphony.h5ad"
11
+ adata_ref_fp = "tests/data/PBMC_Satija.harmony.h5ad"
12
+ query_batch_key = "orig.ident"
13
+ query_clusters = "leiden"
14
+
15
+ @staticmethod
16
+ def assert_equals(f, s, threshold=1e-7):
17
+ assert (abs(f - s) < threshold).all()
18
+
19
+ def test_map_embedding(self):
20
+ adata_query = sc.read_h5ad(self.adata_query_fp)
21
+ adata_ref = sc.read_h5ad(self.adata_ref_fp)
22
+ sp.tl.map_embedding(
23
+ adata_query=adata_query, adata_ref=adata_ref, key=self.query_batch_key
24
+ )
25
+
26
+ adata_query_res = sc.read_h5ad(self.adata_query_res_fp)
27
+
28
+ self.assert_equals(
29
+ adata_query.obsm["X_pca_reference"], adata_query_res.obsm["X_pca_reference"]
30
+ )
31
+ self.assert_equals(
32
+ adata_query.obsm["X_pca_harmony"], adata_query_res.obsm["X_pca_harmony"]
33
+ )
34
+
35
+ sp.tl.per_cell_confidence(adata_query, adata_ref)
36
+
37
+ self.assert_equals(
38
+ adata_query.obs["symphony_per_cell_dist"],
39
+ adata_query_res.obs["symphony_per_cell_dist"],
40
+ )
41
+
42
+ sp.tl.per_cluster_confidence(adata_query, adata_ref, self.query_clusters)
43
+
44
+ self.assert_equals(
45
+ adata_query.obs["symphony_per_cluster_dist"],
46
+ adata_query_res.obs["symphony_per_cluster_dist"],
47
+ )
48
+
49
+ self.assert_equals(
50
+ adata_query.uns["symphony_per_cluster_dist"]["dist"],
51
+ adata_query_res.uns["symphony_per_cluster_dist"]["dist"],
52
+ )
53
+
54
+ assert (
55
+ adata_query.uns["symphony_per_cluster_dist"]["cluster_labels"]
56
+ == adata_query_res.uns["symphony_per_cluster_dist"]["cluster_labels"]
57
+ ).all()
58
+
59
+ def test_ingest(self):
60
+ adata_ref = sc.read_h5ad(self.adata_ref_fp)
61
+ adata_query = sc.read_h5ad(self.adata_query_res_fp)
62
+
63
+ sc.pp.neighbors(adata_ref, use_rep="X_pca_harmony", random_state=0)
64
+ sc.tl.umap(adata_ref, random_state=0)
65
+
66
+ # 1. Default inplace=True + obs label transfer (with different var_names)
67
+ q_inplace = adata_query.copy()
68
+ del q_inplace.obs["celltype.l1"]
69
+ ret = sp.tl.ingest(q_inplace, adata_ref, obs="celltype.l1")
70
+ assert ret is None
71
+ assert "X_umap" in q_inplace.obsm
72
+ assert q_inplace.obsm["X_umap"].shape == (q_inplace.n_obs, 2)
73
+ assert np.isfinite(q_inplace.obsm["X_umap"]).all()
74
+ assert "rep" not in q_inplace.obsm
75
+ assert "celltype.l1" in q_inplace.obs
76
+ assert set(q_inplace.obs["celltype.l1"].unique()).issubset(
77
+ set(adata_ref.obs["celltype.l1"].unique())
78
+ )
79
+
80
+ # 2. inplace=False returns a modified copy without mutating input
81
+ q_orig = adata_query.copy()
82
+ q_copy = sp.tl.ingest(q_orig, adata_ref, inplace=False)
83
+ assert q_copy is not None
84
+ assert q_copy is not q_orig
85
+ assert "X_umap" not in q_orig.obsm
86
+ assert "X_umap" in q_copy.obsm
87
+ assert q_copy.obsm["X_umap"].shape == (q_orig.n_obs, 2)
88
+ assert np.isfinite(q_copy.obsm["X_umap"]).all()
89
+
90
+ # 3. Explicit use_rep + embedding_method="pca" (with missing genes)
91
+ adata_ref_pca = sc.read_h5ad(self.adata_ref_fp)
92
+ sc.pp.neighbors(adata_ref_pca, use_rep="X_pca", random_state=0)
93
+ sc.tl.umap(adata_ref_pca, random_state=0)
94
+
95
+ q_use_rep = adata_query.copy()
96
+ with warnings.catch_warnings(record=True) as caught:
97
+ warnings.simplefilter("always")
98
+ sp.tl.ingest(q_use_rep, adata_ref_pca, use_rep="X_pca_harmony")
99
+ assert "X_umap" in q_use_rep.obsm
100
+ assert any("was used for query" in str(w.message) for w in caught)
101
+
102
+ # Drop several reference genes from query to exercise _pca missing-gene handling
103
+ keep_genes = adata_query.var_names[
104
+ ~adata_query.var_names.isin(adata_ref_pca.var_names[:20])
105
+ ]
106
+ q_pca = adata_query[:, keep_genes].copy()
107
+ sp.tl.ingest(q_pca, adata_ref_pca, embedding_method="pca")
108
+ assert "X_pca" in q_pca.obsm
109
+ assert q_pca.obsm["X_pca"].shape == (
110
+ q_pca.n_obs,
111
+ adata_ref_pca.varm["PCs"].shape[1],
112
+ )
113
+ assert np.isfinite(q_pca.obsm["X_pca"]).all()
@@ -1,54 +0,0 @@
1
- import scanpy as sc
2
- import symphonypy as sp
3
-
4
-
5
- class TestTools:
6
- adata_query_fp = "tests/data/PBMC_Satija.query_subsample.h5ad"
7
- adata_query_res_fp = "tests/data/PBMC_Satija.symphony.h5ad"
8
- adata_ref_fp = "tests/data/PBMC_Satija.harmony.h5ad"
9
- query_batch_key = "orig.ident"
10
- query_clusters = "leiden"
11
-
12
- @staticmethod
13
- def assert_equals(f, s, threshold=1e-7):
14
- assert (abs(f - s) < threshold).all()
15
-
16
- def test_map_embedding(self):
17
- adata_query = sc.read_h5ad(self.adata_query_fp)
18
- adata_ref = sc.read_h5ad(self.adata_ref_fp)
19
- sp.tl.map_embedding(
20
- adata_query=adata_query, adata_ref=adata_ref, key=self.query_batch_key
21
- )
22
-
23
- adata_query_res = sc.read_h5ad(self.adata_query_res_fp)
24
-
25
- self.assert_equals(
26
- adata_query.obsm["X_pca_reference"], adata_query_res.obsm["X_pca_reference"]
27
- )
28
- self.assert_equals(
29
- adata_query.obsm["X_pca_harmony"], adata_query_res.obsm["X_pca_harmony"]
30
- )
31
-
32
- sp.tl.per_cell_confidence(adata_query, adata_ref)
33
-
34
- self.assert_equals(
35
- adata_query.obs["symphony_per_cell_dist"],
36
- adata_query_res.obs["symphony_per_cell_dist"],
37
- )
38
-
39
- sp.tl.per_cluster_confidence(adata_query, adata_ref, self.query_clusters)
40
-
41
- self.assert_equals(
42
- adata_query.obs["symphony_per_cluster_dist"],
43
- adata_query_res.obs["symphony_per_cluster_dist"],
44
- )
45
-
46
- self.assert_equals(
47
- adata_query.uns["symphony_per_cluster_dist"]["dist"],
48
- adata_query_res.uns["symphony_per_cluster_dist"]["dist"],
49
- )
50
-
51
- assert (
52
- adata_query.uns["symphony_per_cluster_dist"]["cluster_labels"]
53
- == adata_query_res.uns["symphony_per_cluster_dist"]["cluster_labels"]
54
- ).all()
File without changes
File without changes
File without changes
File without changes