regdiffusion 0.2.0__py2.py3-none-any.whl → 0.2.2__py2.py3-none-any.whl

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/cli.py CHANGED
@@ -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 < 0).sum() > 0:
51
- raise ValueError("Negative values spotted in the data. Please only provide count data in this CLI tool. ")
52
- if (x - x.astype(int)).sum() > 1:
53
- raise ValueError("Data might have been log transformed. Please only provide count data in this CLI tool. ")
54
- x = np.log(x + 1.0)
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)
regdiffusion/trainer.py CHANGED
@@ -1,11 +1,12 @@
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
- from tqdm import tqdm
9
+ from tqdm.auto import tqdm
9
10
  from .logger import LightLogger
10
11
  from datetime import datetime
11
12
  from .grn import GRN
@@ -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 numpy array. If used on single-cell RNAseq,
43
- the rows are cells and the columns are genes. Data should be log
44
- transformed. You may also want to remove all non expressed genes.
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.
@@ -98,8 +136,8 @@ class RegDiffusionTrainer:
98
136
  accumulation. This is useful when number of genes are extremely
99
137
  large.
100
138
  use_amp (bool): Whether to use automatic mixed precision (bfloat16)
101
- during training. This reduces memory usage by storing activations
102
- in half precision while keeping model parameters in float32.
139
+ during training at the cost of 2x training time. This is usually
140
+ not recommended unless the last slice of memory is a bottleneck.
103
141
  Requires a GPU with bfloat16 support (Ampere or newer).
104
142
  Default: False.
105
143
  memory_efficient (bool): Whether to use the memory-efficient model
@@ -168,58 +206,15 @@ class RegDiffusionTrainer:
168
206
  self.n_gene = n_gene
169
207
 
170
208
  self.evaluator = evaluator
171
-
172
- ## Normalize data
173
- cell_min = exp_array.min(axis=1, keepdims=True)
174
- cell_max = exp_array.max(axis=1, keepdims=True)
175
- cell_range = cell_max - cell_min
176
- n_zero_cells = (cell_range == 0).sum()
177
- if n_zero_cells > 0:
178
- warnings.warn(
179
- f'{n_zero_cells} cells are removed from analysis where no genes are expressed.')
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
  """
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: regdiffusion
3
- Version: 0.2.0
3
+ Version: 0.2.2
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>
@@ -23,14 +23,12 @@ Project-URL: Home, https://github.com/TuftsBCB/RegDiffusion
23
23
  [![Downloads](https://static.pepy.tech/badge/regdiffusion/month)](https://pepy.tech/project/regdiffusion)
24
24
  ![PyPI - Version](https://img.shields.io/pypi/v/regdiffusion)
25
25
 
26
- RegDiffusion is a very fast unsupervised regulatory network inference algorithm (just like GENIE3 and GRNBoost2), based on probabilistic diffusion model. It works well on genes and is capable to rapidly (<5min) predict biologically verifiable links from large single cell RNA-seq data with 14,000+ genes.
26
+ RegDiffusion is a very fast unsupervised regulatory network inference algorithm (just like GENIE3 and GRNBoost2), based on probabilistic diffusion model. It works well on genes and is capable to rapidly (<5min) predict biologically verifiable links from large single cell RNA-seq data with 40,000+ genes.
27
27
 
28
28
  ```
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
- ![](https://raw.githubusercontent.com/TuftsBCB/RegDiffusion/master/resources/regdiffusion_structure.png)
33
-
34
32
  ## Installation
35
33
 
36
34
  RegDiffusion is on pypi.
@@ -39,7 +37,11 @@ RegDiffusion is on pypi.
39
37
  pip install regdiffusion
40
38
  ```
41
39
 
42
- Check out the [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).
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.
43
45
 
44
46
  ## Inferred Networks from RegDiffusion
45
47
  Here are two examples of inferred networks from regdiffusion. The networks are coherent with existing literature and across datasets.
@@ -75,7 +77,7 @@ options:
75
77
 
76
78
  ## Citation
77
79
 
78
- If you find our package useful, consider cite our paper! =)
80
+ If you find our package useful, consider citing our paper! =)
79
81
 
80
82
  ```
81
83
  @article{zhu2024noise,
@@ -1,9 +1,9 @@
1
1
  regdiffusion/__init__.py,sha256=iwbYh6AlX9yldwUp3X_7gfgUNzBSAGBcSoe39HV3zoQ,423
2
- regdiffusion/cli.py,sha256=Fo2k9ZMZSDb95a2EQabZVGfI1HJ8lACTCtpnOwCqwSw,2252
2
+ regdiffusion/cli.py,sha256=qUI7W1qDuTGAJvsGVJxJDw-5rWATR5WmzfWF9A7zPSI,2810
3
3
  regdiffusion/evaluator.py,sha256=bfuKVtbYIXcmUPIRXz4oBVahM3-wsSodXTTmsbbzJvQ,3350
4
4
  regdiffusion/grn.py,sha256=NJSE3-wpMuyjbwvtQIkfTWK1tLikdvvwSKU4d7uSf1Q,25822
5
5
  regdiffusion/logger.py,sha256=3l1fPbtT2mGM94cv_8NlbKuowzeajLaBoIDgKf_UR6M,5906
6
- regdiffusion/trainer.py,sha256=vPekEEvnhnNzvCY6NC1OSP-RjI-ktuF77OsG2ItwRYE,25992
6
+ regdiffusion/trainer.py,sha256=XQb7ABzl-s-oVElNUhrdfyHu5iCN4pnAP5giFlqt5dI,32126
7
7
  regdiffusion/data/__init__.py,sha256=G-eDyYgjY9xqu9v6mN7Py110Lz8O6cDuc4cMAFEecYQ,366
8
8
  regdiffusion/data/beeline.py,sha256=ULETEb7rv7h5OUOQRguMIbF0WBDN5F32TcXGRerM9D8,3697
9
9
  regdiffusion/data/microglia.py,sha256=B-19H8QAUHYMgv1K6i1n3i1SbMRxM7XZ3CE4LFPeVFA,4278
@@ -14,8 +14,8 @@ regdiffusion/models/regdiffusion_me.py,sha256=86Wm7zC-526Kf0KCEN-1gY13kJ-Kz3t5w0
14
14
  regdiffusion/plot/__init__.py,sha256=mXJbpYBc2-noIWrQVx-s_ka0eYsKByj4l_OZYKwUGBU,277
15
15
  regdiffusion/plot/pyvis.py,sha256=ajM1lr2SX1XI06VdgPEiLxo9pw8wStRI0B3McIa0mO4,4581
16
16
  regdiffusion/plot/static.py,sha256=bhDB-xB8C-3ZDUKoDJaoLQc0EqEXYgcO9a-sY_Uvpyo,11776
17
- regdiffusion-0.2.0.dist-info/entry_points.txt,sha256=A737tP1RgN6tYHktWvmZByLxaW__S6-LE7mRTn0PQF0,54
18
- regdiffusion-0.2.0.dist-info/licenses/LICENSE,sha256=jzkY6g_rbcJvt5Ehsqxr6IazE2Nj55hBtW4hkb6QMmw,11341
19
- regdiffusion-0.2.0.dist-info/WHEEL,sha256=Dyt6SBfaasWElUrURkknVFAZDHSTwxg3PaTza7RSbkY,100
20
- regdiffusion-0.2.0.dist-info/METADATA,sha256=aAMcfhN1Z8At9OnUu_AjjfFjgiMvQa9DhJoOVviCVRg,4301
21
- regdiffusion-0.2.0.dist-info/RECORD,,
17
+ regdiffusion-0.2.2.dist-info/entry_points.txt,sha256=A737tP1RgN6tYHktWvmZByLxaW__S6-LE7mRTn0PQF0,54
18
+ regdiffusion-0.2.2.dist-info/licenses/LICENSE,sha256=jzkY6g_rbcJvt5Ehsqxr6IazE2Nj55hBtW4hkb6QMmw,11341
19
+ regdiffusion-0.2.2.dist-info/WHEEL,sha256=Dyt6SBfaasWElUrURkknVFAZDHSTwxg3PaTza7RSbkY,100
20
+ regdiffusion-0.2.2.dist-info/METADATA,sha256=n0eQ1an0kwIqESlkcktyBX8_qeWaBZSasBZ3fW-_FvA,4621
21
+ regdiffusion-0.2.2.dist-info/RECORD,,