symphonypy 0.2.4__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.4
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.4
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,7 +12,40 @@ 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
 
@@ -401,6 +434,81 @@ class Ingest_sp(Ingest):
401
434
 
402
435
  super().__init__(*args, **kwargs)
403
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
+
404
512
  def fit(self, adata_new: AnnData):
405
513
  self._obs = pd.DataFrame(index=adata_new.obs.index)
406
514
  self._obsm = _DimDict(adata_new.n_obs, axis=0)
@@ -429,14 +537,22 @@ class Ingest_sp(Ingest):
429
537
  )
430
538
  return adata.X
431
539
 
432
- if self._use_rep in adata.obsm.keys():
540
+ if isinstance(self._use_rep, str) and self._use_rep in adata.obsm.keys():
433
541
  return adata.obsm[self._use_rep]
434
542
 
543
+ if not isinstance(self._use_rep, str):
544
+ return super()._same_rep()
545
+
435
546
  return adata.X
436
547
 
437
548
  def _pca(self, n_pcs=None):
438
-
439
- 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):
440
556
  use_genes_list = self._adata_ref.var_names[
441
557
  self._adata_ref.var["highly_variable"]
442
558
  ]
@@ -460,6 +576,18 @@ class Ingest_sp(Ingest):
460
576
 
461
577
  return X_pca
462
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
+
463
591
 
464
592
  def _cluster_maha_dist(
465
593
  adata_query_cluster_obs: pd.DataFrame,
@@ -12,11 +12,10 @@ import numpy as np
12
12
  import pandas as pd
13
13
 
14
14
  from anndata import AnnData
15
+ from importlib.metadata import version as _pkg_version
15
16
  from packaging import version
16
17
  from sklearn.neighbors import KNeighborsClassifier
17
18
 
18
- from scanpy._compat import pkg_version
19
-
20
19
  from ._utils import (
21
20
  _assign_clusters,
22
21
  _correct_query,
@@ -220,7 +219,7 @@ def ingest(
220
219
  :type use_rep: str | None, optional
221
220
  :return: if ``inplace=False`` returns a copy of ``adata_query`` with additional slots, otherwise adds to ``adata_query``.
222
221
  """
223
- anndata_version = pkg_version("anndata")
222
+ anndata_version = version.parse(_pkg_version("anndata"))
224
223
  if anndata_version < ANNDATA_MIN_VERSION:
225
224
  raise ValueError(
226
225
  f"ingest only works correctly with anndata>={ANNDATA_MIN_VERSION} "
@@ -228,7 +227,7 @@ def ingest(
228
227
  "`AnnData.concatenate` did not concatenate `.obsm`."
229
228
  )
230
229
 
231
- start = logger.info("running ingest")
230
+ logger.info("running ingest")
232
231
  obs = [obs] if isinstance(obs, str) else obs
233
232
  embedding_method = (
234
233
  [embedding_method] if isinstance(embedding_method, str) else embedding_method
@@ -244,16 +243,19 @@ def ingest(
244
243
  if neighbors_key is None:
245
244
  neighbors_key = "neighbors"
246
245
  if neighbors_key in adata_ref.uns:
246
+ params = adata_ref.uns[neighbors_key].get("params", {})
247
247
  if use_rep is None:
248
- if "use_rep" not in adata_ref.uns[neighbors_key]["params"]:
248
+ if "use_rep" not in params and "layer" not in params:
249
249
  warnings.warn(
250
250
  "'X_pca' representation will be used for neighbors search in adata_query"
251
251
  )
252
- adata_ref.uns[neighbors_key]["params"]["use_rep"] = "X_pca"
253
- else:
252
+ adata_ref.uns[neighbors_key].setdefault("params", {})[
253
+ "use_rep"
254
+ ] = "X_pca"
255
+ elif "use_rep" in params:
254
256
  logger.info(
255
257
  "'%s' representation will be used for neighbors search in adata_query",
256
- adata_ref.uns[neighbors_key]["params"]["use_rep"],
258
+ params["use_rep"],
257
259
  )
258
260
 
259
261
  ing = Ingest_sp(adata_ref, neighbors_key, use_representation=use_rep)
@@ -272,7 +274,7 @@ def ingest(
272
274
  if "rep" in ing._obsm:
273
275
  del ing._obsm["rep"]
274
276
 
275
- return ing.to_adata(inplace)
277
+ return ing.to_adata(inplace=inplace)
276
278
 
277
279
 
278
280
  def map_embedding(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: symphonypy
3
- Version: 0.2.4
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