scVAEIT 1.0.1__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.
- scVAEIT-1.0.1/LICENSE +21 -0
- scVAEIT-1.0.1/MANIFEST.in +4 -0
- scVAEIT-1.0.1/PKG-INFO +119 -0
- scVAEIT-1.0.1/README.md +97 -0
- scVAEIT-1.0.1/pyproject.toml +29 -0
- scVAEIT-1.0.1/scVAEIT/VAEIT.py +393 -0
- scVAEIT-1.0.1/scVAEIT/__init__.py +13 -0
- scVAEIT-1.0.1/scVAEIT/model.py +393 -0
- scVAEIT-1.0.1/scVAEIT/nn_utils.py +400 -0
- scVAEIT-1.0.1/scVAEIT/train.py +204 -0
- scVAEIT-1.0.1/scVAEIT/utils.py +152 -0
- scVAEIT-1.0.1/scVAEIT.egg-info/PKG-INFO +119 -0
- scVAEIT-1.0.1/scVAEIT.egg-info/SOURCES.txt +16 -0
- scVAEIT-1.0.1/scVAEIT.egg-info/dependency_links.txt +1 -0
- scVAEIT-1.0.1/scVAEIT.egg-info/requires.txt +8 -0
- scVAEIT-1.0.1/scVAEIT.egg-info/top_level.txt +2 -0
- scVAEIT-1.0.1/setup.cfg +4 -0
- scVAEIT-1.0.1/setup.py +33 -0
scVAEIT-1.0.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Du Jinhong
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
scVAEIT-1.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: scVAEIT
|
|
3
|
+
Version: 1.0.1
|
|
4
|
+
Summary: scVAEIT is a Python module of Variational autoencoder for single-cell mosaic integration and transfer learning.
|
|
5
|
+
Home-page: https://github.com/jaydu1/scVAEIT
|
|
6
|
+
Project-URL: Bug Tracker, https://github.com/jaydu1/scVAEIT/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/jaydu1/scVAEIT/releases
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Requires-Dist: scikit-learn
|
|
15
|
+
Requires-Dist: matplotlib
|
|
16
|
+
Requires-Dist: pandas
|
|
17
|
+
Requires-Dist: jupyter
|
|
18
|
+
Requires-Dist: numpy
|
|
19
|
+
Requires-Dist: tensorflow<2.16,>=2.12
|
|
20
|
+
Requires-Dist: tensorflow-probability<0.24,>=0.12
|
|
21
|
+
Requires-Dist: scanpy>=1.9.2
|
|
22
|
+
|
|
23
|
+
[](https://pypi.org/project/scVAEIT)
|
|
24
|
+
[](https://pepy.tech/project/scVAEIT)
|
|
25
|
+
|
|
26
|
+
# Variational autoencoder for multimodal mosaic integration and transfer learning
|
|
27
|
+
|
|
28
|
+
This repository contains implementations of *scVAEIT* for integration and imputation of multi-modal datasets.
|
|
29
|
+
*scVAEIT* (Variational autoencoder for multimodal single-cell mosaic integration and transfer learning) was originally proposed by [[Du22]](#references) for single-cell genomics data.
|
|
30
|
+
*scVAEIT* is a deep generative model based on a variational autoencoder (VAE) with masking strategies, which can integrate and impute multi-modal single-cell data, such as single-cell DOGMA-seq, CITE-seq, and ASAP-seq data.
|
|
31
|
+
*scVAEIT* has also been extended to impute single-cell proteomic data in [[Moon24]](#references), though it is also applicable to other types of data.
|
|
32
|
+
*scVAEIT* is implemented in Python, and an R wrapper is also available.
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
Check out the example folder for illustrations of how to use *scVAEIT*:
|
|
37
|
+
|
|
38
|
+
Example | Language | Notebooks
|
|
39
|
+
---|---|---
|
|
40
|
+
Imputation of ADT |  | [`imputation_1modality.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/imputation_1modality.ipynb)
|
|
41
|
+
Imputation of RNA and ADT |  | [`imputation_2modalities.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/imputation_2modalities.ipynb)
|
|
42
|
+
Integration of RNA, ADT, and peaks |  | [`integration_3modalities.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/integration_3modalities.ipynb)
|
|
43
|
+
Imputation of RNA |  | [`imputation_scRNAseq.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/VAEIT in R/imputation_scRNAseq.ipynb)
|
|
44
|
+
Imputation of peptides |  | [`imputation_peptide.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/VAEIT in R/imputation_peptide.ipynb)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
## Reproducibility Materials
|
|
48
|
+
The code for reproducing results in the paper [[Du22]](#references) can be found in the folder `Reproducibility materials`.
|
|
49
|
+
The large preprocessed dataset that contains DOGMA-seq, CITE-seq, and ASAP-seq data from GSE156478 can be accessed through [Google Drive](https://drive.google.com/drive/folders/19bzIGKex9Cwoy3ZWXra6D2hvqDtZOvfB?usp=drive_link).
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
## Dependencies
|
|
55
|
+
|
|
56
|
+
The package can be installed via PyPI:
|
|
57
|
+
|
|
58
|
+
```cmd
|
|
59
|
+
pip install scVAEIT
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Alternatively, the dependencies can be installed via the following commands:
|
|
63
|
+
|
|
64
|
+
```cmd
|
|
65
|
+
mamba create --name tf python=3.9 -y
|
|
66
|
+
conda activate tf
|
|
67
|
+
mamba install -c conda-forge "tensorflow>=2.12, <2.16" "tensorflow-probability>=0.12, <0.24" pandas jupyter -y
|
|
68
|
+
mamba install -c conda-forge "scanpy>=1.9.2" matplotlib scikit-learn -y
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
If you are using `conda`, simply replace `mamba` above with `conda`.
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# Prameters
|
|
78
|
+
## Network parameters
|
|
79
|
+
|
|
80
|
+
In the example, basically, the network is operated in two levels of blocks:
|
|
81
|
+
- The feature levels: the number of genes $n_g$, the number of adts $n_a$, the number of peaks $n_p$. The related parameters are `dim_input_arr` and `uni_block_names` (meaning that they have the same length).
|
|
82
|
+
- The subconnection level: the number of genes, the number of ADTs, the number of peaks in chrom 1 $n_p^1$, the number of peaks in chrom 2 $n_p^2$, etc. The related parameters include `dist_block`, `dim_block_embed`, `dim_block_enc`, `dim_block_dec`, and `block_names`.
|
|
83
|
+
|
|
84
|
+
We explain the parameters as below:
|
|
85
|
+
|
|
86
|
+
- `dim_input_arr` represents the size of input features. In the example, it is simply $[n_g, n_a, n_p]$.
|
|
87
|
+
|
|
88
|
+
- `dim_block` represents the number of subconnected features in all modalities (assuming that the features have been rearranged accordingly). In the example, it is $[n_g, n_a, n_p^1, n_p^2, \ldots]$.
|
|
89
|
+
|
|
90
|
+
- `dist_block`: There are four distributions implemented: 'NB', 'ZINB', 'Bernoulli', 'Gaussian' for negative binomial, zero-inflated negative binomial, Bernoulli, and Gaussian, respectively. However, only 'NB' and 'Bernoulli' were tested and used to generate the results for the paper. 'Bernoulli' is used for ATAC-seq data, and 'NB' is used for genes and proteins.
|
|
91
|
+
|
|
92
|
+
- `dim_block_embed` represents the embedding dimension of the binary mask. For example, `dim_block_embed = [1, 2, 3, ...]` means the mask will be embedded into a continuous vector of dimension 1 for block 1, and so on.
|
|
93
|
+
|
|
94
|
+
- `dim_block_enc` represents the structure of the first latent layer of the encoder. Using skip-connection helps reduce memory and computation complexity.
|
|
95
|
+
In the example, `dim_block_enc = np.array([256, 128] + [16 for _ in chunk_atac])` means that the genes will be embedded into a vector of dimension 256, the adts will be embedded into a vector of dimension 128, and so on.
|
|
96
|
+
For block `i`, we have a sub-network that takes both the features of size `dim_input_arr[i]` and the mask embedding of size `dim_block_embed[i]` and outputs a vector of size `dim_block_enc[i]`.
|
|
97
|
+
After that, the embedding vectors in all blocks will be concatenated into a vector as the input to the encoder.
|
|
98
|
+
|
|
99
|
+
- Similarly, `dim_block_dec` represents the structure of the last latent layer of the decoder. For block `i`, we have a sub-network that takes latent features of size `dim_block_dec[i]` and outputs a vector (the predicted features) of size `dim_input_arr[i]`.
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
- `dimensions` and `dim_latent` specify the network structure in the middle. For example, `dimensions = [256, 128]` and `dim_latent = 32` mean that we have a network $n_{in}-256-128-32-128-256-n_{out}$ where $n_{in}$ is the sum of `dim_block_enc`, and $n_{out}$ is the sum of `dim_block_dec`.
|
|
103
|
+
|
|
104
|
+
## Hyperparameters
|
|
105
|
+
Some of the important hyperparameters are:
|
|
106
|
+
- `beta_unobs` represents that weight for unobserved features.
|
|
107
|
+
- `p_feat` represents the probability of masking for the individual features. The larger value of `p_feat` encourages imputation ability but also requires more training epochs to have a good performance. But the influence of it is not large when training for enough epochs, so we recommend fixing fix `p_feat` as any reasonable value, e.g. 0.2.
|
|
108
|
+
- `p_modal` represents the probability of masking out one modality. You can just leave it as a uniform.
|
|
109
|
+
|
|
110
|
+
In our experiments, the results were not sensitive to the above parameters. So you can just use reasonable values as in the example, except the following parameter requires some care depending on your data:
|
|
111
|
+
|
|
112
|
+
- `beta_modal` represents the importance of each modality. You run the model on your dataset for a few epochs and pick `beta_modal` such that the likelihoods (which will be printed during training) of all modalities are roughly in the same order. Notably, the number of peaks is generally very large, so its likelihood will have a higher value. And that is why you can see it has a small weight 0.01, in the example where `beta_modal = [0.14,0.85,0.01]`.
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
# References
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
- [Du22] Du, J. H., Cai, Z., & Roeder, K. (2022). Robust probabilistic modeling for single-cell multimodal mosaic integration and imputation via scVAEIT. Proceedings of the National Academy of Sciences, 119(49), e2214414119.
|
|
119
|
+
- [Moon24] Moon, H., Du, J. H., Lei, J., & Roeder, K. (2024). Augmented Doubly Robust Post-Imputation Inference for Proteomic data. bioRxiv, 2024-03.
|
scVAEIT-1.0.1/README.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
[](https://pypi.org/project/scVAEIT)
|
|
2
|
+
[](https://pepy.tech/project/scVAEIT)
|
|
3
|
+
|
|
4
|
+
# Variational autoencoder for multimodal mosaic integration and transfer learning
|
|
5
|
+
|
|
6
|
+
This repository contains implementations of *scVAEIT* for integration and imputation of multi-modal datasets.
|
|
7
|
+
*scVAEIT* (Variational autoencoder for multimodal single-cell mosaic integration and transfer learning) was originally proposed by [[Du22]](#references) for single-cell genomics data.
|
|
8
|
+
*scVAEIT* is a deep generative model based on a variational autoencoder (VAE) with masking strategies, which can integrate and impute multi-modal single-cell data, such as single-cell DOGMA-seq, CITE-seq, and ASAP-seq data.
|
|
9
|
+
*scVAEIT* has also been extended to impute single-cell proteomic data in [[Moon24]](#references), though it is also applicable to other types of data.
|
|
10
|
+
*scVAEIT* is implemented in Python, and an R wrapper is also available.
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
Check out the example folder for illustrations of how to use *scVAEIT*:
|
|
15
|
+
|
|
16
|
+
Example | Language | Notebooks
|
|
17
|
+
---|---|---
|
|
18
|
+
Imputation of ADT |  | [`imputation_1modality.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/imputation_1modality.ipynb)
|
|
19
|
+
Imputation of RNA and ADT |  | [`imputation_2modalities.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/imputation_2modalities.ipynb)
|
|
20
|
+
Integration of RNA, ADT, and peaks |  | [`integration_3modalities.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/integration_3modalities.ipynb)
|
|
21
|
+
Imputation of RNA |  | [`imputation_scRNAseq.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/VAEIT in R/imputation_scRNAseq.ipynb)
|
|
22
|
+
Imputation of peptides |  | [`imputation_peptide.ipynb`](https://github.com/jaydu1/scVAEIT/blob/main/example/VAEIT in R/imputation_peptide.ipynb)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
## Reproducibility Materials
|
|
26
|
+
The code for reproducing results in the paper [[Du22]](#references) can be found in the folder `Reproducibility materials`.
|
|
27
|
+
The large preprocessed dataset that contains DOGMA-seq, CITE-seq, and ASAP-seq data from GSE156478 can be accessed through [Google Drive](https://drive.google.com/drive/folders/19bzIGKex9Cwoy3ZWXra6D2hvqDtZOvfB?usp=drive_link).
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
## Dependencies
|
|
33
|
+
|
|
34
|
+
The package can be installed via PyPI:
|
|
35
|
+
|
|
36
|
+
```cmd
|
|
37
|
+
pip install scVAEIT
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Alternatively, the dependencies can be installed via the following commands:
|
|
41
|
+
|
|
42
|
+
```cmd
|
|
43
|
+
mamba create --name tf python=3.9 -y
|
|
44
|
+
conda activate tf
|
|
45
|
+
mamba install -c conda-forge "tensorflow>=2.12, <2.16" "tensorflow-probability>=0.12, <0.24" pandas jupyter -y
|
|
46
|
+
mamba install -c conda-forge "scanpy>=1.9.2" matplotlib scikit-learn -y
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
If you are using `conda`, simply replace `mamba` above with `conda`.
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# Prameters
|
|
56
|
+
## Network parameters
|
|
57
|
+
|
|
58
|
+
In the example, basically, the network is operated in two levels of blocks:
|
|
59
|
+
- The feature levels: the number of genes $n_g$, the number of adts $n_a$, the number of peaks $n_p$. The related parameters are `dim_input_arr` and `uni_block_names` (meaning that they have the same length).
|
|
60
|
+
- The subconnection level: the number of genes, the number of ADTs, the number of peaks in chrom 1 $n_p^1$, the number of peaks in chrom 2 $n_p^2$, etc. The related parameters include `dist_block`, `dim_block_embed`, `dim_block_enc`, `dim_block_dec`, and `block_names`.
|
|
61
|
+
|
|
62
|
+
We explain the parameters as below:
|
|
63
|
+
|
|
64
|
+
- `dim_input_arr` represents the size of input features. In the example, it is simply $[n_g, n_a, n_p]$.
|
|
65
|
+
|
|
66
|
+
- `dim_block` represents the number of subconnected features in all modalities (assuming that the features have been rearranged accordingly). In the example, it is $[n_g, n_a, n_p^1, n_p^2, \ldots]$.
|
|
67
|
+
|
|
68
|
+
- `dist_block`: There are four distributions implemented: 'NB', 'ZINB', 'Bernoulli', 'Gaussian' for negative binomial, zero-inflated negative binomial, Bernoulli, and Gaussian, respectively. However, only 'NB' and 'Bernoulli' were tested and used to generate the results for the paper. 'Bernoulli' is used for ATAC-seq data, and 'NB' is used for genes and proteins.
|
|
69
|
+
|
|
70
|
+
- `dim_block_embed` represents the embedding dimension of the binary mask. For example, `dim_block_embed = [1, 2, 3, ...]` means the mask will be embedded into a continuous vector of dimension 1 for block 1, and so on.
|
|
71
|
+
|
|
72
|
+
- `dim_block_enc` represents the structure of the first latent layer of the encoder. Using skip-connection helps reduce memory and computation complexity.
|
|
73
|
+
In the example, `dim_block_enc = np.array([256, 128] + [16 for _ in chunk_atac])` means that the genes will be embedded into a vector of dimension 256, the adts will be embedded into a vector of dimension 128, and so on.
|
|
74
|
+
For block `i`, we have a sub-network that takes both the features of size `dim_input_arr[i]` and the mask embedding of size `dim_block_embed[i]` and outputs a vector of size `dim_block_enc[i]`.
|
|
75
|
+
After that, the embedding vectors in all blocks will be concatenated into a vector as the input to the encoder.
|
|
76
|
+
|
|
77
|
+
- Similarly, `dim_block_dec` represents the structure of the last latent layer of the decoder. For block `i`, we have a sub-network that takes latent features of size `dim_block_dec[i]` and outputs a vector (the predicted features) of size `dim_input_arr[i]`.
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
- `dimensions` and `dim_latent` specify the network structure in the middle. For example, `dimensions = [256, 128]` and `dim_latent = 32` mean that we have a network $n_{in}-256-128-32-128-256-n_{out}$ where $n_{in}$ is the sum of `dim_block_enc`, and $n_{out}$ is the sum of `dim_block_dec`.
|
|
81
|
+
|
|
82
|
+
## Hyperparameters
|
|
83
|
+
Some of the important hyperparameters are:
|
|
84
|
+
- `beta_unobs` represents that weight for unobserved features.
|
|
85
|
+
- `p_feat` represents the probability of masking for the individual features. The larger value of `p_feat` encourages imputation ability but also requires more training epochs to have a good performance. But the influence of it is not large when training for enough epochs, so we recommend fixing fix `p_feat` as any reasonable value, e.g. 0.2.
|
|
86
|
+
- `p_modal` represents the probability of masking out one modality. You can just leave it as a uniform.
|
|
87
|
+
|
|
88
|
+
In our experiments, the results were not sensitive to the above parameters. So you can just use reasonable values as in the example, except the following parameter requires some care depending on your data:
|
|
89
|
+
|
|
90
|
+
- `beta_modal` represents the importance of each modality. You run the model on your dataset for a few epochs and pick `beta_modal` such that the likelihoods (which will be printed during training) of all modalities are roughly in the same order. Notably, the number of peaks is generally very large, so its likelihood will have a higher value. And that is why you can see it has a small weight 0.01, in the example where `beta_modal = [0.14,0.85,0.01]`.
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# References
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
- [Du22] Du, J. H., Cai, Z., & Roeder, K. (2022). Robust probabilistic modeling for single-cell multimodal mosaic integration and imputation via scVAEIT. Proceedings of the National Academy of Sciences, 119(49), e2214414119.
|
|
97
|
+
- [Moon24] Moon, H., Du, J. H., Lei, J., & Roeder, K. (2024). Augmented Doubly Robust Post-Imputation Inference for Proteomic data. bioRxiv, 2024-03.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "scVAEIT"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "scVAEIT is a Python module of Variational autoencoder for single-cell mosaic integration and transfer learning."
|
|
5
|
+
|
|
6
|
+
dependencies = [
|
|
7
|
+
"scikit-learn",
|
|
8
|
+
"matplotlib",
|
|
9
|
+
"pandas",
|
|
10
|
+
"jupyter",
|
|
11
|
+
"numpy",
|
|
12
|
+
"tensorflow >= 2.12, < 2.16",
|
|
13
|
+
"tensorflow-probability >= 0.12, < 0.24",
|
|
14
|
+
"scanpy >= 1.9.2",
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[build-system]
|
|
18
|
+
requires = ["setuptools==68.2.2;python_version>='3'", "setuptools_scm[toml]>8"]
|
|
19
|
+
build-backend = "setuptools.build_meta"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
[tool.setuptools]
|
|
23
|
+
include-package-data = true
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.packages.find]
|
|
26
|
+
exclude = ["example*", "Reproducibility*"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.dynamic]
|
|
29
|
+
version = {attr = "scVAEIT.__version__"}
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
from typing import Optional, Union
|
|
3
|
+
from types import SimpleNamespace
|
|
4
|
+
|
|
5
|
+
import tensorflow as tf
|
|
6
|
+
|
|
7
|
+
import scVAEIT.model as model
|
|
8
|
+
import scVAEIT.train as train
|
|
9
|
+
from scVAEIT.utils import check_arr_type
|
|
10
|
+
|
|
11
|
+
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
|
12
|
+
from sklearn.preprocessing import OrdinalEncoder
|
|
13
|
+
|
|
14
|
+
from sklearn.model_selection import train_test_split
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
import scanpy as sc
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class VAEIT():
|
|
22
|
+
"""
|
|
23
|
+
Variational Inference for integration and transfer learning.
|
|
24
|
+
"""
|
|
25
|
+
def __init__(self, config: SimpleNamespace, data, masks, id_dataset=None, batches_cate=None, batches_cont=None, conditions=None
|
|
26
|
+
):
|
|
27
|
+
'''
|
|
28
|
+
Initialize the VAEIT model with the provided configuration and data.
|
|
29
|
+
|
|
30
|
+
Parameters
|
|
31
|
+
----------
|
|
32
|
+
config : SimpleNamespace
|
|
33
|
+
Configuration object containing model parameters.
|
|
34
|
+
data : np.array
|
|
35
|
+
The cell-by-feature matrix representing the input data.
|
|
36
|
+
masks : np.array
|
|
37
|
+
Masks indicating missingness, where 1 represents missing and 0 represents observed.
|
|
38
|
+
This can be a full mask matrix with the same shape as `data`, or a condensed matrix indexed by `id_dataset`.
|
|
39
|
+
id_dataset : np.array, optional
|
|
40
|
+
Integer IDs for each cell in the dataset. Required if `masks` is a condensed matrix.
|
|
41
|
+
batches_cate : np.array, optional
|
|
42
|
+
Categorical batch information for each cell.
|
|
43
|
+
batches_cont : np.array, optional
|
|
44
|
+
Continuous batch information for each cell.
|
|
45
|
+
conditions : np.array, optional
|
|
46
|
+
Conditions for each cell, used for calculating MMD loss if `config.gamma` is not 0.
|
|
47
|
+
|
|
48
|
+
Returns
|
|
49
|
+
-------
|
|
50
|
+
None
|
|
51
|
+
'''
|
|
52
|
+
self.dict_method_scname = {
|
|
53
|
+
'PCA' : 'X_pca',
|
|
54
|
+
'UMAP' : 'X_umap',
|
|
55
|
+
'TSNE' : 'X_tsne',
|
|
56
|
+
'diffmap' : 'X_diffmap',
|
|
57
|
+
'draw_graph' : 'X_draw_graph_fa'
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
self.data = tf.convert_to_tensor(data, dtype=tf.keras.backend.floatx())
|
|
61
|
+
|
|
62
|
+
# prprocessing config
|
|
63
|
+
if 'dim_input_arr' not in config or config['dim_input_arr'] is None:
|
|
64
|
+
config['dim_input_arr'] = data.shape[1]
|
|
65
|
+
if np.isscalar(config['dim_input_arr']):
|
|
66
|
+
config['dim_input_arr'] = np.array([config['dim_input_arr']], dtype=np.int32)
|
|
67
|
+
n_modal = len(config['dim_input_arr'])
|
|
68
|
+
n_block = len(config['dim_block']) if 'dim_block' in config and config['dim_block'] is not None else n_modal
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
config = dict(filter(lambda item: item[1] is not None, config.items()))
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
config = {**{
|
|
75
|
+
'beta_kl':2., # weight for beta-VAE
|
|
76
|
+
'beta_reverse':0., # weight for reverse prediction (use masked out features to predict the observed features)
|
|
77
|
+
'beta_modal':np.ones(n_modal, dtype=np.float32), # weight for each modality
|
|
78
|
+
'p_modal':None,
|
|
79
|
+
|
|
80
|
+
'uni_block_names':np.char.add(np.repeat('M-', n_modal), np.arange(n_modal).astype(str)),
|
|
81
|
+
'block_names':np.char.add(np.repeat('M-', n_block), np.arange(n_block).astype(str)),
|
|
82
|
+
'dist_block':np.repeat('NB', n_block),
|
|
83
|
+
'dim_block':np.array(config['dim_input_arr'], dtype=np.int32),
|
|
84
|
+
'dim_block_enc':np.zeros(n_block, dtype=np.int32),
|
|
85
|
+
'dim_block_dec':np.zeros(n_block, dtype=np.int32),
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
'skip_conn':False, # whether to use skip connection in decoder
|
|
89
|
+
'max_vals':None,
|
|
90
|
+
|
|
91
|
+
'gamma':0.
|
|
92
|
+
}, **config}
|
|
93
|
+
|
|
94
|
+
if isinstance(config, dict):
|
|
95
|
+
config = SimpleNamespace(**config)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
config.dimensions = check_arr_type(config.dimensions, np.int32)
|
|
99
|
+
config.dist_block = check_arr_type(config.dist_block, str)
|
|
100
|
+
|
|
101
|
+
if np.isscalar(config.dim_block_embed):
|
|
102
|
+
config.dim_block_embed = np.full(n_block, config.dim_block_embed, dtype=np.int32)
|
|
103
|
+
config.dim_block_enc = check_arr_type(config.dim_block_enc, np.int32)
|
|
104
|
+
config.dim_block_dec = check_arr_type(config.dim_block_dec, np.int32)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# preprocess batch
|
|
108
|
+
self.batches = np.array([], dtype=np.float32).reshape((data.shape[0],0))
|
|
109
|
+
if batches_cate is not None:
|
|
110
|
+
batches_cate = np.array(batches_cate)
|
|
111
|
+
self.cat_enc = OneHotEncoder(drop='first').fit(batches_cate)
|
|
112
|
+
self.batches = self.cat_enc.transform(batches_cate).toarray()
|
|
113
|
+
if batches_cont is not None:
|
|
114
|
+
self.cont_enc = StandardScaler()
|
|
115
|
+
batches_cont = self.cont_enc.fit_transform(batches_cont)
|
|
116
|
+
batches_cont = np.nan_to_num(batches_cont)
|
|
117
|
+
batches_cont = np.array(batches_cont, dtype=np.float32)
|
|
118
|
+
self.batches = np.c_[self.batches, batches_cont]
|
|
119
|
+
self.batches = tf.convert_to_tensor(self.batches, dtype=tf.keras.backend.floatx())
|
|
120
|
+
|
|
121
|
+
if conditions is not None and config.gamma != 0.:
|
|
122
|
+
## observations with np.nan will not participant in calculating mmd_loss
|
|
123
|
+
conditions = np.array(conditions)
|
|
124
|
+
if len(conditions.shape)<2:
|
|
125
|
+
conditions = conditions[:,None]
|
|
126
|
+
self.conditions = OrdinalEncoder(dtype=int, encoded_missing_value=-1).fit_transform(conditions) + int(1)
|
|
127
|
+
|
|
128
|
+
else:
|
|
129
|
+
config.gamma = 0.
|
|
130
|
+
self.conditions = np.zeros((data.shape[0],1), dtype=np.int32)
|
|
131
|
+
self.conditions = tf.cast(self.conditions, tf.int32)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# [num_cells, num_features]
|
|
136
|
+
self.masks = tf.convert_to_tensor(masks, dtype=tf.keras.backend.floatx())
|
|
137
|
+
|
|
138
|
+
if self.masks.shape==self.data.shape:
|
|
139
|
+
self.id_dataset = self.masks
|
|
140
|
+
self.full_masks = True
|
|
141
|
+
else:
|
|
142
|
+
self.id_dataset = tf.convert_to_tensor(id_dataset, dtype=tf.int32)
|
|
143
|
+
self.full_masks = False
|
|
144
|
+
|
|
145
|
+
if config.max_vals is None:
|
|
146
|
+
segment_ids = np.repeat(np.arange(n_block), config.dim_block)
|
|
147
|
+
config.max_vals = np.zeros(segment_ids.max()+1)
|
|
148
|
+
np.maximum.at(config.max_vals, segment_ids, np.max(data,axis=0))
|
|
149
|
+
for i, dist in enumerate(config.dist_block):
|
|
150
|
+
if dist != 'NB':
|
|
151
|
+
config.max_vals[i] = tf.constant(float('nan'))
|
|
152
|
+
elif np.isscalar(config.max_vals):
|
|
153
|
+
config.max_vals = tf.constant(config.max_vals, shape=n_block, dtype=tf.keras.backend.floatx())
|
|
154
|
+
config.max_vals = tf.convert_to_tensor(config.max_vals, dtype=tf.keras.backend.floatx())
|
|
155
|
+
|
|
156
|
+
self.batch_size_inference = 512
|
|
157
|
+
self.config = config
|
|
158
|
+
self.reset()
|
|
159
|
+
print(self.config, self.masks.shape, self.data.shape, self.batches.shape, flush = True)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def reset(self):
|
|
163
|
+
train.clear_session()
|
|
164
|
+
if hasattr(self, 'vae'):
|
|
165
|
+
del self.vae
|
|
166
|
+
import gc
|
|
167
|
+
gc.collect()
|
|
168
|
+
self.vae = model.VariationalAutoEncoder(self.config, self.masks)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def train(self, valid = False, stratify = False, test_size = 0.1, random_state: int = 0,
|
|
172
|
+
learning_rate: float = 1e-3, batch_size: Optional[int] = None, batch_size_inference: Optional[int] = None,
|
|
173
|
+
L: int = 1, num_epoch: int = 200, num_step_per_epoch: Optional[int] = None, save_every_epoch: Optional[int] = 25, init_epoch: Optional[int] = 1,
|
|
174
|
+
early_stopping_patience: int = 10, early_stopping_tolerance: float = 1e-4,
|
|
175
|
+
early_stopping_relative: bool = True, verbose: bool = False,
|
|
176
|
+
checkpoint_dir: Optional[str] = None, delete_existing: Optional[str] = True, eval_func = None):
|
|
177
|
+
'''
|
|
178
|
+
Train the VAEIT model with the specified parameters.
|
|
179
|
+
|
|
180
|
+
Parameters
|
|
181
|
+
----------
|
|
182
|
+
valid : bool, optional
|
|
183
|
+
Whether to use a validation set during training. Default is False.
|
|
184
|
+
stratify : bool, optional
|
|
185
|
+
Whether to stratify the split when creating the validation set. Default is False.
|
|
186
|
+
test_size : float or int, optional
|
|
187
|
+
The proportion or size of the validation set. Default is 0.1.
|
|
188
|
+
random_state : int, optional
|
|
189
|
+
The random state for data splitting. Default is 0.
|
|
190
|
+
learning_rate : float, optional
|
|
191
|
+
The initial learning rate for the Adam optimizer. Default is 1e-3.
|
|
192
|
+
batch_size : int, optional
|
|
193
|
+
The batch size for training. Default is 256 when using full mask matrices, or 64 otherwise.
|
|
194
|
+
batch_size_inference : int, optional
|
|
195
|
+
The batch size for inference. Default is 256 when using full mask matrices, or 64 otherwise.
|
|
196
|
+
L : int, optional
|
|
197
|
+
The number of Monte Carlo samples. Default is 1.
|
|
198
|
+
num_epoch : int, optional
|
|
199
|
+
The maximum number of epochs. Default is 200.
|
|
200
|
+
num_step_per_epoch : int, optional
|
|
201
|
+
The number of steps per epoch. If None, it will be inferred from the number of cells and batch size. Default is None.
|
|
202
|
+
save_every_epoch : int, optional
|
|
203
|
+
Frequency (in epochs) to save model checkpoints. Default is 25.
|
|
204
|
+
init_epoch : int, optional
|
|
205
|
+
The initial epoch number. Default is 1.
|
|
206
|
+
early_stopping_patience : int, optional
|
|
207
|
+
The number of epochs to wait for improvement before early stopping. Default is 10.
|
|
208
|
+
early_stopping_tolerance : float, optional
|
|
209
|
+
The minimum change in loss to be considered as an improvement. Default is 1e-4.
|
|
210
|
+
early_stopping_relative : bool, optional
|
|
211
|
+
Whether to monitor the relative change in loss for early stopping. Default is True.
|
|
212
|
+
verbose : bool, optional
|
|
213
|
+
Whether to print the training process. Default is False.
|
|
214
|
+
checkpoint_dir : str, optional
|
|
215
|
+
Directory to save model checkpoints. Default is None.
|
|
216
|
+
delete_existing : bool, optional
|
|
217
|
+
Whether to delete existing checkpoints in the directory. Default is True.
|
|
218
|
+
eval_func : function, optional
|
|
219
|
+
A function to evaluate the model, which takes the VAE as an input. Default is None.
|
|
220
|
+
|
|
221
|
+
Returns
|
|
222
|
+
-------
|
|
223
|
+
hist : dict
|
|
224
|
+
A dictionary containing the history of training and validation losses.
|
|
225
|
+
'''
|
|
226
|
+
|
|
227
|
+
if batch_size is None:
|
|
228
|
+
batch_size = 256 if self.full_masks else 64
|
|
229
|
+
batch_size = np.minimum(batch_size, self.data.shape[0])
|
|
230
|
+
if batch_size_inference is None:
|
|
231
|
+
batch_size_inference = batch_size
|
|
232
|
+
|
|
233
|
+
if valid:
|
|
234
|
+
if stratify is False:
|
|
235
|
+
stratify = None
|
|
236
|
+
|
|
237
|
+
id_train, id_valid = train_test_split(
|
|
238
|
+
np.arange(self.data.shape[0]),
|
|
239
|
+
test_size=test_size,
|
|
240
|
+
stratify=stratify,
|
|
241
|
+
random_state=random_state)
|
|
242
|
+
|
|
243
|
+
self.dataset_train = tf.data.Dataset.from_tensor_slices((
|
|
244
|
+
self.data[id_train], self.batches[id_train], self.id_dataset[id_train], self.conditions[id_train]
|
|
245
|
+
)).shuffle(buffer_size = len(id_train), seed=0,
|
|
246
|
+
reshuffle_each_iteration=True).batch(batch_size, drop_remainder=True).prefetch(tf.data.experimental.AUTOTUNE)
|
|
247
|
+
|
|
248
|
+
self.dataset_valid = tf.data.Dataset.from_tensor_slices((
|
|
249
|
+
self.data[id_valid], self.batches[id_valid], self.id_dataset[id_valid], self.conditions[id_valid]
|
|
250
|
+
)).batch(batch_size_inference).prefetch(tf.data.experimental.AUTOTUNE)
|
|
251
|
+
else:
|
|
252
|
+
id_train = np.arange(self.data.shape[0])
|
|
253
|
+
self.dataset_train = tf.data.Dataset.from_tensor_slices((
|
|
254
|
+
self.data, self.batches, self.id_dataset, self.conditions
|
|
255
|
+
)).shuffle(buffer_size = len(id_train), seed=0,
|
|
256
|
+
reshuffle_each_iteration=True).batch(batch_size, drop_remainder=True).prefetch(tf.data.experimental.AUTOTUNE)
|
|
257
|
+
self.dataset_valid = None
|
|
258
|
+
|
|
259
|
+
if num_step_per_epoch is None:
|
|
260
|
+
num_step_per_epoch = len(id_train)//batch_size
|
|
261
|
+
|
|
262
|
+
if checkpoint_dir is not None:
|
|
263
|
+
if init_epoch==1 and delete_existing and tf.io.gfile.exists(checkpoint_dir):
|
|
264
|
+
print("Deleting old log directory at {}".format(checkpoint_dir))
|
|
265
|
+
tf.io.gfile.rmtree(checkpoint_dir)
|
|
266
|
+
tf.io.gfile.makedirs(checkpoint_dir)
|
|
267
|
+
|
|
268
|
+
self.vae, hist = train.train(
|
|
269
|
+
self.dataset_train,
|
|
270
|
+
self.dataset_valid,
|
|
271
|
+
self.vae,
|
|
272
|
+
checkpoint_dir,
|
|
273
|
+
learning_rate,
|
|
274
|
+
int(L),
|
|
275
|
+
int(num_epoch),
|
|
276
|
+
int(num_step_per_epoch),
|
|
277
|
+
int(save_every_epoch),
|
|
278
|
+
init_epoch,
|
|
279
|
+
early_stopping_patience,
|
|
280
|
+
early_stopping_tolerance,
|
|
281
|
+
early_stopping_relative,
|
|
282
|
+
self.full_masks,
|
|
283
|
+
verbose,
|
|
284
|
+
eval_func
|
|
285
|
+
)
|
|
286
|
+
return hist
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def save_model(self, path_to_weights):
|
|
290
|
+
checkpoint = tf.train.Checkpoint(net=self.vae)
|
|
291
|
+
manager = tf.train.CheckpointManager(
|
|
292
|
+
checkpoint, path_to_weights, max_to_keep=None
|
|
293
|
+
)
|
|
294
|
+
save_path = manager.save()
|
|
295
|
+
print("Saved checkpoint: {}".format(save_path), flush = True)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def load_model(self, path_to_weights):
|
|
299
|
+
checkpoint = tf.train.Checkpoint(net=self.vae)
|
|
300
|
+
status = checkpoint.restore(path_to_weights)
|
|
301
|
+
print("Loaded checkpoint: {}".format(status), flush = True)
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def set_dataset(self, batch_size_inference=512):
|
|
305
|
+
if not hasattr(self, 'dataset_full') or batch_size_inference != self.batch_size_inference:
|
|
306
|
+
id_samples = np.arange(self.data.shape[0])
|
|
307
|
+
self.dataset_full = tf.data.Dataset.from_tensor_slices((
|
|
308
|
+
self.data, self.batches, self.id_dataset, tf.constant(id_samples)
|
|
309
|
+
)).shuffle(
|
|
310
|
+
buffer_size = len(id_samples), seed=0,
|
|
311
|
+
reshuffle_each_iteration=True
|
|
312
|
+
).batch(batch_size_inference).prefetch(tf.data.experimental.AUTOTUNE)
|
|
313
|
+
self.batch_size_inference = batch_size_inference
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def get_latent_z(self, masks=None, zero_out=True, batch_size_inference=512):
|
|
317
|
+
''' get the posterier mean of current latent space z (encoder output)
|
|
318
|
+
|
|
319
|
+
Returns
|
|
320
|
+
----------
|
|
321
|
+
z : np.array
|
|
322
|
+
\([N,d]\) The latent means.
|
|
323
|
+
'''
|
|
324
|
+
self.set_dataset(batch_size_inference)
|
|
325
|
+
return self.vae.get_z(self.dataset_full, self.full_masks, masks, zero_out)
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def get_denoised_data(self, masks=None, zero_out=True, batch_size_inference=256, return_mean=True, L=50):
|
|
329
|
+
self.set_dataset(batch_size_inference)
|
|
330
|
+
|
|
331
|
+
return self.vae.get_recon(self.dataset_full, self.full_masks, masks, zero_out, return_mean, L)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def update_z(self, masks=None, zero_out=True, batch_size_inference=512, **kwargs):
|
|
335
|
+
self.z = self.get_latent_z(masks, zero_out, batch_size_inference)
|
|
336
|
+
self.adata = sc.AnnData(self.z)
|
|
337
|
+
sc.pp.neighbors(self.adata, **kwargs)
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def visualize_latent(self, method: str = "UMAP",
|
|
341
|
+
color = None, **kwargs):
|
|
342
|
+
'''
|
|
343
|
+
visualize the current latent space z using the scanpy visualization tools
|
|
344
|
+
|
|
345
|
+
Parameters
|
|
346
|
+
----------
|
|
347
|
+
method : str, optional
|
|
348
|
+
Visualization method to use. The default is "draw_graph" (the FA plot). Possible choices include "PCA", "UMAP",
|
|
349
|
+
"diffmap", "TSNE" and "draw_graph"
|
|
350
|
+
color : TYPE, optional
|
|
351
|
+
Keys for annotations of observations/cells or variables/genes, e.g., 'ann1' or ['ann1', 'ann2'].
|
|
352
|
+
The default is None. Same as scanpy.
|
|
353
|
+
**kwargs :
|
|
354
|
+
Extra key-value arguments that can be passed to scanpy plotting functions (scanpy.pl.XX).
|
|
355
|
+
|
|
356
|
+
Returns
|
|
357
|
+
-------
|
|
358
|
+
None.
|
|
359
|
+
|
|
360
|
+
'''
|
|
361
|
+
|
|
362
|
+
if method not in ['PCA', 'UMAP', 'TSNE', 'diffmap', 'draw_graph']:
|
|
363
|
+
raise ValueError("visualization method should be one of 'PCA', 'UMAP', 'TSNE', 'diffmap' and 'draw_graph'")
|
|
364
|
+
|
|
365
|
+
temp = list(self.adata.obsm.keys())
|
|
366
|
+
if method == 'PCA' and not 'X_pca' in temp:
|
|
367
|
+
print("Calculate PCs ...")
|
|
368
|
+
sc.tl.pca(self.adata)
|
|
369
|
+
elif method == 'UMAP' and not 'X_umap' in temp:
|
|
370
|
+
print("Calculate UMAP ...")
|
|
371
|
+
sc.tl.umap(self.adata)
|
|
372
|
+
elif method == 'TSNE' and not 'X_tsne' in temp:
|
|
373
|
+
print("Calculate TSNE ...")
|
|
374
|
+
sc.tl.tsne(self.adata)
|
|
375
|
+
elif method == 'diffmap' and not 'X_diffmap' in temp:
|
|
376
|
+
print("Calculate diffusion map ...")
|
|
377
|
+
sc.tl.diffmap(self.adata)
|
|
378
|
+
elif method == 'draw_graph' and not 'X_draw_graph_fa' in temp:
|
|
379
|
+
print("Calculate FA ...")
|
|
380
|
+
sc.tl.draw_graph(self.adata)
|
|
381
|
+
|
|
382
|
+
if method == 'PCA':
|
|
383
|
+
axes = sc.pl.pca(self.adata, color = color, **kwargs)
|
|
384
|
+
elif method == 'UMAP':
|
|
385
|
+
axes = sc.pl.umap(self.adata, color = color, **kwargs)
|
|
386
|
+
elif method == 'TSNE':
|
|
387
|
+
axes = sc.pl.tsne(self.adata, color = color, **kwargs)
|
|
388
|
+
elif method == 'diffmap':
|
|
389
|
+
axes = sc.pl.diffmap(self.adata, color = color, **kwargs)
|
|
390
|
+
elif method == 'draw_graph':
|
|
391
|
+
axes = sc.pl.draw_graph(self.adata, color = color, **kwargs)
|
|
392
|
+
|
|
393
|
+
return axes
|