symphonypy 0.2.3__tar.gz → 0.2.4__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.
- {symphonypy-0.2.3/symphonypy.egg-info → symphonypy-0.2.4}/PKG-INFO +1 -1
- {symphonypy-0.2.3 → symphonypy-0.2.4}/setup.cfg +1 -1
- {symphonypy-0.2.3 → symphonypy-0.2.4}/symphonypy/_utils.py +46 -23
- {symphonypy-0.2.3 → symphonypy-0.2.4}/symphonypy/tl.py +32 -14
- {symphonypy-0.2.3 → symphonypy-0.2.4/symphonypy.egg-info}/PKG-INFO +1 -1
- {symphonypy-0.2.3 → symphonypy-0.2.4}/LICENSE +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/README.md +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/pyproject.toml +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/symphonypy/__init__.py +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/symphonypy/datasets.py +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/symphonypy/pp.py +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/symphonypy.egg-info/SOURCES.txt +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/symphonypy.egg-info/dependency_links.txt +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/symphonypy.egg-info/requires.txt +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/symphonypy.egg-info/top_level.txt +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/tests/test_preprocessing.py +0 -0
- {symphonypy-0.2.3 → symphonypy-0.2.4}/tests/test_tools.py +0 -0
|
@@ -17,6 +17,38 @@ from scanpy.tools._ingest import Ingest, _DimDict
|
|
|
17
17
|
logger = logging.getLogger("symphonypy")
|
|
18
18
|
|
|
19
19
|
|
|
20
|
+
def _harmony_sigma(ref_ho, harmony_kwargs, K):
|
|
21
|
+
"""Extract sigma from a harmony result, falling back to the input
|
|
22
|
+
parameter when the backend (cpp) does not expose it."""
|
|
23
|
+
sigma = getattr(ref_ho, "sigma", None)
|
|
24
|
+
if sigma is not None:
|
|
25
|
+
return np.asarray(sigma, dtype=np.float32).ravel()
|
|
26
|
+
s = harmony_kwargs.get("sigma", 0.1)
|
|
27
|
+
if np.isscalar(s):
|
|
28
|
+
return np.full(int(K), float(s), dtype=np.float32)
|
|
29
|
+
return np.asarray(s, dtype=np.float32).ravel()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _harmony_converged(ref_ho, harmony_kwargs):
|
|
33
|
+
"""Backend-agnostic convergence flag. Returns True/False, or None
|
|
34
|
+
if it cannot be determined."""
|
|
35
|
+
if hasattr(ref_ho, "check_convergence"):
|
|
36
|
+
try:
|
|
37
|
+
return bool(ref_ho.check_convergence(1))
|
|
38
|
+
except Exception:
|
|
39
|
+
pass
|
|
40
|
+
obj = list(getattr(ref_ho, "objective_harmony", []) or [])
|
|
41
|
+
if len(obj) < 2:
|
|
42
|
+
return None
|
|
43
|
+
# Replicate torch backend's i_type=1 criterion.
|
|
44
|
+
eps = float(harmony_kwargs.get("epsilon_harmony", 1e-2))
|
|
45
|
+
max_iter = int(harmony_kwargs.get("max_iter_harmony", 10))
|
|
46
|
+
rel = (obj[-2] - obj[-1]) / (abs(obj[-2]) + 1e-12)
|
|
47
|
+
converged_by_eps = rel < eps
|
|
48
|
+
# If the loop stopped before max_iter, by construction it converged.
|
|
49
|
+
return bool(converged_by_eps or (len(obj) - 1) < max_iter)
|
|
50
|
+
|
|
51
|
+
|
|
20
52
|
def _harmony_integrate_python(
|
|
21
53
|
adata: AnnData,
|
|
22
54
|
key: list[str] | str,
|
|
@@ -35,51 +67,42 @@ def _harmony_integrate_python(
|
|
|
35
67
|
**harmony_kwargs,
|
|
36
68
|
)
|
|
37
69
|
|
|
38
|
-
#
|
|
70
|
+
# Orientation: legacy harmonypy returned (d, N); both new backends
|
|
71
|
+
# return (N, d). The check disambiguates without relying on backend type.
|
|
39
72
|
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
73
|
Z_corr = ref_ho.Z_corr.T
|
|
44
74
|
R = ref_ho.R
|
|
45
75
|
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
76
|
if ref_ho.Z_corr.shape[0] == ref_ho.Z_corr.shape[1]:
|
|
50
77
|
logger.warning(
|
|
51
|
-
"
|
|
78
|
+
"Z_corr is square (%d x %d); orientation is ambiguous. "
|
|
79
|
+
"Pass force_transpose_output=True if results look wrong.",
|
|
80
|
+
ref_ho.Z_corr.shape[0], ref_ho.Z_corr.shape[1],
|
|
52
81
|
)
|
|
53
82
|
Z_corr = ref_ho.Z_corr
|
|
54
83
|
R = ref_ho.R.T
|
|
55
84
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
85
|
+
K = int(ref_ho.K)
|
|
86
|
+
converged = _harmony_converged(ref_ho, harmony_kwargs)
|
|
87
|
+
sigma = _harmony_sigma(ref_ho, harmony_kwargs, K)
|
|
59
88
|
|
|
60
|
-
|
|
61
|
-
C = R @ Z_corr
|
|
89
|
+
adata.obsm[ref_basis_adjusted] = Z_corr
|
|
90
|
+
C = R @ Z_corr # [K, d]
|
|
62
91
|
|
|
63
92
|
adata.uns["harmony"] = {
|
|
64
|
-
# [K] the number of cells softly belonging to each cluster
|
|
65
93
|
"Nr": R.sum(axis=1),
|
|
66
|
-
# ref cluster centroids
|
|
67
|
-
# [K, d]
|
|
68
94
|
"C": C,
|
|
69
|
-
|
|
70
|
-
"
|
|
71
|
-
# sigma [K] (cluster cross entropy regularization coef)
|
|
72
|
-
"sigma": ref_ho.sigma,
|
|
95
|
+
"K": K,
|
|
96
|
+
"sigma": sigma,
|
|
73
97
|
"ref_basis_loadings": ref_basis_loadings,
|
|
74
98
|
"ref_basis_adjusted": ref_basis_adjusted,
|
|
75
99
|
"vars_use": key,
|
|
76
100
|
"harmony_kwargs": harmony_kwargs,
|
|
77
101
|
"converged": converged,
|
|
78
|
-
# [K, Nref]
|
|
79
102
|
"R": R,
|
|
80
103
|
}
|
|
81
104
|
|
|
82
|
-
if
|
|
105
|
+
if converged is False:
|
|
83
106
|
logger.warning(
|
|
84
107
|
"Harmony didn't converge. "
|
|
85
108
|
"Consider increasing max_iter_harmony parameter value"
|
|
@@ -361,7 +384,7 @@ def _run_soft_kmeans(
|
|
|
361
384
|
# number of clusters
|
|
362
385
|
"K": K,
|
|
363
386
|
# sigma [K] (cluster cross enthropy regularization coef)
|
|
364
|
-
"sigma":
|
|
387
|
+
"sigma": np.full(int(K), float(sigma), dtype=np.float32) if np.isscalar(sigma) else np.asarray(sigma, dtype=np.float32).ravel(),
|
|
365
388
|
"ref_basis_loadings": ref_basis_loadings,
|
|
366
389
|
"ref_basis_adjusted": ref_basis,
|
|
367
390
|
"vars_use": None,
|
|
@@ -4,7 +4,9 @@ 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
|
|
@@ -158,15 +160,21 @@ def per_cluster_confidence(
|
|
|
158
160
|
reference_cluster_centroids, ord=2, axis=1, keepdims=True
|
|
159
161
|
)
|
|
160
162
|
grouped = adata_query.obs.groupby(cluster_key, observed=True)
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
163
|
+
|
|
164
|
+
def _apply(g):
|
|
165
|
+
return _cluster_maha_dist(
|
|
166
|
+
g, adata_query,
|
|
167
|
+
transferred_primary_basis=transferred_primary_basis,
|
|
168
|
+
reference_cluster_centroids=reference_cluster_centroids,
|
|
169
|
+
reference_cluster_centroids_norm=reference_cluster_centroids_norm,
|
|
170
|
+
u=u, lamb=lamb,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
try:
|
|
174
|
+
dists = grouped.apply(_apply, include_groups=False)
|
|
175
|
+
except TypeError:
|
|
176
|
+
# pandas < 2.2
|
|
177
|
+
dists = grouped.apply(_apply)
|
|
170
178
|
|
|
171
179
|
if uns is not None:
|
|
172
180
|
adata_query.uns[uns] = {
|
|
@@ -293,7 +301,7 @@ def map_embedding(
|
|
|
293
301
|
:type key: list[str] | str | None, optional
|
|
294
302
|
:param lamb: Entropy regularization parameter for soft k-means, defaults to None
|
|
295
303
|
:type lamb: float | np.array | None, optional
|
|
296
|
-
:param sigma:
|
|
304
|
+
: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
305
|
:type sigma: float | np.array, optional
|
|
298
306
|
: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
307
|
:type use_genes_column: str | None, optional
|
|
@@ -360,7 +368,15 @@ def map_embedding(
|
|
|
360
368
|
C = harmony_ref["C"]
|
|
361
369
|
Y = C / np.linalg.norm(C, ord=2, axis=1, keepdims=True)
|
|
362
370
|
|
|
363
|
-
|
|
371
|
+
K_eff = int(harmony_ref["K"])
|
|
372
|
+
ref_sigma = harmony_ref.get("sigma")
|
|
373
|
+
if ref_sigma is not None:
|
|
374
|
+
sigma_eff = np.asarray(ref_sigma, dtype=np.float64).ravel()
|
|
375
|
+
if sigma_eff.size == 1:
|
|
376
|
+
sigma_eff = np.repeat(sigma_eff, K_eff)
|
|
377
|
+
else:
|
|
378
|
+
sigma_eff = sigma
|
|
379
|
+
R = _assign_clusters(X, sigma_eff, Y, K_eff)
|
|
364
380
|
|
|
365
381
|
# 3. correct query embeddings
|
|
366
382
|
# likewise harmonypy
|
|
@@ -376,7 +392,9 @@ def map_embedding(
|
|
|
376
392
|
# [B + 1, N]
|
|
377
393
|
phi_ = np.concatenate([np.ones((1, phi.shape[1])), phi], axis=0)
|
|
378
394
|
|
|
379
|
-
phi_n =
|
|
395
|
+
phi_n = np.array(
|
|
396
|
+
[batch_data[col].nunique() for col in batch_data.columns], dtype=int
|
|
397
|
+
)
|
|
380
398
|
# lambda (ridge regularization coef)
|
|
381
399
|
if lamb is None:
|
|
382
400
|
lamb = np.repeat([1] * len(phi_n), phi_n)
|
|
@@ -439,7 +457,7 @@ def tsne(
|
|
|
439
457
|
adata: AnnData,
|
|
440
458
|
use_rep: str = "X_pca",
|
|
441
459
|
t_sne_slot: str = "X_tsne",
|
|
442
|
-
use_model:
|
|
460
|
+
use_model: TSNEEmbedding | str | None = None,
|
|
443
461
|
save_path: str | None = None,
|
|
444
462
|
use_raw: bool | None = None,
|
|
445
463
|
return_model: bool = False,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|