symphonypy 0.2.1__tar.gz → 0.2.3__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.
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: symphonypy
3
+ Version: 0.2.3
4
+ Summary: Porting of Symphony R package to Python
5
+ Home-page: https://github.com/potulabe/symphonypy
6
+ Author: Kseniya Petrova, Sergey Isaev
7
+ Author-email: praefrontalis@gmail.com, serj.hoop@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: harmonypy
15
+ Requires-Dist: scanpy
16
+ Requires-Dist: scikit-learn
17
+ Dynamic: license-file
18
+
19
+ <!-- omit in toc -->
20
+ # Symphonypy
21
+ [![pytest workflow](https://github.com/potulabe/symphonypy/actions/workflows/test.yaml/badge.svg)](https://github.com/potulabe/symphonypy/actions/workflows/test.yaml)
22
+
23
+ Porting of [Symphony R](https://github.com/immunogenomics/symphony) package to Python
24
+
25
+ - [Installation and usage](#installation-and-usage)
26
+ - [Benchmarking](#benchmarking)
27
+
28
+
29
+ ## Installation and usage
30
+ Please visit [Read the Docs](https://symphonypy.readthedocs.io/en/latest/index.html) documentation web page.
31
+
32
+ ## Benchmarking
33
+ - Harmony (R) vs Harmonypy benchmarking: [benchmarking/Benchmarking_harmony_PBMC_Satija.ipynb](benchmarking/Benchmarking_harmony_PBMC_Satija_CITEseq.ipynb)
34
+ - Symphony (R) vs Symphonypy benchmarking: [benchmarking/Benchmarking_symphony_PBMC.ipynb](benchmarking/Benchmarking_symphony_PBMC.ipynb)
@@ -0,0 +1,16 @@
1
+ <!-- omit in toc -->
2
+ # Symphonypy
3
+ [![pytest workflow](https://github.com/potulabe/symphonypy/actions/workflows/test.yaml/badge.svg)](https://github.com/potulabe/symphonypy/actions/workflows/test.yaml)
4
+
5
+ Porting of [Symphony R](https://github.com/immunogenomics/symphony) package to Python
6
+
7
+ - [Installation and usage](#installation-and-usage)
8
+ - [Benchmarking](#benchmarking)
9
+
10
+
11
+ ## Installation and usage
12
+ Please visit [Read the Docs](https://symphonypy.readthedocs.io/en/latest/index.html) documentation web page.
13
+
14
+ ## Benchmarking
15
+ - Harmony (R) vs Harmonypy benchmarking: [benchmarking/Benchmarking_harmony_PBMC_Satija.ipynb](benchmarking/Benchmarking_harmony_PBMC_Satija_CITEseq.ipynb)
16
+ - Symphony (R) vs Symphonypy benchmarking: [benchmarking/Benchmarking_symphony_PBMC.ipynb](benchmarking/Benchmarking_symphony_PBMC.ipynb)
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = symphonypy
3
- version = 0.2.1
3
+ version = 0.2.3
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
@@ -32,6 +32,6 @@ Symphony algorithm:
32
32
  5*. Count mapping confidence metrics
33
33
  """
34
34
 
35
- from . import preprocessing as pp
36
- from . import tools as tl
35
+ from . import pp
36
+ from . import tl
37
37
  from . import datasets
@@ -24,6 +24,7 @@ def _harmony_integrate_python(
24
24
  ref_basis_adjusted: str = "X_pca_harmony",
25
25
  ref_basis_loadings: str = "PCs",
26
26
  verbose: bool = False,
27
+ force_transpose_output: bool = False,
27
28
  **harmony_kwargs,
28
29
  ) -> None:
29
30
  ref_ho = run_harmony(
@@ -34,22 +35,40 @@ def _harmony_integrate_python(
34
35
  **harmony_kwargs,
35
36
  )
36
37
 
37
- adata.obsm[ref_basis_adjusted] = ref_ho.Z_corr.T
38
+ # compatibility with old harmonypy implementations:
39
+ 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
+ Z_corr = ref_ho.Z_corr.T
44
+ R = ref_ho.R
45
+ 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
+ if ref_ho.Z_corr.shape[0] == ref_ho.Z_corr.shape[1]:
50
+ 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."
52
+ )
53
+ Z_corr = ref_ho.Z_corr
54
+ R = ref_ho.R.T
55
+
56
+ adata.obsm[ref_basis_adjusted] = Z_corr
38
57
 
39
58
  converged = ref_ho.check_convergence(1)
40
59
 
41
- # [K, d] = [K, Nref] x [d, N_ref].T
42
- C = ref_ho.R @ ref_ho.Z_corr.T
60
+ # [K, d] = [K, Nref] x [N_ref, d]
61
+ C = R @ Z_corr
43
62
 
44
63
  adata.uns["harmony"] = {
45
64
  # [K] the number of cells softly belonging to each cluster
46
- "Nr": ref_ho.R.sum(axis=1),
65
+ "Nr": R.sum(axis=1),
47
66
  # ref cluster centroids
48
67
  # [K, d]
49
68
  "C": C,
50
69
  # number of clusters
51
70
  "K": ref_ho.K,
52
- # sigma [K] (cluster cross enthropy regularization coef)
71
+ # sigma [K] (cluster cross entropy regularization coef)
53
72
  "sigma": ref_ho.sigma,
54
73
  "ref_basis_loadings": ref_basis_loadings,
55
74
  "ref_basis_adjusted": ref_basis_adjusted,
@@ -57,7 +76,7 @@ def _harmony_integrate_python(
57
76
  "harmony_kwargs": harmony_kwargs,
58
77
  "converged": converged,
59
78
  # [K, Nref]
60
- "R": ref_ho.R,
79
+ "R": R,
61
80
  }
62
81
 
63
82
  if not converged:
@@ -140,6 +159,8 @@ def _harmony_integrate_R(
140
159
  "ref_basis_adjusted": ref_basis_adjusted,
141
160
  "converged": converged,
142
161
  "R": R,
162
+ "harmony_kwargs": harmony_kwargs,
163
+ "vars_use": key,
143
164
  }
144
165
  adata.obsm[ref_basis_adjusted] = Z_corr
145
166
 
@@ -238,7 +259,7 @@ def _adjust_for_missing_genes(
238
259
  t = np.zeros((adata.shape[0], use_genes_list.shape[0]))
239
260
 
240
261
  X = adata[:, use_genes_list[use_genes_list_present]].X
241
- t[:, use_genes_list_present] = X.A if issparse(X) else X.copy()
262
+ t[:, use_genes_list_present] = X.toarray() if issparse(X) else X.copy()
242
263
 
243
264
  return t
244
265
 
@@ -280,7 +301,7 @@ def _map_query_to_ref(
280
301
  )
281
302
  else:
282
303
  X = adata_query[:, use_genes_list].X
283
- t = X.A if issparse(X) else X.copy()
304
+ t = X.toarray() if issparse(X) else X.copy()
284
305
 
285
306
  means = (
286
307
  np.array(adata_ref.var["mean"][use_genes_list_present])
@@ -322,7 +343,7 @@ def _run_soft_kmeans(
322
343
  model.fit(adata_ref.obsm[ref_basis])
323
344
  C = model.cluster_centers_
324
345
 
325
- Z_cos = adata_ref.obsm[ref_basis]
346
+ Z_cos = adata_ref.obsm[ref_basis].copy()
326
347
  Z_cos /= Z_cos.max(axis=1, keepdims=True)
327
348
  Z_cos /= np.linalg.norm(Z_cos, ord=2, axis=1, keepdims=True)
328
349
 
@@ -22,24 +22,25 @@ def harmony_integrate(
22
22
  **harmony_kwargs,
23
23
  ):
24
24
  """
25
- Run Harmony batch correction on adata,
26
- save corrected output to adata.obsm,
27
- save all the necessary to Symphony mapping
28
- algorithm parameters to adata.uns
29
-
30
- Args:
31
- adata (AnnData): adata object with batch
32
- key (list[str] | str): which columns from adata.obs
33
- to use as batch keys (`vars_use` parameter of Harmony)
34
- flavor (str, optional): if to run harmonypy or Harmony via rpy2. Defaults to "python".
35
- ref_basis_source (str, optional): adata.obsm[ref_basis_source] will be used
36
- as input embedding to Harmony. Defaults to "X_pca".
37
- ref_basis_adjusted (str, optional): at adata.obsm[ref_basis_adjusted]
38
- corrected embedding will be saved. Defaults to "X_pca_harmony".
39
- ref_basis_loadings (str, optional): gene loadings of ref_basis_source. Defaults to "PCs".
40
- verbose (bool, optional): verbosity level of harmony. Defaults to False.
41
- random_seed (int, optional): random_seed for harmony. Defaults to 1.
25
+ Run Harmony batch correction on adata, save corrected output to ``adata.obsm``,
26
+ save all the necessary to Symphony mapping algorithm parameters to ``adata.uns``
42
27
 
28
+ :param adata: adata object with batch
29
+ :type adata: AnnData
30
+ :param key: which columns from ``adata.obs`` to use as batch keys (``vars_use`` parameter of Harmony)
31
+ :type key: list[str] | str
32
+ :param flavor: if to run harmonypy or Harmony via ``rpy2``, defaults to "python"
33
+ :type flavor: str, optional
34
+ :param ref_basis_source: ``adata.obsm[ref_basis_source]`` will be used as input embedding to Harmony, defaults to "X_pca"
35
+ :type ref_basis_source: str, optional
36
+ :param ref_basis_adjusted: slot where to put corrected coordinates, defaults to "X_pca_harmony"
37
+ :type ref_basis_adjusted: str, optional
38
+ :param ref_basis_loadings: slot with feature loadings to the original embedding, defaults to "PCs"
39
+ :type ref_basis_loadings: str, optional
40
+ :param verbose: if to print logs of steps of integration, defaults to False
41
+ :type verbose: bool, optional
42
+ :param random_seed: random seed, defaults to 1
43
+ :type random_seed: int, optional
43
44
  """
44
45
 
45
46
  if flavor == "python":
@@ -41,15 +41,20 @@ def per_cell_confidence(
41
41
  """
42
42
  Calculates the weighted Mahalanobis distance for query cells to reference clusters.
43
43
  Higher distance metric indicates less confidence.
44
- Saves the metric to `adata_query.obs[obs]`
45
-
46
- Args:
47
- adata_query (AnnData): query adata object mapped to `adata_ref` with Symphony
48
- adata_ref (AnnData): reference adata object (with Harmony object in adata_ref.uns)
49
- ref_basis_adjusted (str, optional): adata_ref.obsm[ref_basis_adjusted] should contain resulting (harmony integrated if batch was present) reference representation. Defaults to "X_pca_harmony".
50
- query_basis_adjusted (str, optional): adata_query.obsm[query_basis_adjusted] should contain symphony adjusted query representation. Defaults to "X_pca_harmony".
51
- transferred_primary_basis (str, optional): adata_query.obsm[transferred_primary_basis] should contain pre-Symphony reference PC query representation. Defaults to "X_pca_reference".
52
- obs (str, optional): at adata_query.obs[obs] confidence metric will be saved. Defaults to "symphony_confidence".
44
+ Saves the metric to ``adata_query.obs[obs]``
45
+
46
+ :param adata_query: query adata object mapped to ``adata_ref`` with Symphony
47
+ :type adata_query: AnnData
48
+ :param adata_ref: reference adata object (with Harmony object in ``adata_ref.uns``)
49
+ :type adata_ref: AnnData
50
+ :param ref_basis_adjusted: ``adata_ref.obsm[ref_basis_adjusted]`` should contain resulting (harmony integrated if batch was present) reference representation, defaults to "X_pca_harmony"
51
+ :type ref_basis_adjusted: str, optional
52
+ :param query_basis_adjusted: ``adata_query.obsm[query_basis_adjusted]`` should contain symphony adjusted query representation, defaults to "X_pca_harmony"
53
+ :type query_basis_adjusted: str, optional
54
+ :param transferred_primary_basis: ``adata_query.obsm[transferred_primary_basis]`` should contain pre-Symphony reference PC query representation, defaults to "X_pca_reference"
55
+ :type transferred_primary_basis: str, optional
56
+ :param obs: at ``adata_query.obs[obs]`` confidence metric will be saved, defaults to "symphony_per_cell_dist"
57
+ :type obs: str, optional
53
58
  """
54
59
 
55
60
  assert (
@@ -116,22 +121,28 @@ def per_cluster_confidence(
116
121
  obs: str | None = "symphony_per_cluster_dist",
117
122
  uns: str | None = "symphony_per_cluster_dist",
118
123
  ):
119
- """
120
- Calculates the Mahalanobis distance from user-defined query clusters to their nearest
124
+ """Calculates the Mahalanobis distance from user-defined query clusters to their nearest
121
125
  reference centroid after initial projection into reference PCA space.
122
126
  All query cells in a cluster get the same score. Higher distance indicates less confidence.
123
127
  Due to the instability of estimating covariance with small numbers of cells, we do not assign a
124
128
  score to clusters smaller than u * d, where d is the dimensionality of the embedding and u is specified.
125
129
 
126
- Args:
127
- adata_query (AnnData): query adata object mapped to `adata_ref` with Symphony
128
- adata_ref (AnnData): reference adata object (with Harmony object in adata_ref.uns)
129
- cluster_key (str, [str]): which keys from adata_query.obs to use as a cluster label (if list, adata_query will be grouped by them)
130
- u (float, optional): at least u * d cells are to be assigned to a cluster, where d is a dimensionality of representation. Defaults to 2.
131
- lamb (float, optional): ridge regression like coef for covariance matrix inversion numerical stability. Defaults to 0 (no ridge).
132
- transferred_primary_basis (str, optional): adata_query.obsm[transferred_primary_basis] should contain pre-Symphony reference PC query representation. Defaults to "X_pca_reference".
133
- obs (str | None, optional): If not None, resulted dists would be written to adata_query.obs[obs] for each cell (just the same value for each cluster)
134
- uns (str | None, optional): If not None, resulted dists would be written to adata_query.uns[uns] for each cluster
130
+ :param adata_query: query adata object mapped to ``adata_ref`` with Symphony
131
+ :type adata_query: AnnData
132
+ :param adata_ref: reference adata object (with Harmony object in ``adata_ref.uns``)
133
+ :type adata_ref: AnnData
134
+ :param cluster_key: which keys from ``adata_query.obs`` to use as a cluster label (if list, adata_query will be grouped by them)
135
+ :type cluster_key: str
136
+ :param u: at least u * d cells are to be assigned to a cluster, where d is a dimensionality of representation, defaults to 2
137
+ :type u: float, optional
138
+ :param lamb: ridge regression like coef for covariance matrix inversion numerical stability, defaults to 0
139
+ :type lamb: float, optional
140
+ :param transferred_primary_basis: ``adata_query.obsm[transferred_primary_basis]`` should contain pre-Symphony reference PC query representation, defaults to "X_pca_reference"
141
+ :type transferred_primary_basis: str, optional
142
+ :param obs: If not None, resulted dists would be written to ``adata_query.obs[obs]`` for each cell (just the same value for each cluster), defaults to "symphony_per_cluster_dist"
143
+ :type obs: str | None, optional
144
+ :param uns: If not None, resulted dists would be written to ``adata_query.uns[uns]`` for each cluster, defaults to "symphony_per_cluster_dist"
145
+ :type uns: str | None, optional
135
146
  """
136
147
  assert (
137
148
  "harmony" in adata_ref.uns
@@ -146,8 +157,8 @@ def per_cluster_confidence(
146
157
  reference_cluster_centroids_norm = reference_cluster_centroids / np.linalg.norm(
147
158
  reference_cluster_centroids, ord=2, axis=1, keepdims=True
148
159
  )
149
-
150
- dists = adata_query.obs.groupby(cluster_key).apply(
160
+ grouped = adata_query.obs.groupby(cluster_key, observed=True)
161
+ dists = grouped.apply(
151
162
  _cluster_maha_dist,
152
163
  adata_query,
153
164
  transferred_primary_basis=transferred_primary_basis,
@@ -158,10 +169,13 @@ def per_cluster_confidence(
158
169
  )
159
170
 
160
171
  if uns is not None:
161
- adata_query.uns[uns] = {"key": cluster_key, "dist": dists}
172
+ adata_query.uns[uns] = {
173
+ "key": cluster_key,
174
+ "dist": dists.to_numpy(),
175
+ "cluster_labels": dists.index.to_numpy(),
176
+ }
162
177
  if obs is not None:
163
- grouped = adata_query.obs.groupby(cluster_key)[cluster_key]
164
- adata_query.obs[obs] = grouped.transform(lambda x: dists[x[0]])
178
+ adata_query.obs[obs] = grouped[cluster_key].transform(lambda x: dists[x.name])
165
179
 
166
180
 
167
181
  def ingest(
@@ -176,24 +190,27 @@ def ingest(
176
190
  **kwargs,
177
191
  ):
178
192
  """
179
- copied from https://github.com/scverse/scanpy/blob/master/scanpy/tools/_ingest.py
193
+ Copied from https://github.com/scverse/scanpy/blob/master/scanpy/tools/_ingest.py
180
194
  with little change that var_names equality between adata and adata_new wouldn't be check if needless,
181
- and additional parameter `use_rep` is added.
182
-
183
- Args:
184
- adata_query (AnnData): target adata object.
185
- adata_ref (AnnData): source adata object.
186
- obs (Optional[Union[str, Iterable[str]]], optional): which columns from adata_red.obs to transfer. Defaults to None.
187
- embedding_method (Union[str, Iterable[str]], optional): which adata_ref's embeddings to transfer. Defaults to ('umap', 'pca').
188
- labeling_method (str, optional): which method to use for labeling transferring. Defaults to 'knn'.
189
- neighbors_key (Optional[str], optional): which key from adata_ref.uns to use as source of neighbors info. Defaults to None.
190
- inplace (bool, optional): if to write directly to adata_query or return an adjusted copy of adata_query. Defaults to True.
191
- use_rep (str, None): which adata_query's representation to use for embedding mappings. If None, it will be decided depending on circumstances. Defaults to None.
192
- kwargs: will be forwarded to the `sc.tl.Ingest.neighbors` function.
193
-
194
- Returns:
195
- if inplace is False returns a copy of adata_query with additional slots,
196
- otherwise adds to adata_query.
195
+ and additional parameter ``use_rep`` is added.
196
+
197
+ :param adata_query: target AnnData object
198
+ :type adata_query: AnnData
199
+ :param adata_ref: source AnnData object
200
+ :type adata_ref: AnnData
201
+ :param obs: which columns from ``adata_red.obs`` to transfer, defaults to None
202
+ :type obs: Optional[Union[str, Iterable[str]]], optional
203
+ :param embedding_method: which ``adata_ref``'s embeddings to transfer, defaults to "umap"
204
+ :type embedding_method: Union[str, Iterable[str]], optional
205
+ :param labeling_method: which method to use for labeling transferring, defaults to "knn"
206
+ :type labeling_method: str, optional
207
+ :param neighbors_key: which key from ``adata_ref.uns`` to use as source of neighbors info, defaults to None
208
+ :type neighbors_key: Optional[str], optional
209
+ :param inplace: if to write directly to ``adata_query`` or return an adjusted copy of ``adata_query``, defaults to True
210
+ :type inplace: bool, optional
211
+ :param use_rep: which ``adata_query``'s representation to use for embedding mappings. If None, it will be decided depending on circumstances, defaults to None
212
+ :type use_rep: str | None, optional
213
+ :return: if ``inplace=False`` returns a copy of ``adata_query`` with additional slots, otherwise adds to ``adata_query``.
197
214
  """
198
215
  anndata_version = pkg_version("anndata")
199
216
  if anndata_version < ANNDATA_MIN_VERSION:
@@ -242,7 +259,7 @@ def ingest(
242
259
  for i, col in enumerate(obs):
243
260
  ing.map_labels(col, labeling_method[i])
244
261
 
245
- logger.info(" finished", time=start)
262
+ logger.info("finished")
246
263
 
247
264
  if "rep" in ing._obsm:
248
265
  del ing._obsm["rep"]
@@ -263,37 +280,33 @@ def map_embedding(
263
280
  K: int | None = None,
264
281
  reference_primary_basis: str = "X_pca",
265
282
  ) -> None:
266
- """
267
- Actually runs Symphony algorithm for mapping adata_query to adata_ref.
268
- Will use Harmony object from adata_ref.uns if present,
283
+ """Actually runs Symphony algorithm for mapping ``adata_query`` to ``adata_ref``.
284
+ Will use Harmony object from ``adata_ref.uns`` if present,
269
285
  otherwise will firstly run k-means clusterization Harmony step
270
286
  without batch correction.
271
287
 
272
- Adds mapping of query cells to reference coords
273
- to adata_query.obsm[transferred_primary_basis] and
274
- symphony-corrected coords to adata_query.obsm[transferred_adjusted_basis],
275
- and query to the reference's clusters membership to adata_query.obsm[transferred_adjusted_basis + "_R"]
276
-
277
- Args:
278
- adata_query (AnnData): query adata object.
279
- adata_ref (AnnData): reference adata object
280
- (to account for batch effect in reference first run harmony_integrate).
281
- key (list[str] | str | None, optional): which of the columns
282
- from adata_query.obs to consider as batch keys. Defaults to None.
283
- lamb (float | np.array | None, optional): Entropy regularization parameter for soft k-means. Defaults to None.
284
- sigma (float | np.array, optional): Ridge regularization parameter for the linear model. Defaults to 0.1.
285
- use_genes_column (str | None, optional): adata_ref.var[use_genes_column] genes will
286
- be used to map query embeddings to reference. Defaults to "highly_variable".
287
- transferred_adjusted_basis (str, optional): in adata_query.obsm[transferred_adjusted_basis]
288
- symphony-adjusted coords will be saved. Defaults to "X_pca_harmony".
289
- transferred_primary_basis (str, optional): in adata_query.obsm[transferred_primary_basis]
290
- adata_query mapping to reference coords will be saved. Defaults to "X_pca_reference".
291
- ref_basis_loadings (str, optional): adata_ref.varm[ref_basis_loadings] will be used
292
- as gene loadings to map adata_query to adata_ref coords. Defaults to "PCs".
293
- K (int | None, optional): Number of clusters to use for k-means clustering.
294
- Only used if harmony integration was not performed on adata_ref. Defaults to None.
295
- reference_primary_basis (str): which reference embedding to use for k-means clustering.
296
- Only used if harmony integration was not performed on adata_ref. Defaults to "X_pca".
288
+ :param adata_query: query AnnData object
289
+ :type adata_query: AnnData
290
+ :param adata_ref: reference AnnData object (to account for batch effect in reference first run ``pp.harmony_integrate``).
291
+ :type adata_ref: AnnData
292
+ :param key: which of the columns from ``adata_query.obs`` to consider as batch keys, defaults to None
293
+ :type key: list[str] | str | None, optional
294
+ :param lamb: Entropy regularization parameter for soft k-means, defaults to None
295
+ :type lamb: float | np.array | None, optional
296
+ :param sigma: Ridge regularization parameter for the linear model, defaults to 0.1
297
+ :type sigma: float | np.array, optional
298
+ :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
+ :type use_genes_column: str | None, optional
300
+ :param transferred_adjusted_basis: in ``adata_query.obsm[transferred_adjusted_basis]`` symphony-adjusted coords will be saved, defaults to "X_pca_harmony"
301
+ :type transferred_adjusted_basis: str, optional
302
+ :param transferred_primary_basis: in ``adata_query.obsm[transferred_primary_basis]`` query mapping to reference coordinates will be saved, defaults to "X_pca_reference"
303
+ :type transferred_primary_basis: str, optional
304
+ :param ref_basis_loadings: ``adata_ref.varm[ref_basis_loadings]`` will be used as gene loadings to map ``adata_query`` to ``adata_ref`` coordinates, defaults to "PCs"
305
+ :type ref_basis_loadings: str, optional
306
+ :param K: Number of clusters to use for k-means clustering. Only used if harmony integration was not performed on ``adata_ref``, defaults to None
307
+ :type K: int | None, optional
308
+ :param reference_primary_basis: which reference embedding to use for k-means clustering. Only used if harmony integration was not performed on ``adata_ref``, defaults to "X_pca"
309
+ :type reference_primary_basis: str, optional
297
310
  """
298
311
  # Errors
299
312
  assert (
@@ -393,18 +406,20 @@ def transfer_labels_kNN(
393
406
  query_basis: str = "X_pca_harmony",
394
407
  **kNN_kwargs,
395
408
  ) -> None:
396
- """
397
- Run sklearn kNN classificator for label transferring.
398
- Args:
399
- adata_ref (AnnData): adata object to use for train.
400
- adata_query (AnnData): adata object to use for prediction.
401
- kNN_args: will be passed to kNN class init function.
402
- ref_labels (list[str] | str): either a list of column names or a str of one column name from `adata_ref.obs` to use as labels for model training.
403
- query_labels (list[str] | str | None): keys in `adata_query.obs` where to save transferred `ref_labels`.
404
- (in corresponding to ref_labels order). If not provided, `ref_labels` will be used.
405
- ref_basis (str): adata_ref.obsm[ref_basis] will be used as features for kNN training. Default: "X_pca_harmony".
406
- query_basis (str): adata_query.obsm[query_basis] will be used as features for prediction. Default: "X_pca_harmony".
407
- kNN_kwargs: will be passed to kNN class init function.
409
+ """Run sklearn kNN classifier for label transferring.
410
+
411
+ :param adata_query: AnnData object to use for train
412
+ :type adata_query: AnnData
413
+ :param adata_ref: AnnData object to use for prediction
414
+ :type adata_ref: AnnData
415
+ :param ref_labels: either a list of column names or a str of one column name from ``adata_ref.obs`` to use as labels for model training
416
+ :type ref_labels: list[str] | str
417
+ :param query_labels: keys in ``adata_query.obs`` where to save transferred ``ref_labels`` (in corresponding to ``ref_labels`` order). If not provided, ``ref_labels`` will be used
418
+ :type query_labels: list[str] | str | None, optional
419
+ :param ref_basis: ``adata_ref.obsm[ref_basis]`` will be used as features for kNN training, defaults to "X_pca_harmony"
420
+ :type ref_basis: str, optional
421
+ :param query_basis: ``adata_query.obsm[query_basis]`` will be used as features for prediction, defaults to "X_pca_harmony"
422
+ :type query_basis: str, optional
408
423
  """
409
424
  knn = KNeighborsClassifier(*kNN_args, **kNN_kwargs)
410
425
 
@@ -429,23 +444,24 @@ def tsne(
429
444
  use_raw: bool | None = None,
430
445
  return_model: bool = False,
431
446
  **kwargs,
432
- ) -> None | "openTSNE.TSNEEmbedding":
433
- """
434
- Run openTSNE dimension reduction on adata if use_model is None,
435
- or ingest adata.obsm[use_rep] to existing embedding, saved in use_model.
436
-
437
- Args:
438
- adata (Anndata): adata object
439
- use_rep (str): adata.obsm[use_rep] will be used as features for `openTSNE` model.
440
- t_sne_slot (str): to adata.obsm[t_sne_slot] embedding will be saved.
441
- use_model (`openTSNE.TSNEEmbedding`, str, None): `openTSNE` model object or path to pickle dumped model to use. Defaults to None.
442
- save_path (str, None): Filepath to save pickle of the `openTSNE` model. Defaults to None.
443
- use_raw (bool, None): If to use adata.raw.X as features for `openTSNE`. Defaults to None.
444
- return_model (bool): If to return `openTSNE` model. Defaults to False.
445
- kwargs: will be forwarded to the `openTSNE.TSNE` init function.
446
-
447
- Returns:
448
- if return_model is True, returns `openTSNE` model
447
+ ) -> None:
448
+ """Run openTSNE dimension reduction on adata if ``use_model`` is None,
449
+ or ingest ``adata.obsm[use_rep]`` to existing embedding, saved in ``use_model``.
450
+
451
+ :param adata: AnnData object
452
+ :type adata: AnnData
453
+ :param use_rep: ``adata.obsm[use_rep]`` will be used as features for openTSNE model, defaults to "X_pca"
454
+ :type use_rep: str, optional
455
+ :param t_sne_slot: to ``adata.obsm[t_sne_slot]`` embedding will be saved, defaults to "X_tsne"
456
+ :type t_sne_slot: str, optional
457
+ :param use_model: openTSNE model object or path to pickle dumped model to use, defaults to None
458
+ :type use_model: openTSNE.TSNEEmbedding | str | None, optional
459
+ :param save_path: Filepath to save pickle of the openTSNE model, defaults to None
460
+ :type save_path: str | None, optional
461
+ :param use_raw: If to use ``adata.raw.X`` as features for openTSNE, defaults to None
462
+ :type use_raw: bool | None, optional
463
+ :param return_model: If to return openTSNE model, defaults to False
464
+ :type return_model: bool, optional
449
465
  """
450
466
 
451
467
  import pickle
@@ -462,7 +478,6 @@ def tsne(
462
478
  logger.warning("The model that will be saved is a `PartialTSNEEmbedding`")
463
479
 
464
480
  if use_model is None:
465
-
466
481
  tsne_obj = TSNE(**kwargs)
467
482
 
468
483
  if use_rep != "X":
@@ -474,7 +489,6 @@ def tsne(
474
489
 
475
490
  adata.obsm[t_sne_slot] = np.array(model)
476
491
  else:
477
-
478
492
  if isinstance(use_model, str):
479
493
  with open(use_model, "rb") as model_file:
480
494
  model = pickle.load(model_file)
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: symphonypy
3
+ Version: 0.2.3
4
+ Summary: Porting of Symphony R package to Python
5
+ Home-page: https://github.com/potulabe/symphonypy
6
+ Author: Kseniya Petrova, Sergey Isaev
7
+ Author-email: praefrontalis@gmail.com, serj.hoop@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.8
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: harmonypy
15
+ Requires-Dist: scanpy
16
+ Requires-Dist: scikit-learn
17
+ Dynamic: license-file
18
+
19
+ <!-- omit in toc -->
20
+ # Symphonypy
21
+ [![pytest workflow](https://github.com/potulabe/symphonypy/actions/workflows/test.yaml/badge.svg)](https://github.com/potulabe/symphonypy/actions/workflows/test.yaml)
22
+
23
+ Porting of [Symphony R](https://github.com/immunogenomics/symphony) package to Python
24
+
25
+ - [Installation and usage](#installation-and-usage)
26
+ - [Benchmarking](#benchmarking)
27
+
28
+
29
+ ## Installation and usage
30
+ Please visit [Read the Docs](https://symphonypy.readthedocs.io/en/latest/index.html) documentation web page.
31
+
32
+ ## Benchmarking
33
+ - Harmony (R) vs Harmonypy benchmarking: [benchmarking/Benchmarking_harmony_PBMC_Satija.ipynb](benchmarking/Benchmarking_harmony_PBMC_Satija_CITEseq.ipynb)
34
+ - Symphony (R) vs Symphonypy benchmarking: [benchmarking/Benchmarking_symphony_PBMC.ipynb](benchmarking/Benchmarking_symphony_PBMC.ipynb)
@@ -5,10 +5,12 @@ setup.cfg
5
5
  symphonypy/__init__.py
6
6
  symphonypy/_utils.py
7
7
  symphonypy/datasets.py
8
- symphonypy/preprocessing.py
9
- symphonypy/tools.py
8
+ symphonypy/pp.py
9
+ symphonypy/tl.py
10
10
  symphonypy.egg-info/PKG-INFO
11
11
  symphonypy.egg-info/SOURCES.txt
12
12
  symphonypy.egg-info/dependency_links.txt
13
13
  symphonypy.egg-info/requires.txt
14
- symphonypy.egg-info/top_level.txt
14
+ symphonypy.egg-info/top_level.txt
15
+ tests/test_preprocessing.py
16
+ tests/test_tools.py
@@ -0,0 +1,34 @@
1
+ import scanpy as sc
2
+ import symphonypy as sp
3
+
4
+
5
+ class TestPreprocessing:
6
+ adata_fp = "tests/data/PBMC_Satija.query_subsample.h5ad"
7
+ batch_key = "orig.ident"
8
+
9
+ def assert_harmony_object(self, adata):
10
+ assert "X_pca_harmony" in adata.obsm
11
+ assert "harmony" in adata.uns
12
+ assert "Nr" in adata.uns["harmony"]
13
+ assert "C" in adata.uns["harmony"]
14
+ assert "K" in adata.uns["harmony"]
15
+ assert "sigma" in adata.uns["harmony"]
16
+ assert "ref_basis_loadings" in adata.uns["harmony"]
17
+ assert "ref_basis_adjusted" in adata.uns["harmony"]
18
+ assert "vars_use" in adata.uns["harmony"]
19
+ assert "harmony_kwargs" in adata.uns["harmony"]
20
+ assert "converged" in adata.uns["harmony"]
21
+ assert "R" in adata.uns["harmony"]
22
+
23
+ def test_harmony_integrate_python(self):
24
+ adata = sc.read_h5ad(self.adata_fp)
25
+ sp.pp.harmony_integrate(adata, key=self.batch_key, flavor="python")
26
+
27
+ self.assert_harmony_object(adata)
28
+
29
+
30
+ # def test_harmony_integrate_R(self):
31
+ # adata = sc.read_h5ad(self.adata_fp)
32
+ # sp.pp.harmony_integrate(adata, key=self.batch_key, flavor="R")
33
+
34
+ # self.assert_harmony_object(adata)
@@ -0,0 +1,54 @@
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()
symphonypy-0.2.1/PKG-INFO DELETED
@@ -1,104 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: symphonypy
3
- Version: 0.2.1
4
- Summary: Porting of Symphony R package to Python
5
- Home-page: https://github.com/potulabe/symphonypy
6
- Author: Kseniya Petrova, Sergey Isaev
7
- Author-email: praefrontalis@gmail.com, serj.hoop@gmail.com
8
- Classifier: Programming Language :: Python :: 3
9
- Classifier: License :: OSI Approved :: MIT License
10
- Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.8
12
- Description-Content-Type: text/markdown
13
- License-File: LICENSE
14
-
15
- <!-- omit in toc -->
16
- # Symphonypy
17
- Porting of [Symphony R](https://github.com/immunogenomics/symphony) package to Python
18
-
19
- - [Installation](#installation)
20
- - [Examples](#examples)
21
- - [Instructions](#instructions)
22
- - [Step 1: Reference building](#step-1-reference-building)
23
- - [Step 2: Query preprocessing and Symphony](#step-2-query-preprocessing-and-symphony)
24
- - [Step 3: Label transfer](#step-3-label-transfer)
25
- - [Step 4 (optional): Dimensionality reduction](#step-4-optional-dimensionality-reduction)
26
- - [Benchmarking](#benchmarking)
27
-
28
-
29
- ## Installation
30
- Symphonypy package might be installed via pip:
31
- ```
32
- pip install symphonypy
33
- ```
34
-
35
- ## Examples
36
- Here are Jupyter-notebooks with simple examples of how to use symphonypy
37
- - with [pre-built references](notebooks/Symphonypy_precomputed.ipynb) from original Symphony ([nbviewer](https://nbviewer.org/github/potulabe/symphonypy/blob/main/notebooks/Symphonypy_precomputed.ipynb)),
38
- - with [reference building](notebooks/Symphonypy_simple_tutorial.ipynb) from scratch ([nbviewer](https://nbviewer.org/github/potulabe/symphonypy/blob/main/notebooks/Symphonypy_simple_tutorial.ipynb)),
39
- - for [mapping to reference without harmony step](notebooks/Symphonypy_without_harmony_tutorial.ipynb) ([nbviewer](https://nbviewer.org/github/potulabe/symphonypy/blob/main/notebooks/Symphonypy_without_harmony_tutorial.ipynb)).
40
-
41
- ## Instructions
42
- ### Step 1: Reference building
43
- ```python
44
- import scanpy as sc
45
- import symphonypy as sp
46
-
47
- sc.pp.normalize_total(adata_ref, target_sum=1e5)
48
- sc.pp.log1p(adata_ref)
49
- sc.pp.highly_variable_genes(
50
- adata_ref,
51
- batch_key=batch_key_ref,
52
- n_top_genes=n_top_genes,
53
- )
54
- adata_ref.raw = adata_ref
55
- adata_ref = adata_ref[:, adata_ref.var.highly_variable]
56
- sc.pp.scale(adata_ref, max_value=10)
57
- sc.pp.pca(adata_ref, n_comps=30, zero_center=False)
58
-
59
- # You can skip Harmony if you have only one batch in reference
60
- sp.pp.harmony_integrate(adata_ref, key=batch_key_ref)
61
- # -> adata_ref.obsm["X_pca_harmony"] <- Harmony adjusted "X_pca"
62
- # -> adata_ref.uns["harmony"] <- Harmony object for Symphony
63
- ```
64
-
65
- ### Step 2: Query preprocessing and Symphony
66
- ```python
67
- # target_sum for normalize_total() should be the same as in reference
68
- sc.pp.normalize_total(adata_query, target_sum=1e5)
69
- sc.pp.log1p(adata_query)
70
-
71
- # Symphony
72
- sp.tl.map_embedding(adata_query, adata_ref, key=batch_key_query)
73
- # -> adata_query.obsm["X_pca_harmony"] <- Symphony adjusted query's PCA
74
- sp.tl.per_cell_confidence(adata_query, adata_ref)
75
- # -> adata_query.obs["symphony_per_cell_dist"] <- Symphony mapping score per cell
76
- sp.tl.per_cluster_confidence(adata_query, adata_ref, query_clusters)
77
- # -> adata_query.uns["symphony_per_cluster_dist"] <- Symphony mapping score per cluster
78
- ```
79
-
80
- ### Step 3: Label transfer
81
- ```python
82
- sp.tl.transfer_labels_kNN(adata_query, adata_ref, labels)
83
- # -> adata_query.obs[labels] <- transferred labels (via sklearn kNN)
84
- ```
85
-
86
- ### Step 4 (optional): Dimensionality reduction
87
- With UMAP:
88
- ```python
89
- sc.pp.neighbors(adata_ref, use_rep="X_pca_harmony")
90
- sc.tl.umap(adata_ref)
91
- sp.tl.ingest(adata_query, adata_ref)
92
- # -> adata_query.obsm["X_umap"] <- mapped to the reference's UMAP coords
93
- ```
94
-
95
- With t-SNE (`openTSNE` should be installed, `pip install openTSNE`):
96
- ```python
97
- tSNE_model = sp.tl.tsne(adata_ref, use_rep="X_pca_harmony", return_model=True)
98
- sp.tl.tsne(adata_query, use_rep="X_pca_harmony", use_model=tSNE_model)
99
- # -> adata_query.obsm["X_tsne"] <- mapped to the reference's tSNE coords
100
- ```
101
-
102
- ## Benchmarking
103
- - Harmony (R) vs harmonypy benchmarking: [benchmarking/Benchmarking_harmony_PBMC_Satija.ipynb](benchmarking/Benchmarking_harmony_PBMC_Satija_CITEseq.ipynb)
104
- - Symphony (R) vs symphonypy benchmarking: [benchmarking/Benchmarking_symphony_PBMC.ipynb](benchmarking/Benchmarking_symphony_PBMC.ipynb)
@@ -1,90 +0,0 @@
1
- <!-- omit in toc -->
2
- # Symphonypy
3
- Porting of [Symphony R](https://github.com/immunogenomics/symphony) package to Python
4
-
5
- - [Installation](#installation)
6
- - [Examples](#examples)
7
- - [Instructions](#instructions)
8
- - [Step 1: Reference building](#step-1-reference-building)
9
- - [Step 2: Query preprocessing and Symphony](#step-2-query-preprocessing-and-symphony)
10
- - [Step 3: Label transfer](#step-3-label-transfer)
11
- - [Step 4 (optional): Dimensionality reduction](#step-4-optional-dimensionality-reduction)
12
- - [Benchmarking](#benchmarking)
13
-
14
-
15
- ## Installation
16
- Symphonypy package might be installed via pip:
17
- ```
18
- pip install symphonypy
19
- ```
20
-
21
- ## Examples
22
- Here are Jupyter-notebooks with simple examples of how to use symphonypy
23
- - with [pre-built references](notebooks/Symphonypy_precomputed.ipynb) from original Symphony ([nbviewer](https://nbviewer.org/github/potulabe/symphonypy/blob/main/notebooks/Symphonypy_precomputed.ipynb)),
24
- - with [reference building](notebooks/Symphonypy_simple_tutorial.ipynb) from scratch ([nbviewer](https://nbviewer.org/github/potulabe/symphonypy/blob/main/notebooks/Symphonypy_simple_tutorial.ipynb)),
25
- - for [mapping to reference without harmony step](notebooks/Symphonypy_without_harmony_tutorial.ipynb) ([nbviewer](https://nbviewer.org/github/potulabe/symphonypy/blob/main/notebooks/Symphonypy_without_harmony_tutorial.ipynb)).
26
-
27
- ## Instructions
28
- ### Step 1: Reference building
29
- ```python
30
- import scanpy as sc
31
- import symphonypy as sp
32
-
33
- sc.pp.normalize_total(adata_ref, target_sum=1e5)
34
- sc.pp.log1p(adata_ref)
35
- sc.pp.highly_variable_genes(
36
- adata_ref,
37
- batch_key=batch_key_ref,
38
- n_top_genes=n_top_genes,
39
- )
40
- adata_ref.raw = adata_ref
41
- adata_ref = adata_ref[:, adata_ref.var.highly_variable]
42
- sc.pp.scale(adata_ref, max_value=10)
43
- sc.pp.pca(adata_ref, n_comps=30, zero_center=False)
44
-
45
- # You can skip Harmony if you have only one batch in reference
46
- sp.pp.harmony_integrate(adata_ref, key=batch_key_ref)
47
- # -> adata_ref.obsm["X_pca_harmony"] <- Harmony adjusted "X_pca"
48
- # -> adata_ref.uns["harmony"] <- Harmony object for Symphony
49
- ```
50
-
51
- ### Step 2: Query preprocessing and Symphony
52
- ```python
53
- # target_sum for normalize_total() should be the same as in reference
54
- sc.pp.normalize_total(adata_query, target_sum=1e5)
55
- sc.pp.log1p(adata_query)
56
-
57
- # Symphony
58
- sp.tl.map_embedding(adata_query, adata_ref, key=batch_key_query)
59
- # -> adata_query.obsm["X_pca_harmony"] <- Symphony adjusted query's PCA
60
- sp.tl.per_cell_confidence(adata_query, adata_ref)
61
- # -> adata_query.obs["symphony_per_cell_dist"] <- Symphony mapping score per cell
62
- sp.tl.per_cluster_confidence(adata_query, adata_ref, query_clusters)
63
- # -> adata_query.uns["symphony_per_cluster_dist"] <- Symphony mapping score per cluster
64
- ```
65
-
66
- ### Step 3: Label transfer
67
- ```python
68
- sp.tl.transfer_labels_kNN(adata_query, adata_ref, labels)
69
- # -> adata_query.obs[labels] <- transferred labels (via sklearn kNN)
70
- ```
71
-
72
- ### Step 4 (optional): Dimensionality reduction
73
- With UMAP:
74
- ```python
75
- sc.pp.neighbors(adata_ref, use_rep="X_pca_harmony")
76
- sc.tl.umap(adata_ref)
77
- sp.tl.ingest(adata_query, adata_ref)
78
- # -> adata_query.obsm["X_umap"] <- mapped to the reference's UMAP coords
79
- ```
80
-
81
- With t-SNE (`openTSNE` should be installed, `pip install openTSNE`):
82
- ```python
83
- tSNE_model = sp.tl.tsne(adata_ref, use_rep="X_pca_harmony", return_model=True)
84
- sp.tl.tsne(adata_query, use_rep="X_pca_harmony", use_model=tSNE_model)
85
- # -> adata_query.obsm["X_tsne"] <- mapped to the reference's tSNE coords
86
- ```
87
-
88
- ## Benchmarking
89
- - Harmony (R) vs harmonypy benchmarking: [benchmarking/Benchmarking_harmony_PBMC_Satija.ipynb](benchmarking/Benchmarking_harmony_PBMC_Satija_CITEseq.ipynb)
90
- - Symphony (R) vs symphonypy benchmarking: [benchmarking/Benchmarking_symphony_PBMC.ipynb](benchmarking/Benchmarking_symphony_PBMC.ipynb)
@@ -1,104 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: symphonypy
3
- Version: 0.2.1
4
- Summary: Porting of Symphony R package to Python
5
- Home-page: https://github.com/potulabe/symphonypy
6
- Author: Kseniya Petrova, Sergey Isaev
7
- Author-email: praefrontalis@gmail.com, serj.hoop@gmail.com
8
- Classifier: Programming Language :: Python :: 3
9
- Classifier: License :: OSI Approved :: MIT License
10
- Classifier: Operating System :: OS Independent
11
- Requires-Python: >=3.8
12
- Description-Content-Type: text/markdown
13
- License-File: LICENSE
14
-
15
- <!-- omit in toc -->
16
- # Symphonypy
17
- Porting of [Symphony R](https://github.com/immunogenomics/symphony) package to Python
18
-
19
- - [Installation](#installation)
20
- - [Examples](#examples)
21
- - [Instructions](#instructions)
22
- - [Step 1: Reference building](#step-1-reference-building)
23
- - [Step 2: Query preprocessing and Symphony](#step-2-query-preprocessing-and-symphony)
24
- - [Step 3: Label transfer](#step-3-label-transfer)
25
- - [Step 4 (optional): Dimensionality reduction](#step-4-optional-dimensionality-reduction)
26
- - [Benchmarking](#benchmarking)
27
-
28
-
29
- ## Installation
30
- Symphonypy package might be installed via pip:
31
- ```
32
- pip install symphonypy
33
- ```
34
-
35
- ## Examples
36
- Here are Jupyter-notebooks with simple examples of how to use symphonypy
37
- - with [pre-built references](notebooks/Symphonypy_precomputed.ipynb) from original Symphony ([nbviewer](https://nbviewer.org/github/potulabe/symphonypy/blob/main/notebooks/Symphonypy_precomputed.ipynb)),
38
- - with [reference building](notebooks/Symphonypy_simple_tutorial.ipynb) from scratch ([nbviewer](https://nbviewer.org/github/potulabe/symphonypy/blob/main/notebooks/Symphonypy_simple_tutorial.ipynb)),
39
- - for [mapping to reference without harmony step](notebooks/Symphonypy_without_harmony_tutorial.ipynb) ([nbviewer](https://nbviewer.org/github/potulabe/symphonypy/blob/main/notebooks/Symphonypy_without_harmony_tutorial.ipynb)).
40
-
41
- ## Instructions
42
- ### Step 1: Reference building
43
- ```python
44
- import scanpy as sc
45
- import symphonypy as sp
46
-
47
- sc.pp.normalize_total(adata_ref, target_sum=1e5)
48
- sc.pp.log1p(adata_ref)
49
- sc.pp.highly_variable_genes(
50
- adata_ref,
51
- batch_key=batch_key_ref,
52
- n_top_genes=n_top_genes,
53
- )
54
- adata_ref.raw = adata_ref
55
- adata_ref = adata_ref[:, adata_ref.var.highly_variable]
56
- sc.pp.scale(adata_ref, max_value=10)
57
- sc.pp.pca(adata_ref, n_comps=30, zero_center=False)
58
-
59
- # You can skip Harmony if you have only one batch in reference
60
- sp.pp.harmony_integrate(adata_ref, key=batch_key_ref)
61
- # -> adata_ref.obsm["X_pca_harmony"] <- Harmony adjusted "X_pca"
62
- # -> adata_ref.uns["harmony"] <- Harmony object for Symphony
63
- ```
64
-
65
- ### Step 2: Query preprocessing and Symphony
66
- ```python
67
- # target_sum for normalize_total() should be the same as in reference
68
- sc.pp.normalize_total(adata_query, target_sum=1e5)
69
- sc.pp.log1p(adata_query)
70
-
71
- # Symphony
72
- sp.tl.map_embedding(adata_query, adata_ref, key=batch_key_query)
73
- # -> adata_query.obsm["X_pca_harmony"] <- Symphony adjusted query's PCA
74
- sp.tl.per_cell_confidence(adata_query, adata_ref)
75
- # -> adata_query.obs["symphony_per_cell_dist"] <- Symphony mapping score per cell
76
- sp.tl.per_cluster_confidence(adata_query, adata_ref, query_clusters)
77
- # -> adata_query.uns["symphony_per_cluster_dist"] <- Symphony mapping score per cluster
78
- ```
79
-
80
- ### Step 3: Label transfer
81
- ```python
82
- sp.tl.transfer_labels_kNN(adata_query, adata_ref, labels)
83
- # -> adata_query.obs[labels] <- transferred labels (via sklearn kNN)
84
- ```
85
-
86
- ### Step 4 (optional): Dimensionality reduction
87
- With UMAP:
88
- ```python
89
- sc.pp.neighbors(adata_ref, use_rep="X_pca_harmony")
90
- sc.tl.umap(adata_ref)
91
- sp.tl.ingest(adata_query, adata_ref)
92
- # -> adata_query.obsm["X_umap"] <- mapped to the reference's UMAP coords
93
- ```
94
-
95
- With t-SNE (`openTSNE` should be installed, `pip install openTSNE`):
96
- ```python
97
- tSNE_model = sp.tl.tsne(adata_ref, use_rep="X_pca_harmony", return_model=True)
98
- sp.tl.tsne(adata_query, use_rep="X_pca_harmony", use_model=tSNE_model)
99
- # -> adata_query.obsm["X_tsne"] <- mapped to the reference's tSNE coords
100
- ```
101
-
102
- ## Benchmarking
103
- - Harmony (R) vs harmonypy benchmarking: [benchmarking/Benchmarking_harmony_PBMC_Satija.ipynb](benchmarking/Benchmarking_harmony_PBMC_Satija_CITEseq.ipynb)
104
- - Symphony (R) vs symphonypy benchmarking: [benchmarking/Benchmarking_symphony_PBMC.ipynb](benchmarking/Benchmarking_symphony_PBMC.ipynb)
File without changes
File without changes