symphonypy 0.2.2__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.2/symphonypy.egg-info → symphonypy-0.2.4}/PKG-INFO +1 -1
- {symphonypy-0.2.2 → symphonypy-0.2.4}/setup.cfg +1 -1
- {symphonypy-0.2.2 → symphonypy-0.2.4}/symphonypy/_utils.py +59 -17
- {symphonypy-0.2.2 → symphonypy-0.2.4}/symphonypy/tl.py +34 -18
- {symphonypy-0.2.2 → symphonypy-0.2.4/symphonypy.egg-info}/PKG-INFO +1 -1
- {symphonypy-0.2.2 → symphonypy-0.2.4}/LICENSE +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/README.md +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/pyproject.toml +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/symphonypy/__init__.py +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/symphonypy/datasets.py +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/symphonypy/pp.py +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/symphonypy.egg-info/SOURCES.txt +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/symphonypy.egg-info/dependency_links.txt +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/symphonypy.egg-info/requires.txt +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/symphonypy.egg-info/top_level.txt +0 -0
- {symphonypy-0.2.2 → symphonypy-0.2.4}/tests/test_preprocessing.py +0 -0
- {symphonypy-0.2.2 → 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,
|
|
@@ -24,6 +56,7 @@ def _harmony_integrate_python(
|
|
|
24
56
|
ref_basis_adjusted: str = "X_pca_harmony",
|
|
25
57
|
ref_basis_loadings: str = "PCs",
|
|
26
58
|
verbose: bool = False,
|
|
59
|
+
force_transpose_output: bool = False,
|
|
27
60
|
**harmony_kwargs,
|
|
28
61
|
) -> None:
|
|
29
62
|
ref_ho = run_harmony(
|
|
@@ -34,33 +67,42 @@ def _harmony_integrate_python(
|
|
|
34
67
|
**harmony_kwargs,
|
|
35
68
|
)
|
|
36
69
|
|
|
37
|
-
|
|
70
|
+
# Orientation: legacy harmonypy returned (d, N); both new backends
|
|
71
|
+
# return (N, d). The check disambiguates without relying on backend type.
|
|
72
|
+
if ref_ho.Z_corr.shape[0] != adata.shape[0] or force_transpose_output:
|
|
73
|
+
Z_corr = ref_ho.Z_corr.T
|
|
74
|
+
R = ref_ho.R
|
|
75
|
+
else:
|
|
76
|
+
if ref_ho.Z_corr.shape[0] == ref_ho.Z_corr.shape[1]:
|
|
77
|
+
logger.warning(
|
|
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],
|
|
81
|
+
)
|
|
82
|
+
Z_corr = ref_ho.Z_corr
|
|
83
|
+
R = ref_ho.R.T
|
|
38
84
|
|
|
39
|
-
|
|
85
|
+
K = int(ref_ho.K)
|
|
86
|
+
converged = _harmony_converged(ref_ho, harmony_kwargs)
|
|
87
|
+
sigma = _harmony_sigma(ref_ho, harmony_kwargs, K)
|
|
40
88
|
|
|
41
|
-
|
|
42
|
-
C =
|
|
89
|
+
adata.obsm[ref_basis_adjusted] = Z_corr
|
|
90
|
+
C = R @ Z_corr # [K, d]
|
|
43
91
|
|
|
44
92
|
adata.uns["harmony"] = {
|
|
45
|
-
|
|
46
|
-
"Nr": ref_ho.R.sum(axis=1),
|
|
47
|
-
# ref cluster centroids
|
|
48
|
-
# [K, d]
|
|
93
|
+
"Nr": R.sum(axis=1),
|
|
49
94
|
"C": C,
|
|
50
|
-
|
|
51
|
-
"
|
|
52
|
-
# sigma [K] (cluster cross enthropy regularization coef)
|
|
53
|
-
"sigma": ref_ho.sigma,
|
|
95
|
+
"K": K,
|
|
96
|
+
"sigma": sigma,
|
|
54
97
|
"ref_basis_loadings": ref_basis_loadings,
|
|
55
98
|
"ref_basis_adjusted": ref_basis_adjusted,
|
|
56
99
|
"vars_use": key,
|
|
57
100
|
"harmony_kwargs": harmony_kwargs,
|
|
58
101
|
"converged": converged,
|
|
59
|
-
|
|
60
|
-
"R": ref_ho.R,
|
|
102
|
+
"R": R,
|
|
61
103
|
}
|
|
62
104
|
|
|
63
|
-
if
|
|
105
|
+
if converged is False:
|
|
64
106
|
logger.warning(
|
|
65
107
|
"Harmony didn't converge. "
|
|
66
108
|
"Consider increasing max_iter_harmony parameter value"
|
|
@@ -141,7 +183,7 @@ def _harmony_integrate_R(
|
|
|
141
183
|
"converged": converged,
|
|
142
184
|
"R": R,
|
|
143
185
|
"harmony_kwargs": harmony_kwargs,
|
|
144
|
-
"vars_use": key
|
|
186
|
+
"vars_use": key,
|
|
145
187
|
}
|
|
146
188
|
adata.obsm[ref_basis_adjusted] = Z_corr
|
|
147
189
|
|
|
@@ -342,7 +384,7 @@ def _run_soft_kmeans(
|
|
|
342
384
|
# number of clusters
|
|
343
385
|
"K": K,
|
|
344
386
|
# sigma [K] (cluster cross enthropy regularization coef)
|
|
345
|
-
"sigma":
|
|
387
|
+
"sigma": np.full(int(K), float(sigma), dtype=np.float32) if np.isscalar(sigma) else np.asarray(sigma, dtype=np.float32).ravel(),
|
|
346
388
|
"ref_basis_loadings": ref_basis_loadings,
|
|
347
389
|
"ref_basis_adjusted": ref_basis,
|
|
348
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
|
|
@@ -157,16 +159,22 @@ def per_cluster_confidence(
|
|
|
157
159
|
reference_cluster_centroids_norm = reference_cluster_centroids / np.linalg.norm(
|
|
158
160
|
reference_cluster_centroids, ord=2, axis=1, keepdims=True
|
|
159
161
|
)
|
|
162
|
+
grouped = adata_query.obs.groupby(cluster_key, observed=True)
|
|
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
|
+
)
|
|
160
172
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
reference_cluster_centroids_norm=reference_cluster_centroids_norm,
|
|
167
|
-
u=u,
|
|
168
|
-
lamb=lamb,
|
|
169
|
-
)
|
|
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] = {
|
|
@@ -175,8 +183,7 @@ def per_cluster_confidence(
|
|
|
175
183
|
"cluster_labels": dists.index.to_numpy(),
|
|
176
184
|
}
|
|
177
185
|
if obs is not None:
|
|
178
|
-
|
|
179
|
-
adata_query.obs[obs] = grouped.transform(lambda x: dists[x[0]])
|
|
186
|
+
adata_query.obs[obs] = grouped[cluster_key].transform(lambda x: dists[x.name])
|
|
180
187
|
|
|
181
188
|
|
|
182
189
|
def ingest(
|
|
@@ -260,7 +267,7 @@ def ingest(
|
|
|
260
267
|
for i, col in enumerate(obs):
|
|
261
268
|
ing.map_labels(col, labeling_method[i])
|
|
262
269
|
|
|
263
|
-
logger.info("
|
|
270
|
+
logger.info("finished")
|
|
264
271
|
|
|
265
272
|
if "rep" in ing._obsm:
|
|
266
273
|
del ing._obsm["rep"]
|
|
@@ -294,7 +301,7 @@ def map_embedding(
|
|
|
294
301
|
:type key: list[str] | str | None, optional
|
|
295
302
|
:param lamb: Entropy regularization parameter for soft k-means, defaults to None
|
|
296
303
|
:type lamb: float | np.array | None, optional
|
|
297
|
-
: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.
|
|
298
305
|
:type sigma: float | np.array, optional
|
|
299
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"
|
|
300
307
|
:type use_genes_column: str | None, optional
|
|
@@ -361,7 +368,15 @@ def map_embedding(
|
|
|
361
368
|
C = harmony_ref["C"]
|
|
362
369
|
Y = C / np.linalg.norm(C, ord=2, axis=1, keepdims=True)
|
|
363
370
|
|
|
364
|
-
|
|
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)
|
|
365
380
|
|
|
366
381
|
# 3. correct query embeddings
|
|
367
382
|
# likewise harmonypy
|
|
@@ -377,7 +392,9 @@ def map_embedding(
|
|
|
377
392
|
# [B + 1, N]
|
|
378
393
|
phi_ = np.concatenate([np.ones((1, phi.shape[1])), phi], axis=0)
|
|
379
394
|
|
|
380
|
-
phi_n =
|
|
395
|
+
phi_n = np.array(
|
|
396
|
+
[batch_data[col].nunique() for col in batch_data.columns], dtype=int
|
|
397
|
+
)
|
|
381
398
|
# lambda (ridge regularization coef)
|
|
382
399
|
if lamb is None:
|
|
383
400
|
lamb = np.repeat([1] * len(phi_n), phi_n)
|
|
@@ -440,7 +457,7 @@ def tsne(
|
|
|
440
457
|
adata: AnnData,
|
|
441
458
|
use_rep: str = "X_pca",
|
|
442
459
|
t_sne_slot: str = "X_tsne",
|
|
443
|
-
use_model:
|
|
460
|
+
use_model: TSNEEmbedding | str | None = None,
|
|
444
461
|
save_path: str | None = None,
|
|
445
462
|
use_raw: bool | None = None,
|
|
446
463
|
return_model: bool = False,
|
|
@@ -465,7 +482,6 @@ def tsne(
|
|
|
465
482
|
:type return_model: bool, optional
|
|
466
483
|
"""
|
|
467
484
|
|
|
468
|
-
|
|
469
485
|
import pickle
|
|
470
486
|
|
|
471
487
|
try:
|
|
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
|