regdiffusion 0.2.0__tar.gz → 0.2.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.
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/NEWS.md +7 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/PKG-INFO +9 -5
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/README.md +8 -4
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/pyproject.toml +1 -1
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/cli.py +16 -5
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/trainer.py +194 -56
- regdiffusion-0.2.1/test_scripts/test_sparse_support.py +110 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/.github/workflows/documentation.yml +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/.gitignore +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/LICENSE +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/.gitignore +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/BUILD.md +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/Makefile +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/REG_PySCENIC.ipynb +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/_static/rd_logo_horizontal.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/_static/rd_logo_horizontal@2x.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/_static/regdiffusion.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/_static/regdiffusion@2x.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/_templates/autosummary/class.rst +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/_templates/autosummary/classnoinheritance.rst +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/conf.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/data_module.rst +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/downstream_with_pyscenic.md +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/index.rst +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/large_networks.md +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/main_api.rst +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/make.bat +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/models.rst +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/quick_tour.md +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/googled258341a97f33073.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Cx3cr1.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Fcrls.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Hexb.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Mertk.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_P2ry12.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Pros1.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Sall1.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Siglech.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Tmem119.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements/rd_hammond_Trem2.html +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/supplements.rst +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/example.ipynb +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/__init__.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/data/__init__.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/data/beeline.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/data/microglia.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/data/utils.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/evaluator.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/grn.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/logger.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/models/__init__.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/models/regdiffusion.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/models/regdiffusion_me.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/plot/__init__.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/plot/pyvis.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/regdiffusion/plot/static.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/apoe_net.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/aucell_mtx.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/aucell_umap.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/biomarkers.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/cellnames.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/edgelist.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/heatmap.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/mecs.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/mecs_cluster.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/regdiffusion_structure.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/regulon_scores.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/shinygo.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/resources/umap_comparison.png +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/test_scripts/test_beeline_benchmark.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/test_scripts/test_beeline_worker.py +0 -0
- {regdiffusion-0.2.0 → regdiffusion-0.2.1}/test_scripts/test_memory_benchmark.py +0 -0
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# RegDiffusion News / Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.1 [unreleased]
|
|
4
|
+
|
|
5
|
+
### New Features
|
|
6
|
+
- Added sparse matrix support for `RegDiffusionTrainer`. The `exp_array` argument now accepts scipy sparse matrices (e.g. `adata.X`) directly. Normalization statistics are computed in chunks and each sample is normalized on-the-fly during training, so the full dense matrix is never materialized. This enables training on datasets with 1M+ cells without excessive memory usage.
|
|
7
|
+
- Updated CLI (`regdiffusion` command) to handle sparse `adata.X` from H5AD files, including sparse-safe data validation and log-transform via `log1p` on non-zero entries.
|
|
8
|
+
|
|
9
|
+
|
|
3
10
|
## 0.2.0
|
|
4
11
|
|
|
5
12
|
### Memory Optimization
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: regdiffusion
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.1
|
|
4
4
|
Summary: Gene Regulatory Networks Inference using diffusion model
|
|
5
5
|
Author-email: Hao Zhu <haozhu233@gmail.com>, Donna Slonim <donna.slonim@tufts.edu>
|
|
6
6
|
Maintainer-email: Hao Zhu <haozhu233@gmail.com>
|
|
@@ -29,8 +29,6 @@ RegDiffusion is a very fast unsupervised regulatory network inference algorithm
|
|
|
29
29
|
Zhu H, Slonim D. From Noise to Knowledge: Diffusion Probabilistic Model-Based Neural Inference of Gene Regulatory Networks. J Comput Biol. 2024 Nov;31(11):1087-1103. doi: 10.1089/cmb.2024.0607. Epub 2024 Oct 10. PMID: 39387266; PMCID: PMC11698671.
|
|
30
30
|
```
|
|
31
31
|
|
|
32
|
-

|
|
33
|
-
|
|
34
32
|
## Installation
|
|
35
33
|
|
|
36
34
|
RegDiffusion is on pypi.
|
|
@@ -39,7 +37,13 @@ RegDiffusion is on pypi.
|
|
|
39
37
|
pip install regdiffusion
|
|
40
38
|
```
|
|
41
39
|
|
|
42
|
-
Check out
|
|
40
|
+
Check out [this tutorial](https://tuftsbcb.github.io/RegDiffusion/quick_tour.html) for a quick tour of how to use RegDiffusion! If you would like to integrate results from RegDiffusion into the SCENIC pipeline, checkout [this tutorial](https://tuftsbcb.github.io/RegDiffusion/downstream_with_pyscenic.html).
|
|
41
|
+
|
|
42
|
+
## New in v0.2
|
|
43
|
+
- **Memory-efficient mode**: Set `memory_efficient=True` in `RegDiffusionTrainer` to reduce peak GPU memory by ~45%, making it easier to work with large gene sets on consumer GPUs (You can now fit 20k genes on a 16GB GPU).
|
|
44
|
+
- **Sparse matrix support**: `RegDiffusionTrainer` now accepts scipy sparse matrices directly (e.g., `adata.X`), enabling training on datasets with 1M+ cells without excessive memory usage.
|
|
45
|
+
|
|
46
|
+

|
|
43
47
|
|
|
44
48
|
## Inferred Networks from RegDiffusion
|
|
45
49
|
Here are two examples of inferred networks from regdiffusion. The networks are coherent with existing literature and across datasets.
|
|
@@ -75,7 +79,7 @@ options:
|
|
|
75
79
|
|
|
76
80
|
## Citation
|
|
77
81
|
|
|
78
|
-
If you find our package useful, consider
|
|
82
|
+
If you find our package useful, consider citing our paper! =)
|
|
79
83
|
|
|
80
84
|
```
|
|
81
85
|
@article{zhu2024noise,
|
|
@@ -10,8 +10,6 @@ RegDiffusion is a very fast unsupervised regulatory network inference algorithm
|
|
|
10
10
|
Zhu H, Slonim D. From Noise to Knowledge: Diffusion Probabilistic Model-Based Neural Inference of Gene Regulatory Networks. J Comput Biol. 2024 Nov;31(11):1087-1103. doi: 10.1089/cmb.2024.0607. Epub 2024 Oct 10. PMID: 39387266; PMCID: PMC11698671.
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-

|
|
14
|
-
|
|
15
13
|
## Installation
|
|
16
14
|
|
|
17
15
|
RegDiffusion is on pypi.
|
|
@@ -20,7 +18,13 @@ RegDiffusion is on pypi.
|
|
|
20
18
|
pip install regdiffusion
|
|
21
19
|
```
|
|
22
20
|
|
|
23
|
-
Check out
|
|
21
|
+
Check out [this tutorial](https://tuftsbcb.github.io/RegDiffusion/quick_tour.html) for a quick tour of how to use RegDiffusion! If you would like to integrate results from RegDiffusion into the SCENIC pipeline, checkout [this tutorial](https://tuftsbcb.github.io/RegDiffusion/downstream_with_pyscenic.html).
|
|
22
|
+
|
|
23
|
+
## New in v0.2
|
|
24
|
+
- **Memory-efficient mode**: Set `memory_efficient=True` in `RegDiffusionTrainer` to reduce peak GPU memory by ~45%, making it easier to work with large gene sets on consumer GPUs (You can now fit 20k genes on a 16GB GPU).
|
|
25
|
+
- **Sparse matrix support**: `RegDiffusionTrainer` now accepts scipy sparse matrices directly (e.g., `adata.X`), enabling training on datasets with 1M+ cells without excessive memory usage.
|
|
26
|
+
|
|
27
|
+

|
|
24
28
|
|
|
25
29
|
## Inferred Networks from RegDiffusion
|
|
26
30
|
Here are two examples of inferred networks from regdiffusion. The networks are coherent with existing literature and across datasets.
|
|
@@ -56,7 +60,7 @@ options:
|
|
|
56
60
|
|
|
57
61
|
## Citation
|
|
58
62
|
|
|
59
|
-
If you find our package useful, consider
|
|
63
|
+
If you find our package useful, consider citing our paper! =)
|
|
60
64
|
|
|
61
65
|
```
|
|
62
66
|
@article{zhu2024noise,
|
|
@@ -13,7 +13,7 @@ maintainers = [
|
|
|
13
13
|
]
|
|
14
14
|
readme = "README.md"
|
|
15
15
|
license = {file = "LICENSE"}
|
|
16
|
-
version = "0.2.
|
|
16
|
+
version = "0.2.1"
|
|
17
17
|
description = "Gene Regulatory Networks Inference using diffusion model"
|
|
18
18
|
|
|
19
19
|
classifiers = ["License :: OSI Approved :: Apache Software License"]
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import argparse
|
|
2
2
|
import os
|
|
3
3
|
import numpy as np
|
|
4
|
+
import scipy.sparse as sp
|
|
4
5
|
import scanpy as sc
|
|
5
6
|
from .trainer import RegDiffusionTrainer
|
|
6
7
|
|
|
@@ -47,11 +48,21 @@ def main():
|
|
|
47
48
|
|
|
48
49
|
print("Applying log transformation on the dataset...")
|
|
49
50
|
x = adata.X
|
|
50
|
-
if (x
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
51
|
+
if sp.issparse(x):
|
|
52
|
+
if (x < 0).nnz > 0:
|
|
53
|
+
raise ValueError("Negative values spotted in the data. Please only provide count data in this CLI tool. ")
|
|
54
|
+
residual = x.copy()
|
|
55
|
+
residual.data = residual.data - residual.data.astype(int)
|
|
56
|
+
if abs(residual.sum()) > 1:
|
|
57
|
+
raise ValueError("Data might have been log transformed. Please only provide count data in this CLI tool. ")
|
|
58
|
+
x = x.copy()
|
|
59
|
+
x.data = np.log1p(x.data) # log(0+1)=0 stays sparse
|
|
60
|
+
else:
|
|
61
|
+
if (x < 0).sum() > 0:
|
|
62
|
+
raise ValueError("Negative values spotted in the data. Please only provide count data in this CLI tool. ")
|
|
63
|
+
if (x - x.astype(int)).sum() > 1:
|
|
64
|
+
raise ValueError("Data might have been log transformed. Please only provide count data in this CLI tool. ")
|
|
65
|
+
x = np.log(x + 1.0)
|
|
55
66
|
|
|
56
67
|
print("Initializing RegDiffusion trainer and starting training...")
|
|
57
68
|
rd_trainer = RegDiffusionTrainer(x)
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import numpy as np
|
|
2
2
|
import pandas as pd
|
|
3
|
+
import scipy.sparse as sp
|
|
3
4
|
import torch
|
|
4
5
|
import torch.nn.functional as F
|
|
5
|
-
from torch.utils.data import DataLoader
|
|
6
|
+
from torch.utils.data import DataLoader, Dataset
|
|
6
7
|
from torch.utils.data.dataset import TensorDataset
|
|
7
8
|
from .models import RegDiffusion, RegDiffusionME
|
|
8
9
|
from tqdm import tqdm
|
|
@@ -28,6 +29,40 @@ def power_beta_schedule(timesteps, start_noise, end_noise, power=2):
|
|
|
28
29
|
beta_end = scale * end_noise
|
|
29
30
|
return beta_start + (beta_end - beta_start) * poweredspace
|
|
30
31
|
|
|
32
|
+
class _SparseExpressionDataset(Dataset):
|
|
33
|
+
"""Dataset that stores sparse expression data and normalizes on-the-fly.
|
|
34
|
+
|
|
35
|
+
Instead of materializing the full dense normalized matrix (which can be
|
|
36
|
+
100+ GB for 1M cells), this dataset keeps the original sparse matrix in
|
|
37
|
+
memory and converts only the requested rows to dense during __getitem__.
|
|
38
|
+
|
|
39
|
+
Normalization applied per sample:
|
|
40
|
+
1. Min-max per cell: (x - cell_min) / cell_range
|
|
41
|
+
2. Z-score per gene: (x - gene_mean) / gene_std
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(self, sparse_X, cell_types, cell_min, cell_range,
|
|
45
|
+
gene_mean, gene_std, indices):
|
|
46
|
+
self.X = sparse_X # scipy CSR matrix (shared, read-only)
|
|
47
|
+
self.cell_types = cell_types # int array (full, not subset)
|
|
48
|
+
self.cell_min = cell_min # (n_cell,) float32
|
|
49
|
+
self.cell_range = cell_range # (n_cell,) float32
|
|
50
|
+
self.gene_mean = gene_mean # (n_gene,) float32
|
|
51
|
+
self.gene_std = gene_std # (n_gene,) float32
|
|
52
|
+
self.indices = indices # row indices for this split
|
|
53
|
+
|
|
54
|
+
def __len__(self):
|
|
55
|
+
return len(self.indices)
|
|
56
|
+
|
|
57
|
+
def __getitem__(self, idx):
|
|
58
|
+
real_idx = self.indices[idx]
|
|
59
|
+
row = self.X[real_idx].toarray().ravel().astype(np.float32)
|
|
60
|
+
row = (row - self.cell_min[real_idx]) / self.cell_range[real_idx]
|
|
61
|
+
row = (row - self.gene_mean) / self.gene_std
|
|
62
|
+
ct = int(self.cell_types[real_idx])
|
|
63
|
+
return torch.from_numpy(row), torch.tensor(ct, dtype=torch.long)
|
|
64
|
+
|
|
65
|
+
|
|
31
66
|
class RegDiffusionTrainer:
|
|
32
67
|
"""
|
|
33
68
|
Initialize and Train a RegDiffusion model.
|
|
@@ -39,9 +74,12 @@ class RegDiffusionTrainer:
|
|
|
39
74
|
You can access the model through `RegDiffusionTrainer.model`.
|
|
40
75
|
|
|
41
76
|
Args:
|
|
42
|
-
exp_array (np.ndarray): 2D
|
|
43
|
-
the rows are cells and the columns
|
|
44
|
-
transformed. You may also want to
|
|
77
|
+
exp_array (np.ndarray or scipy.sparse matrix): 2D expression matrix.
|
|
78
|
+
If used on single-cell RNAseq, the rows are cells and the columns
|
|
79
|
+
are genes. Data should be log transformed. You may also want to
|
|
80
|
+
remove all non expressed genes. Sparse matrices (e.g. from
|
|
81
|
+
``adata.X``) are supported and handled memory-efficiently — the
|
|
82
|
+
full dense normalized matrix is never materialized.
|
|
45
83
|
cell_types (np.ndarray): (Optional) 1D integer array for cell type. If
|
|
46
84
|
you have labels in your cell type, you need to convert them to
|
|
47
85
|
interge. Default is None.
|
|
@@ -168,58 +206,15 @@ class RegDiffusionTrainer:
|
|
|
168
206
|
self.n_gene = n_gene
|
|
169
207
|
|
|
170
208
|
self.evaluator = evaluator
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
normalized_X = (exp_array - cell_min) / cell_range
|
|
181
|
-
normalized_X_std = normalized_X.std(0)
|
|
182
|
-
n_zero_genes = (normalized_X_std == 0).sum()
|
|
183
|
-
if n_zero_genes > 0:
|
|
184
|
-
raise ValueError(
|
|
185
|
-
f'{n_zero_genes} genes have 0 variance. Please remove these genes from your data.')
|
|
186
|
-
normalized_X = (normalized_X - normalized_X.mean(0))/normalized_X_std
|
|
187
|
-
|
|
188
|
-
## Train/validation split
|
|
189
|
-
random_state = np.random.RandomState(train_split_seed)
|
|
190
|
-
train_val_split = random_state.rand(normalized_X.shape[0])
|
|
191
|
-
train_index = train_val_split <= train_split
|
|
192
|
-
val_index = train_val_split > train_split
|
|
193
|
-
|
|
194
|
-
x_tensor_train = torch.tensor(
|
|
195
|
-
normalized_X[train_index, ], dtype=torch.float32)
|
|
196
|
-
celltype_tensor_train = torch.tensor(
|
|
197
|
-
cell_types[train_index], dtype=int)
|
|
198
|
-
x_tensor_val = torch.tensor(
|
|
199
|
-
normalized_X[val_index, ], dtype=torch.float32)
|
|
200
|
-
celltype_tensor_val = torch.tensor(cell_types[val_index],dtype=int)
|
|
201
|
-
|
|
202
|
-
## Setup dataset and dataloader
|
|
203
|
-
self.train_dataset = torch.utils.data.TensorDataset(
|
|
204
|
-
x_tensor_train, celltype_tensor_train
|
|
205
|
-
)
|
|
206
|
-
# Implement bootstrap for train sampler
|
|
207
|
-
train_sampler = torch.utils.data.RandomSampler(
|
|
208
|
-
self.train_dataset, replacement=True, num_samples=batch_size)
|
|
209
|
-
self.train_dataloader = torch.utils.data.DataLoader(
|
|
210
|
-
self.train_dataset,
|
|
211
|
-
sampler=train_sampler,
|
|
212
|
-
batch_size = batch_size,
|
|
213
|
-
drop_last=True)
|
|
214
|
-
|
|
215
|
-
self.val_dataset = torch.utils.data.TensorDataset(
|
|
216
|
-
x_tensor_val, celltype_tensor_val
|
|
217
|
-
)
|
|
218
|
-
self.val_dataloader = torch.utils.data.DataLoader(
|
|
219
|
-
self.val_dataset,
|
|
220
|
-
shuffle=False,
|
|
221
|
-
batch_size = batch_size,
|
|
222
|
-
drop_last=False)
|
|
209
|
+
|
|
210
|
+
if sp.issparse(exp_array):
|
|
211
|
+
self._prepare_sparse_data(
|
|
212
|
+
exp_array, cell_types, batch_size,
|
|
213
|
+
train_split, train_split_seed)
|
|
214
|
+
else:
|
|
215
|
+
self._prepare_dense_data(
|
|
216
|
+
exp_array, cell_types, batch_size,
|
|
217
|
+
train_split, train_split_seed)
|
|
223
218
|
|
|
224
219
|
# Setup Model ----------------------------------------------------------
|
|
225
220
|
gene_reg_norm = 1/(n_gene-1)
|
|
@@ -268,6 +263,149 @@ class RegDiffusionTrainer:
|
|
|
268
263
|
self.amp_device_type = 'cuda' if device.startswith('cuda') else 'cpu'
|
|
269
264
|
|
|
270
265
|
|
|
266
|
+
def _prepare_dense_data(self, exp_array, cell_types, batch_size,
|
|
267
|
+
train_split, train_split_seed):
|
|
268
|
+
"""Normalize dense numpy array and build TensorDataset (original path)."""
|
|
269
|
+
cell_min = exp_array.min(axis=1, keepdims=True)
|
|
270
|
+
cell_max = exp_array.max(axis=1, keepdims=True)
|
|
271
|
+
cell_range = cell_max - cell_min
|
|
272
|
+
n_zero_cells = (cell_range == 0).sum()
|
|
273
|
+
if n_zero_cells > 0:
|
|
274
|
+
warnings.warn(
|
|
275
|
+
f'{n_zero_cells} cells are removed from analysis where no genes are expressed.')
|
|
276
|
+
normalized_X = (exp_array - cell_min) / cell_range
|
|
277
|
+
normalized_X_std = normalized_X.std(0)
|
|
278
|
+
n_zero_genes = (normalized_X_std == 0).sum()
|
|
279
|
+
if n_zero_genes > 0:
|
|
280
|
+
raise ValueError(
|
|
281
|
+
f'{n_zero_genes} genes have 0 variance. Please remove these genes from your data.')
|
|
282
|
+
normalized_X = (normalized_X - normalized_X.mean(0)) / normalized_X_std
|
|
283
|
+
|
|
284
|
+
random_state = np.random.RandomState(train_split_seed)
|
|
285
|
+
train_val_split = random_state.rand(normalized_X.shape[0])
|
|
286
|
+
train_index = train_val_split <= train_split
|
|
287
|
+
val_index = train_val_split > train_split
|
|
288
|
+
|
|
289
|
+
x_tensor_train = torch.tensor(
|
|
290
|
+
normalized_X[train_index, ], dtype=torch.float32)
|
|
291
|
+
celltype_tensor_train = torch.tensor(
|
|
292
|
+
cell_types[train_index], dtype=int)
|
|
293
|
+
x_tensor_val = torch.tensor(
|
|
294
|
+
normalized_X[val_index, ], dtype=torch.float32)
|
|
295
|
+
celltype_tensor_val = torch.tensor(cell_types[val_index], dtype=int)
|
|
296
|
+
|
|
297
|
+
self.train_dataset = TensorDataset(
|
|
298
|
+
x_tensor_train, celltype_tensor_train)
|
|
299
|
+
train_sampler = torch.utils.data.RandomSampler(
|
|
300
|
+
self.train_dataset, replacement=True, num_samples=batch_size)
|
|
301
|
+
self.train_dataloader = DataLoader(
|
|
302
|
+
self.train_dataset,
|
|
303
|
+
sampler=train_sampler,
|
|
304
|
+
batch_size=batch_size,
|
|
305
|
+
drop_last=True)
|
|
306
|
+
|
|
307
|
+
self.val_dataset = TensorDataset(
|
|
308
|
+
x_tensor_val, celltype_tensor_val)
|
|
309
|
+
self.val_dataloader = DataLoader(
|
|
310
|
+
self.val_dataset,
|
|
311
|
+
shuffle=False,
|
|
312
|
+
batch_size=batch_size,
|
|
313
|
+
drop_last=False)
|
|
314
|
+
|
|
315
|
+
def _prepare_sparse_data(self, exp_array, cell_types, batch_size,
|
|
316
|
+
train_split, train_split_seed):
|
|
317
|
+
"""Compute normalization stats from sparse matrix in chunks, then build
|
|
318
|
+
a _SparseExpressionDataset that normalizes on-the-fly per sample.
|
|
319
|
+
|
|
320
|
+
This never materializes the full dense normalized matrix, so memory
|
|
321
|
+
usage stays proportional to (sparse matrix size + one batch of dense
|
|
322
|
+
rows) rather than (n_cell * n_gene * 4 bytes).
|
|
323
|
+
"""
|
|
324
|
+
n_cell, n_gene = exp_array.shape
|
|
325
|
+
exp_array = sp.csr_matrix(exp_array) # ensure CSR for fast row slicing
|
|
326
|
+
|
|
327
|
+
# --- Per-cell min/max in chunks ---
|
|
328
|
+
chunk_size = min(10000, n_cell)
|
|
329
|
+
cell_min = np.empty(n_cell, dtype=np.float64)
|
|
330
|
+
cell_max = np.empty(n_cell, dtype=np.float64)
|
|
331
|
+
for start in range(0, n_cell, chunk_size):
|
|
332
|
+
end = min(start + chunk_size, n_cell)
|
|
333
|
+
chunk = exp_array[start:end]
|
|
334
|
+
cell_min[start:end] = np.asarray(
|
|
335
|
+
chunk.min(axis=1).todense()).ravel()
|
|
336
|
+
cell_max[start:end] = np.asarray(
|
|
337
|
+
chunk.max(axis=1).todense()).ravel()
|
|
338
|
+
|
|
339
|
+
cell_range = cell_max - cell_min
|
|
340
|
+
valid_mask = cell_range > 0
|
|
341
|
+
n_zero_cells = (~valid_mask).sum()
|
|
342
|
+
if n_zero_cells > 0:
|
|
343
|
+
warnings.warn(
|
|
344
|
+
f'{n_zero_cells} cells are removed from analysis where no '
|
|
345
|
+
'genes are expressed.')
|
|
346
|
+
|
|
347
|
+
# --- Per-gene mean/std of min-max-normalized data (chunked) ---
|
|
348
|
+
n_valid = valid_mask.sum()
|
|
349
|
+
gene_sum = np.zeros(n_gene, dtype=np.float64)
|
|
350
|
+
gene_sum_sq = np.zeros(n_gene, dtype=np.float64)
|
|
351
|
+
|
|
352
|
+
for start in range(0, n_cell, chunk_size):
|
|
353
|
+
end = min(start + chunk_size, n_cell)
|
|
354
|
+
chunk_valid = valid_mask[start:end]
|
|
355
|
+
if not chunk_valid.any():
|
|
356
|
+
continue
|
|
357
|
+
# Only materialize valid rows in this chunk
|
|
358
|
+
chunk_dense = exp_array[start:end][chunk_valid].toarray().astype(
|
|
359
|
+
np.float64)
|
|
360
|
+
c_min = cell_min[start:end][chunk_valid][:, None]
|
|
361
|
+
c_range = cell_range[start:end][chunk_valid][:, None]
|
|
362
|
+
chunk_norm = (chunk_dense - c_min) / c_range
|
|
363
|
+
gene_sum += chunk_norm.sum(axis=0)
|
|
364
|
+
gene_sum_sq += (chunk_norm ** 2).sum(axis=0)
|
|
365
|
+
|
|
366
|
+
gene_mean = (gene_sum / n_valid).astype(np.float32)
|
|
367
|
+
gene_var = (gene_sum_sq / n_valid) - gene_mean.astype(np.float64) ** 2
|
|
368
|
+
gene_std = np.sqrt(np.maximum(gene_var, 0)).astype(np.float32)
|
|
369
|
+
|
|
370
|
+
n_zero_genes = (gene_std == 0).sum()
|
|
371
|
+
if n_zero_genes > 0:
|
|
372
|
+
raise ValueError(
|
|
373
|
+
f'{n_zero_genes} genes have 0 variance. Please remove these '
|
|
374
|
+
'genes from your data.')
|
|
375
|
+
|
|
376
|
+
# --- Train/validation split (only among valid cells) ---
|
|
377
|
+
valid_indices = np.where(valid_mask)[0]
|
|
378
|
+
random_state = np.random.RandomState(train_split_seed)
|
|
379
|
+
split_vals = random_state.rand(len(valid_indices))
|
|
380
|
+
train_indices = valid_indices[split_vals <= train_split]
|
|
381
|
+
val_indices = valid_indices[split_vals > train_split]
|
|
382
|
+
|
|
383
|
+
cell_min_f32 = cell_min.astype(np.float32)
|
|
384
|
+
cell_range_f32 = cell_range.astype(np.float32)
|
|
385
|
+
|
|
386
|
+
# --- Build datasets ---
|
|
387
|
+
self.train_dataset = _SparseExpressionDataset(
|
|
388
|
+
exp_array, cell_types,
|
|
389
|
+
cell_min_f32, cell_range_f32, gene_mean, gene_std,
|
|
390
|
+
train_indices)
|
|
391
|
+
train_sampler = torch.utils.data.RandomSampler(
|
|
392
|
+
self.train_dataset, replacement=True, num_samples=batch_size)
|
|
393
|
+
self.train_dataloader = DataLoader(
|
|
394
|
+
self.train_dataset,
|
|
395
|
+
sampler=train_sampler,
|
|
396
|
+
batch_size=batch_size,
|
|
397
|
+
drop_last=True)
|
|
398
|
+
|
|
399
|
+
self.val_dataset = _SparseExpressionDataset(
|
|
400
|
+
exp_array, cell_types,
|
|
401
|
+
cell_min_f32, cell_range_f32, gene_mean, gene_std,
|
|
402
|
+
val_indices)
|
|
403
|
+
self.val_dataloader = DataLoader(
|
|
404
|
+
self.val_dataset,
|
|
405
|
+
shuffle=False,
|
|
406
|
+
batch_size=batch_size,
|
|
407
|
+
drop_last=False)
|
|
408
|
+
|
|
271
409
|
@torch.no_grad()
|
|
272
410
|
def forward_pass(self, x_0, t):
|
|
273
411
|
"""
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""Verify that RegDiffusionTrainer accepts sparse matrices and produces
|
|
2
|
+
results consistent with the dense path."""
|
|
3
|
+
import numpy as np
|
|
4
|
+
import scipy.sparse as sp
|
|
5
|
+
import torch
|
|
6
|
+
import regdiffusion as rd
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_sparse_dense_consistency():
|
|
10
|
+
"""Train briefly with dense and sparse input; compare adjacency matrices."""
|
|
11
|
+
np.random.seed(42)
|
|
12
|
+
torch.manual_seed(42)
|
|
13
|
+
|
|
14
|
+
# Create a small synthetic expression matrix (log-transformed counts)
|
|
15
|
+
n_cell, n_gene = 200, 50
|
|
16
|
+
dense_X = np.random.rand(n_cell, n_gene).astype(np.float32)
|
|
17
|
+
# Make it look like log-transformed scRNA-seq (many near-zero values)
|
|
18
|
+
dense_X[dense_X < 0.6] = 0.0
|
|
19
|
+
dense_X = np.log1p(dense_X * 10)
|
|
20
|
+
|
|
21
|
+
sparse_X = sp.csr_matrix(dense_X)
|
|
22
|
+
|
|
23
|
+
# --- Dense path ---
|
|
24
|
+
torch.manual_seed(0)
|
|
25
|
+
np.random.seed(0)
|
|
26
|
+
trainer_dense = rd.RegDiffusionTrainer(
|
|
27
|
+
dense_X, device='cpu', n_steps=5, batch_size=32)
|
|
28
|
+
|
|
29
|
+
# --- Sparse path ---
|
|
30
|
+
torch.manual_seed(0)
|
|
31
|
+
np.random.seed(0)
|
|
32
|
+
trainer_sparse = rd.RegDiffusionTrainer(
|
|
33
|
+
sparse_X, device='cpu', n_steps=5, batch_size=32)
|
|
34
|
+
|
|
35
|
+
# Both should have the same shape metadata
|
|
36
|
+
assert trainer_dense.n_cell == trainer_sparse.n_cell
|
|
37
|
+
assert trainer_dense.n_gene == trainer_sparse.n_gene
|
|
38
|
+
|
|
39
|
+
# Check that one batch from each dataloader has the same shape
|
|
40
|
+
batch_d = next(iter(trainer_dense.train_dataloader))
|
|
41
|
+
batch_s = next(iter(trainer_sparse.train_dataloader))
|
|
42
|
+
assert batch_d[0].shape == batch_s[0].shape, (
|
|
43
|
+
f"Dense batch: {batch_d[0].shape}, Sparse batch: {batch_s[0].shape}")
|
|
44
|
+
|
|
45
|
+
# Verify no NaN/Inf in sparse-path batches
|
|
46
|
+
assert torch.isfinite(batch_s[0]).all(), "Sparse batch contains NaN/Inf!"
|
|
47
|
+
|
|
48
|
+
print("PASS: Sparse and dense paths produce consistent shapes, no NaN/Inf.")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_sparse_training():
|
|
52
|
+
"""Full sparse training smoke test."""
|
|
53
|
+
np.random.seed(42)
|
|
54
|
+
torch.manual_seed(42)
|
|
55
|
+
|
|
56
|
+
n_cell, n_gene = 300, 30
|
|
57
|
+
dense_X = np.random.rand(n_cell, n_gene).astype(np.float32)
|
|
58
|
+
dense_X[dense_X < 0.5] = 0.0
|
|
59
|
+
dense_X = np.log1p(dense_X * 10)
|
|
60
|
+
sparse_X = sp.csr_matrix(dense_X)
|
|
61
|
+
|
|
62
|
+
trainer = rd.RegDiffusionTrainer(
|
|
63
|
+
sparse_X, device='cpu', n_steps=10, batch_size=64)
|
|
64
|
+
trainer.train()
|
|
65
|
+
|
|
66
|
+
adj = trainer.get_adj()
|
|
67
|
+
assert adj.shape == (n_gene, n_gene), f"Unexpected adj shape: {adj.shape}"
|
|
68
|
+
assert np.isfinite(adj).all(), "Adjacency matrix has NaN/Inf"
|
|
69
|
+
print("PASS: Sparse training completes, adjacency matrix is valid.")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_sparse_with_cell_types():
|
|
73
|
+
"""Sparse input with cell type labels."""
|
|
74
|
+
np.random.seed(42)
|
|
75
|
+
n_cell, n_gene = 200, 20
|
|
76
|
+
dense_X = np.random.rand(n_cell, n_gene).astype(np.float32)
|
|
77
|
+
dense_X[dense_X < 0.5] = 0.0
|
|
78
|
+
dense_X = np.log1p(dense_X * 10)
|
|
79
|
+
sparse_X = sp.csr_matrix(dense_X)
|
|
80
|
+
cell_types = np.random.randint(0, 3, n_cell)
|
|
81
|
+
|
|
82
|
+
trainer = rd.RegDiffusionTrainer(
|
|
83
|
+
sparse_X, cell_types=cell_types,
|
|
84
|
+
device='cpu', n_steps=5, batch_size=32)
|
|
85
|
+
trainer.train()
|
|
86
|
+
print("PASS: Sparse with cell types works.")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def test_sparse_val_split():
|
|
90
|
+
"""Sparse input with train/val split."""
|
|
91
|
+
np.random.seed(42)
|
|
92
|
+
n_cell, n_gene = 200, 20
|
|
93
|
+
dense_X = np.random.rand(n_cell, n_gene).astype(np.float32)
|
|
94
|
+
dense_X[dense_X < 0.5] = 0.0
|
|
95
|
+
dense_X = np.log1p(dense_X * 10)
|
|
96
|
+
sparse_X = sp.csr_matrix(dense_X)
|
|
97
|
+
|
|
98
|
+
trainer = rd.RegDiffusionTrainer(
|
|
99
|
+
sparse_X, device='cpu', n_steps=5, batch_size=32,
|
|
100
|
+
train_split=0.8)
|
|
101
|
+
trainer.train()
|
|
102
|
+
print("PASS: Sparse with train/val split works.")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
if __name__ == '__main__':
|
|
106
|
+
test_sparse_dense_consistency()
|
|
107
|
+
test_sparse_training()
|
|
108
|
+
test_sparse_with_cell_types()
|
|
109
|
+
test_sparse_val_split()
|
|
110
|
+
print("\nAll sparse support tests passed!")
|
|
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
|
{regdiffusion-0.2.0 → regdiffusion-0.2.1}/docs/_templates/autosummary/classnoinheritance.rst
RENAMED
|
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
|
|
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
|
|
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
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|