regdiffusion 0.2.2__py2.py3-none-any.whl → 0.2.3__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/__init__.py CHANGED
@@ -6,10 +6,10 @@ from . import models
6
6
  from . import plot
7
7
 
8
8
  from .logger import LightLogger, load_logger
9
- from .trainer import RegDiffusionTrainer
9
+ from .trainer import RegDiffusionTrainer, set_seed
10
10
  from .grn import GRN, read_hdf5
11
11
  from .evaluator import GRNEvaluator
12
12
 
13
- __all__ = ['data', 'models', 'plot', 'LightLogger', 'load_logger',
14
- 'RegDiffusionTrainer', 'GRN', 'read_hdf5', 'GRNEvaluator']
13
+ __all__ = ['data', 'models', 'plot', 'LightLogger', 'load_logger',
14
+ 'RegDiffusionTrainer', 'set_seed', 'GRN', 'read_hdf5', 'GRNEvaluator']
15
15
 
regdiffusion/cli.py CHANGED
@@ -36,6 +36,12 @@ def main():
36
36
  default=4,
37
37
  help="Number of workers to use for edgelist extraction. Default: 4"
38
38
  )
39
+ parser.add_argument(
40
+ "--seed",
41
+ type=int,
42
+ default=None,
43
+ help="Random seed for reproducible results. Default: None"
44
+ )
39
45
 
40
46
  args = parser.parse_args()
41
47
 
@@ -65,7 +71,7 @@ def main():
65
71
  x = np.log(x + 1.0)
66
72
 
67
73
  print("Initializing RegDiffusion trainer and starting training...")
68
- rd_trainer = RegDiffusionTrainer(x)
74
+ rd_trainer = RegDiffusionTrainer(x, seed=args.seed)
69
75
  rd_trainer.train()
70
76
 
71
77
  grn = rd_trainer.get_grn(
@@ -1,7 +1,7 @@
1
1
  import numpy as np
2
2
  import scanpy as sc
3
3
  import pandas as pd
4
- from tqdm import tqdm
4
+ from tqdm.auto import tqdm
5
5
  import zipfile
6
6
  import os
7
7
  from .utils import download_file
@@ -47,14 +47,14 @@ def load_beeline(data_dir='data', benchmark_data='hESC',
47
47
 
48
48
  Args:
49
49
  data_dir (str): Parent directory to save and load the data. If the path
50
- does not exist, it will be created. Data will be saved in a
51
- subdirectory under the provided path.
52
- benchmark_data (str): Benchmark datasets. Choose among "hESC", "hHep",
53
- "mDC", "mESC", "mHSC", "mHSC-GM", and "mHSC-L".
54
- benchmark_setting (str): Benchmark settings. Choose among "500_STRING",
55
- "1000_STRING", "500_Non-ChIP", "1000_Non-ChIP", "500_ChIP-seq",
56
- "1000_ChIP-seq", "500_lofgof", and "1000_lofgof". If either of the
57
- "lofgof" settings is choosed, only "mESC" data is available.
50
+ does not exist, it will be created. Data will be saved in a
51
+ subdirectory under the provided path.
52
+ benchmark_data (str): Benchmark datasets. Choose among "hESC", "hHep",
53
+ "mDC", "mESC", "mHSC", "mHSC-GM", and "mHSC-L".
54
+ benchmark_setting (str): Benchmark settings. Choose among "500_STRING",
55
+ "1000_STRING", "500_Non-ChIP", "1000_Non-ChIP", "500_ChIP-seq",
56
+ "1000_ChIP-seq", "500_lofgof", and "1000_lofgof". If either of the
57
+ "lofgof" settings is chosen, only "mESC" data is available.
58
58
 
59
59
  Returns:
60
60
  tuple: A tuple containing two objects for a single BEELINE benchmark.
@@ -1,7 +1,7 @@
1
1
  import numpy as np
2
2
  import scanpy as sc
3
3
  import pandas as pd
4
- from tqdm import tqdm
4
+ from tqdm.auto import tqdm
5
5
  import zipfile
6
6
  import os
7
7
  from .utils import download_file
@@ -26,8 +26,8 @@ def load_atlas_microglia(data_dir='data') -> sc.AnnData:
26
26
 
27
27
  Args:
28
28
  data_dir (str): Parent directory to save and load the data. If the path
29
- does not exist, it will be created. Data will be saved in a
30
- subdirectory under the provided path.
29
+ does not exist, it will be created. Data will be saved in a
30
+ subdirectory under the provided path.
31
31
  """
32
32
  if not os.path.exists(data_dir):
33
33
  os.mkdir(data_dir)
@@ -73,9 +73,8 @@ def load_hammond_microglia(data_dir='data'):
73
73
 
74
74
  Args:
75
75
  data_dir (str): Parent directory to save and load the data. If the path
76
- does not exist, it will be created. Data will be saved in a
77
- subdirectory under the provided path.
78
-
76
+ does not exist, it will be created. Data will be saved in a
77
+ subdirectory under the provided path.
79
78
  """
80
79
  if not os.path.exists(data_dir):
81
80
  os.mkdir(data_dir)
@@ -1,5 +1,5 @@
1
1
  import urllib
2
- from tqdm import tqdm
2
+ from tqdm.auto import tqdm
3
3
 
4
4
  # Modified from https://gist.github.com/yanqd0/c13ed29e29432e3cf3e7c38467f42f51
5
5
  def download_file(url, file_path, chunk_size=1024):
regdiffusion/evaluator.py CHANGED
@@ -59,6 +59,16 @@ class GRNEvaluator:
59
59
  self.report_epr = ('EPR' in metrics)
60
60
 
61
61
  def evaluate(self, A):
62
+ """
63
+ Evaluate a predicted adjacency matrix against the ground truth.
64
+
65
+ Args:
66
+ A (np.ndarray): Predicted adjacency matrix of shape
67
+ (n_gene, n_gene) or (n_tf, n_gene).
68
+
69
+ Returns:
70
+ dict: Dictionary of evaluation metrics (e.g. AUROC, AUPR).
71
+ """
62
72
  if A.shape[0] == A.shape[1]:
63
73
  A = A[self.tf_mask, :]
64
74
  A = A[:, self.gene_mask]
regdiffusion/grn.py CHANGED
@@ -1,6 +1,6 @@
1
1
  import numpy as np
2
2
  import pandas as pd
3
- from tqdm import tqdm
3
+ from tqdm.auto import tqdm
4
4
  from datetime import datetime
5
5
  from collections import deque, Counter
6
6
  from scipy.sparse import csr_matrix
@@ -10,42 +10,41 @@ import concurrent.futures
10
10
  from .plot import plot_pyvis
11
11
 
12
12
  class GRN:
13
- """
14
- A Object to save and analyze gene regulatory network
13
+ """
14
+ An object to save and analyze a gene regulatory network.
15
15
 
16
- A GRN object includes the adjacency matrix between transcriptional factors
17
- and target genes. In many cases, when TFs are not specified, we have a
18
- square-shaped adjacency matrix. We expected the adjacency
19
- matrix to hold predicted weights/probabilities for the edges (float).
16
+ A GRN object includes the adjacency matrix between transcriptional factors
17
+ and target genes. In many cases, when TFs are not specified, we have a
18
+ square-shaped adjacency matrix. We expect the adjacency
19
+ matrix to hold predicted weights/probabilities for the edges (float).
20
20
 
21
21
  To create a GRN object, you need at least two things: the adjacency matrix
22
22
  and the corresponding gene names. You can further specify the TF names if
23
- your adjacency matrix is not a square matrix.
23
+ your adjacency matrix is not a square matrix.
24
24
 
25
- You can save a GRN object to the HDF5 format using the `.to_hdf5` method in
26
- the GRN class. You can load a saved GRN object using the `read_hdf5`
27
- function in this package.
25
+ You can save a GRN object to the HDF5 format using the ``.to_hdf5`` method
26
+ in the GRN class. You can load a saved GRN object using the ``read_hdf5``
27
+ function in this package.
28
28
 
29
29
  If your adjacency matrix is very large and space is a concern, you may
30
- consider provide a value for `top_gene_percentile`. This value will
31
- calculate the a cutoff point for the values in the adjacency matrix.
32
- Every value whose absolute value is below this cutoff point will be set to
33
- zero. Later on, we can save the data as a sparse matrix to reduce the
34
- space requirement.
35
-
30
+ consider providing a value for ``top_gene_percentile``. This will calculate
31
+ a cutoff point for the values in the adjacency matrix. Every value whose
32
+ absolute value is below this cutoff point will be set to zero. Later on, we
33
+ can save the data as a sparse matrix to reduce the space requirement.
34
+
36
35
  The GRN object comes with many useful methods to analyze and visualize the
37
- network. Top top-level interfaces includes `.extract_node_2hop_neighborhood`
38
- and `.visualize_local_neighborhood`.
36
+ network. Top-level interfaces include ``.extract_local_neighborhood``
37
+ and ``.visualize_local_neighborhood``.
39
38
 
40
39
  Args:
41
40
  adj_matrix (np.ndarray): A 2D adjacency matrix to save.
42
- gene_names (np.ndarray): A 1D numpy array with all the target gene
43
- names.
44
- tf_names (np.ndarray, optional): A 1D numpy array with all the TF gene
45
- names.
46
- top_gene_percentile (int): If this value is set, only the top k absolute
47
- values in the adjacency matrix will be kept. All the other values
48
- will be set to zero.
41
+ gene_names (np.ndarray): A 1D numpy array with all the target gene
42
+ names.
43
+ tf_names (np.ndarray, optional): A 1D numpy array with all the TF
44
+ gene names.
45
+ top_gene_percentile (int): If this value is set, only the top k
46
+ absolute values in the adjacency matrix will be kept. All the
47
+ other values will be set to zero.
49
48
  """
50
49
  def __init__(self, adj_matrix: np.ndarray,
51
50
  gene_names: np.ndarray,
@@ -65,8 +64,9 @@ class GRN:
65
64
  # Here we are estimating the cutoff point for top a% predicted edges
66
65
  # To speed up the process, we calculate the 1-a% percentile within
67
66
  # 10,000 sampled edges instead of all edges.
68
- random_row_idx = np.random.randint(0, self.n_tfs, 10000)
69
- random_col_idx = np.random.randint(0, self.n_genes, 10000)
67
+ rng = np.random.RandomState(0)
68
+ random_row_idx = rng.randint(0, self.n_tfs, 10000)
69
+ random_col_idx = rng.randint(0, self.n_genes, 10000)
70
70
  sampled_values = adj_matrix[random_row_idx, random_col_idx]
71
71
  self.cutoff_threshold = np.percentile(
72
72
  np.abs(sampled_values), 100-top_gene_percentile
@@ -137,7 +137,7 @@ class GRN:
137
137
  selected gene. It is slightly faster than the dataframe version.
138
138
 
139
139
  Args:
140
- genes (str, List(str)): A single gene or a list of genes to inspect.
140
+ gene (str): A single gene to inspect.
141
141
  k (int): Top-k edges to inspect on each node. If k=-1, export all
142
142
  """
143
143
  gene_idx = self.gene_indices[gene]
@@ -162,7 +162,7 @@ class GRN:
162
162
  The dataframe will have 3 columns: `source`, `target`, `weight`.
163
163
 
164
164
  Args:
165
- genes (str, List(str)): A single gene or a list of genes to inspect.
165
+ gene (str): A single gene to inspect.
166
166
  k (int): Top-k edges to inspect on each node. If k=-1, export all
167
167
  """
168
168
  source_indices = self.extract_node_sources_as_indices(gene, k)
@@ -182,7 +182,7 @@ class GRN:
182
182
  selected gene. It is slightly faster than the dataframe version.
183
183
 
184
184
  Args:
185
- genes (str, List(str)): A single gene or a list of genes to inspect.
185
+ gene (str): A single gene to inspect.
186
186
  k (int): Top-k edges to inspect on each node. If k=-1, export all
187
187
  """
188
188
  gene_idx = self.tf_indices[gene]
@@ -207,7 +207,7 @@ class GRN:
207
207
  The dataframe will have 3 columns: `source`, `target`, `weight`.
208
208
 
209
209
  Args:
210
- genes (str, List(str)): A single gene or a list of genes to inspect.
210
+ gene (str): A single gene to inspect.
211
211
  k (int): Top-k edges to inspect on each node. If k=-1, export all
212
212
  """
213
213
  target_indices = self.extract_node_targets_as_indices(gene, k)
@@ -227,7 +227,7 @@ class GRN:
227
227
  It is slightly faster than the dataframe version.
228
228
 
229
229
  Args:
230
- genes (str, List(str)): A single gene or a list of genes to inspect.
230
+ gene (str): A single gene to inspect.
231
231
  k (int): Top-k edges to inspect on each node. If k=-1, export all
232
232
  """
233
233
  gene_idx = self.gene_indices[gene]
@@ -261,7 +261,7 @@ class GRN:
261
261
  The dataframe will have 3 columns: `source`, `target`, `weight`.
262
262
 
263
263
  Args:
264
- genes (str, List(str)): A single gene or a list of genes to inspect.
264
+ gene (str): A single gene to inspect.
265
265
  k (int): Top-k edges to inspect on each node. If k=-1, export all
266
266
  """
267
267
  neighbor_indices = self.extract_node_neighbors_as_indices(gene, k)
@@ -294,10 +294,10 @@ class GRN:
294
294
  is defined in a similar way but smaller.
295
295
 
296
296
  Args:
297
- genes (str, List(str)): A single gene or a list of genes to inspect.
297
+ gene (str): A single gene to inspect.
298
298
  k (int): Top-k edges to inspect on each node. If k=-1, export all
299
299
  hops (str): Number of hops to explore. We can either do a "2.5" or
300
- "1.5" hop travesal around selected genes. Default is "2.5".
300
+ "1.5" hop traversal around selected genes. Default is "2.5".
301
301
  """
302
302
  if isinstance(genes, str):
303
303
  genes = [genes]
@@ -364,7 +364,7 @@ class GRN:
364
364
  (2-hop) around selected gene(s).
365
365
 
366
366
  Args:
367
- genes (str, List(str)): A single gene or a list of genes to inspect.
367
+ gene (str): A single gene to inspect.
368
368
  k (int): Top-k edges to inspect on each node. If k=-1, export all.
369
369
  hops (str): Number of hops of the neighborhood to explore. Default
370
370
  is "2.5".
regdiffusion/logger.py CHANGED
@@ -82,6 +82,19 @@ class LightLogger:
82
82
  self.logging_vars.add(k)
83
83
 
84
84
  def check_early_stopping(self, item: str, k: int = 10):
85
+ """
86
+ Check if training should stop early based on a monitored metric.
87
+
88
+ Returns True if the minimum value in the last ``k`` steps is greater
89
+ than the historical minimum, indicating no improvement.
90
+
91
+ Args:
92
+ item (str): The metric name to monitor (e.g. 'val_loss').
93
+ k (int): Window size to check for improvement. Default: 10.
94
+
95
+ Returns:
96
+ bool: True if early stopping criteria is met.
97
+ """
85
98
  end_idx = self.mem[self.current_log]['current_step']
86
99
  window = []
87
100
  start_idx = max(end_idx-k, 0)
@@ -62,19 +62,19 @@ class RegDiffusion(nn.Module):
62
62
  From noise to knowledge: probabilistic diffusion-based neural inference
63
63
 
64
64
  Args:
65
- n_genes (int): Number of Genes
66
- time_dim (int): Dimension of time step embedding
67
- n_celltype (int): Number of expected cell types. If it is not provided,
68
- there would be no celltype embedding. Default is None.
69
- celltype_dim (int): Dimension of cell types
70
- hidden_dims (list[int]): List of integer for the dimensions of the
71
- hidden layers. The first hidden dimension will be used as the size
72
- for gene embedding.
73
- adj_dropout (float): A single number between 0 and 1 specifying the
74
- percentage of values in the adjacency matrix that are dropped
75
- during training.
76
- init_coef (int): Coefficient to multiply with gene regulation norm
77
- (1/(n_gene - 1)) to initialize the adjacency matrix.
65
+ n_gene (int): Number of genes.
66
+ time_dim (int): Dimension of time step embedding.
67
+ n_celltype (int): Number of expected cell types. If it is not provided,
68
+ there would be no celltype embedding. Default is None.
69
+ celltype_dim (int): Dimension of cell type embedding. Default: 4.
70
+ hidden_dims (list[int]): List of integers for the dimensions of the
71
+ hidden layers. The first hidden dimension will be used as the size
72
+ for gene embedding. Default: [16, 16, 16].
73
+ adj_dropout (float): A single number between 0 and 1 specifying the
74
+ percentage of values in the adjacency matrix that are dropped
75
+ during training. Default: 0.3.
76
+ init_coef (int): Coefficient to multiply with gene regulation norm
77
+ (1/(n_gene - 1)) to initialize the adjacency matrix. Default: 5.
78
78
  """
79
79
  def __init__(
80
80
  self, n_gene, time_dim,
@@ -92,12 +92,16 @@ class RegDiffusion(nn.Module):
92
92
 
93
93
  adj_A = torch.ones(n_gene, n_gene) * self.gene_reg_norm * init_coef
94
94
  self.adj_A = nn.Parameter(adj_A, requires_grad =True, )
95
- self.sampled_adj_row_nonparam = nn.Parameter(
96
- torch.randint(0, n_gene, size=(10000,)),
97
- requires_grad=False)
98
- self.sampled_adj_col_nonparam = nn.Parameter(
99
- torch.randint(0, n_gene, size=(10000,)),
100
- requires_grad=False)
95
+ # Integer index tensors, not learnable weights. Registered as buffers
96
+ # so they stay out of `parameters()` while keeping their state_dict
97
+ # keys (the `_nonparam` suffix is vestigial, kept for checkpoint
98
+ # compatibility).
99
+ self.register_buffer(
100
+ 'sampled_adj_row_nonparam',
101
+ torch.randint(0, n_gene, size=(10000,)))
102
+ self.register_buffer(
103
+ 'sampled_adj_col_nonparam',
104
+ torch.randint(0, n_gene, size=(10000,)))
101
105
 
102
106
  self.time_mlp = nn.Sequential(
103
107
  SinusoidalPositionEmbeddings(time_dim),
@@ -144,6 +148,26 @@ class RegDiffusion(nn.Module):
144
148
  adj = self.get_adj_().detach().cpu().numpy() / self.gene_reg_norm
145
149
  return adj.astype(np.float16)
146
150
 
151
+ def get_sparse_loss(self):
152
+ """L1 sparsity penalty: mean absolute value of the off-diagonal,
153
+ soft-thresholded adjacency entries.
154
+
155
+ ``abs`` is required. Soft thresholding preserves sign, so a plain mean
156
+ of signed values would be *reduced* by making inhibitory (negative)
157
+ edges more negative -- the opposite of a sparsity penalty. In practice
158
+ negative entries do not survive thresholding (they land in the
159
+ ``|x| < tau`` dead zone, where the output and its gradient are both
160
+ zero), so this matches the previous signed mean on real runs; it is
161
+ corrected here so the penalty is right by construction rather than by
162
+ accident.
163
+
164
+ The mean is taken over the n*(n-1) off-diagonal entries, since
165
+ ``get_adj_`` masks the diagonal to zero, so this agrees with
166
+ ``RegDiffusionME.get_sparse_loss``, its sampled approximation.
167
+ """
168
+ n = self.n_gene
169
+ return self.get_adj_().abs().sum() / (n * (n - 1))
170
+
147
171
  @torch.no_grad()
148
172
  def get_sampled_adj_(self):
149
173
  return self.get_adj_()[
@@ -45,19 +45,19 @@ class RegDiffusionME(nn.Module):
45
45
  The model architecture and inference behavior are identical to RegDiffusion.
46
46
 
47
47
  Args:
48
- n_genes (int): Number of Genes
49
- time_dim (int): Dimension of time step embedding
48
+ n_gene (int): Number of genes.
49
+ time_dim (int): Dimension of time step embedding.
50
50
  n_celltype (int): Number of expected cell types. If it is not provided,
51
- there would be no celltype embedding. Default is None.
52
- celltype_dim (int): Dimension of cell types
53
- hidden_dims (list[int]): List of integer for the dimensions of the
54
- hidden layers. The first hidden dimension will be used as the size
55
- for gene embedding.
51
+ there would be no celltype embedding. Default is None.
52
+ celltype_dim (int): Dimension of cell type embedding. Default: 4.
53
+ hidden_dims (list[int]): List of integers for the dimensions of the
54
+ hidden layers. The first hidden dimension will be used as the size
55
+ for gene embedding. Default: [16, 16, 16].
56
56
  adj_dropout (float): A single number between 0 and 1 specifying the
57
- percentage of values in the adjacency matrix that are dropped
58
- during training.
57
+ percentage of values in the adjacency matrix that are dropped
58
+ during training. Default: 0.3.
59
59
  init_coef (int): Coefficient to multiply with gene regulation norm
60
- (1/(n_gene - 1)) to initialize the adjacency matrix.
60
+ (1/(n_gene - 1)) to initialize the adjacency matrix. Default: 5.
61
61
  """
62
62
  def __init__(
63
63
  self, n_gene, time_dim,
@@ -75,12 +75,16 @@ class RegDiffusionME(nn.Module):
75
75
 
76
76
  adj_A = torch.ones(n_gene, n_gene) * self.gene_reg_norm * init_coef
77
77
  self.adj_A = nn.Parameter(adj_A, requires_grad =True, )
78
- self.sampled_adj_row_nonparam = nn.Parameter(
79
- torch.randint(0, n_gene, size=(10000,)),
80
- requires_grad=False)
81
- self.sampled_adj_col_nonparam = nn.Parameter(
82
- torch.randint(0, n_gene, size=(10000,)),
83
- requires_grad=False)
78
+ # Integer index tensors, not learnable weights. Registered as buffers
79
+ # so they stay out of `parameters()` while keeping their state_dict
80
+ # keys (the `_nonparam` suffix is vestigial, kept for checkpoint
81
+ # compatibility).
82
+ self.register_buffer(
83
+ 'sampled_adj_row_nonparam',
84
+ torch.randint(0, n_gene, size=(10000,)))
85
+ self.register_buffer(
86
+ 'sampled_adj_col_nonparam',
87
+ torch.randint(0, n_gene, size=(10000,)))
84
88
 
85
89
  self.time_mlp = nn.Sequential(
86
90
  SinusoidalPositionEmbeddings(time_dim),
@@ -127,19 +131,34 @@ class RegDiffusionME(nn.Module):
127
131
  adj = self.get_adj_().detach().cpu().numpy() / self.gene_reg_norm
128
132
  return adj.astype(np.float16)
129
133
 
130
- def get_sampled_sparse_loss(self):
134
+ def get_sparse_loss(self):
131
135
  """Compute mean absolute value of sampled adj entries for sparse loss.
132
136
 
137
+ Memory-efficient approximation of ``RegDiffusion.get_sparse_loss``.
133
138
  Instead of materializing the full (n_gene, n_gene) get_adj_() matrix,
134
139
  this samples 10,000 random entries, applies soft thresholding, and
135
140
  returns the mean. This avoids creating 3 additional (n,n) tensors
136
141
  that the full get_adj_() would require.
142
+
143
+ Diagonal (self-loop) samples are excluded so this matches the base
144
+ model, whose ``get_adj_`` masks the diagonal to zero.
137
145
  """
138
- sampled_vals = self.adj_A[
139
- self.sampled_adj_row_nonparam, self.sampled_adj_col_nonparam
140
- ]
146
+ rows = self.sampled_adj_row_nonparam
147
+ cols = self.sampled_adj_col_nonparam
148
+ sampled_vals = self.adj_A[rows, cols]
141
149
  sampled_clean = self.soft_thresholding(sampled_vals, self.gene_reg_norm/2)
142
- return sampled_clean.abs().mean()
150
+ off_diag = (rows != cols).to(sampled_clean.dtype)
151
+ return (sampled_clean.abs() * off_diag).sum() / off_diag.sum()
152
+
153
+ def get_sampled_sparse_loss(self):
154
+ """
155
+ Deprecated API. Use get_sparse_loss instead.
156
+ """
157
+ import warnings
158
+ warnings.warn(
159
+ "get_sampled_sparse_loss is deprecated, use get_sparse_loss instead",
160
+ DeprecationWarning)
161
+ return self.get_sparse_loss()
143
162
 
144
163
  @torch.no_grad()
145
164
  def get_sampled_adj_(self):
regdiffusion/trainer.py CHANGED
@@ -14,6 +14,17 @@ from .evaluator import GRNEvaluator
14
14
  from .logger import LightLogger
15
15
  import matplotlib.pyplot as plt
16
16
  import warnings
17
+ import random
18
+
19
+ def set_seed(seed):
20
+ """Set random seeds for reproducibility across PyTorch, NumPy, and CUDA."""
21
+ random.seed(seed)
22
+ np.random.seed(seed)
23
+ torch.manual_seed(seed)
24
+ if torch.cuda.is_available():
25
+ torch.cuda.manual_seed_all(seed)
26
+ torch.backends.cudnn.deterministic = True
27
+ torch.backends.cudnn.benchmark = False
17
28
 
18
29
  def linear_beta_schedule(timesteps, start_noise, end_noise):
19
30
  scale = 1000 / timesteps
@@ -82,7 +93,7 @@ class RegDiffusionTrainer:
82
93
  full dense normalized matrix is never materialized.
83
94
  cell_types (np.ndarray): (Optional) 1D integer array for cell type. If
84
95
  you have labels in your cell type, you need to convert them to
85
- interge. Default is None.
96
+ integer. Default is None.
86
97
  T (int): Total number of diffusion steps. Default: 5,000
87
98
  start_noise (float): Minimal noise level (beta) to be added. Default:
88
99
  0.0001
@@ -91,7 +102,7 @@ class RegDiffusionTrainer:
91
102
  time_dim (int): Dimension size for the time embedding. Default: 64.
92
103
  celltype_dim (int): Dimension size for the cell type embedding.
93
104
  Default: 4.
94
- hidden_dim (list): Dimension sizes for the feature learning layers. We
105
+ hidden_dims (list): Dimension sizes for the feature learning layers. We
95
106
  use the size of the first layer as the dimension for gene embeddings
96
107
  as well. Default: [16, 16, 16].
97
108
  init_coef (int): A coefficent to control the value to initialize the
@@ -119,9 +130,9 @@ class RegDiffusionTrainer:
119
130
  to run this model on Apple's MPS chips. Default is "cuda" but if
120
131
  you only has CPU, it will switch back to CPU.
121
132
  compile (boolean): Whether to compile the model before training.
122
- Compile the model is a good idea on large dataset and ofter improves
123
- inference speed when it works. For smaller dataset, eager execution
124
- if often good enough.
133
+ Compile the model is a good idea on large dataset and often improves
134
+ inference speed when it works. For smaller dataset, eager execution
135
+ is often good enough.
125
136
  evaluator (GRNEvaluator): (Optional) A defined GRNEvaluator if ground
126
137
  truth data is available. Evaluation will be done every 100 steps by
127
138
  default but you can change this setting through the eval_on_n_steps
@@ -145,6 +156,8 @@ class RegDiffusionTrainer:
145
156
  for soft thresholding (saves boolean masks instead of float32
146
157
  tensors) and sampled sparse loss (avoids materializing full
147
158
  n_gene x n_gene matrix for L1 regularization). Default: False.
159
+ seed (int): Random seed for full reproducibility. When set, all
160
+ sources of randomness are seeded. Default: None (non-deterministic).
148
161
  """
149
162
  def __init__(
150
163
  self, exp_array, cell_types=None,
@@ -159,14 +172,22 @@ class RegDiffusionTrainer:
159
172
  device='cuda', compile=False,
160
173
  evaluator=None, eval_on_n_steps=100, logger=None,
161
174
  gradient_accumulation=False, use_amp=False,
162
- memory_efficient=False
175
+ memory_efficient=False,
176
+ seed=None
163
177
  ):
164
178
  hp = locals()
165
179
  del hp['exp_array']
166
180
  del hp['cell_types']
167
181
  del hp['logger']
168
182
  self.hp = hp
169
-
183
+
184
+ # Seed for reproducibility
185
+ if seed is not None:
186
+ set_seed(seed)
187
+ self._sampler_generator = torch.Generator()
188
+ if seed is not None:
189
+ self._sampler_generator.manual_seed(seed)
190
+
170
191
  if device == 'mps':
171
192
  raise Exception("We noticed unreliable training behavior on",
172
193
  "Apple's silicon. Consider using other devices.")
@@ -239,8 +260,7 @@ class RegDiffusionTrainer:
239
260
  if name.endswith('adj_A'):
240
261
  adj_params.append(param)
241
262
  else:
242
- if not name.endswith('_nonparam'):
243
- non_adj_params.append(param)
263
+ non_adj_params.append(param)
244
264
  self.opt = torch.optim.Adam(
245
265
  [{'params': non_adj_params}, {'params': adj_params}],
246
266
  lr=lr_nn,
@@ -297,7 +317,8 @@ class RegDiffusionTrainer:
297
317
  self.train_dataset = TensorDataset(
298
318
  x_tensor_train, celltype_tensor_train)
299
319
  train_sampler = torch.utils.data.RandomSampler(
300
- self.train_dataset, replacement=True, num_samples=batch_size)
320
+ self.train_dataset, replacement=True, num_samples=batch_size,
321
+ generator=self._sampler_generator)
301
322
  self.train_dataloader = DataLoader(
302
323
  self.train_dataset,
303
324
  sampler=train_sampler,
@@ -389,7 +410,8 @@ class RegDiffusionTrainer:
389
410
  cell_min_f32, cell_range_f32, gene_mean, gene_std,
390
411
  train_indices)
391
412
  train_sampler = torch.utils.data.RandomSampler(
392
- self.train_dataset, replacement=True, num_samples=batch_size)
413
+ self.train_dataset, replacement=True, num_samples=batch_size,
414
+ generator=self._sampler_generator)
393
415
  self.train_dataloader = DataLoader(
394
416
  self.train_dataset,
395
417
  sampler=train_sampler,
@@ -409,12 +431,17 @@ class RegDiffusionTrainer:
409
431
  @torch.no_grad()
410
432
  def forward_pass(self, x_0, t):
411
433
  """
412
- Forward diffusion process
413
-
434
+ Forward diffusion process. Adds noise to the input according to the
435
+ diffusion schedule at the given timesteps.
436
+
414
437
  Args:
415
- x_0 (torch.FloatTensor): Torch tensor for expression data. Rows are
416
- cells and columns are genes
438
+ x_0 (torch.FloatTensor): Torch tensor for expression data. Rows
439
+ are cells and columns are genes.
417
440
  t (torch.LongTensor): Torch tensor for diffusion time steps.
441
+
442
+ Returns:
443
+ tuple: (x_t, noise) where x_t is the noised input and noise is
444
+ the sampled Gaussian noise that was added.
418
445
  """
419
446
  noise = torch.randn_like(x_0)
420
447
  mean_coef = self.mean_schedule.gather(dim=-1, index=t)
@@ -423,10 +450,18 @@ class RegDiffusionTrainer:
423
450
  return x_t, noise
424
451
 
425
452
  def train(self, n_steps=None):
453
+ """
454
+ Train the model. Dispatches to gradient accumulation or normal
455
+ training based on the ``gradient_accumulation`` setting.
456
+
457
+ Args:
458
+ n_steps (int): Number of steps to train. If not provided, uses
459
+ the n_steps specified during initialization.
460
+ """
426
461
  if self.hp['gradient_accumulation']:
427
- self._train_with_gradient_accumulation(n_steps=None)
462
+ self._train_with_gradient_accumulation(n_steps=n_steps)
428
463
  else:
429
- self._train_normal(n_steps=None)
464
+ self._train_normal(n_steps=n_steps)
430
465
 
431
466
 
432
467
  def _train_normal(self, n_steps=None):
@@ -435,9 +470,9 @@ class RegDiffusionTrainer:
435
470
 
436
471
  Args:
437
472
  n_steps (int): Number of steps to train. If not provided, it will
438
- train the model by the n_steps sepcified in class
473
+ train the model by the n_steps specified in class
439
474
  initialization. Please read our paper to see how to identify
440
- the converge point.
475
+ the convergence point.
441
476
  """
442
477
  start_time = datetime.now()
443
478
  eval_steps = self.hp['eval_on_n_steps']
@@ -445,7 +480,9 @@ class RegDiffusionTrainer:
445
480
  n_steps = self.hp['n_steps']
446
481
  sampled_adj = self.model.get_sampled_adj_()
447
482
  with tqdm(range(n_steps)) as pbar:
448
- for epoch in pbar:
483
+ for epoch in pbar:
484
+ if self.hp['seed'] is not None:
485
+ torch.manual_seed(self.hp['seed'] + epoch)
449
486
  epoch_loss = []
450
487
  for step, batch in enumerate(self.train_dataloader):
451
488
  x_0, ct = batch
@@ -467,11 +504,13 @@ class RegDiffusionTrainer:
467
504
  loss_ = F.mse_loss(noise, z, reduction='none')
468
505
  loss = loss_.mean()
469
506
 
470
- if hasattr(self.model, 'get_sampled_sparse_loss'):
471
- loss_sparse = self.model.get_sampled_sparse_loss() * self.hp['sparse_loss_coef']
472
- else:
473
- adj_m = self.model.get_adj_()
474
- loss_sparse = adj_m.mean() * self.hp['sparse_loss_coef']
507
+ # Only computed past the warmup window, where it is
508
+ # actually applied.
509
+ if epoch > 10:
510
+ loss_sparse = (
511
+ self.model.get_sparse_loss()
512
+ * self.hp['sparse_loss_coef']
513
+ )
475
514
 
476
515
  if epoch > 10:
477
516
  loss = loss + loss_sparse
@@ -495,6 +534,8 @@ class RegDiffusionTrainer:
495
534
  for k in eval_result.keys():
496
535
  epoch_log[k] = eval_result[k]
497
536
  if self.hp['train_split'] < 1:
537
+ if self.hp['seed'] is not None:
538
+ torch.manual_seed(self.hp['seed'] + n_steps + epoch)
498
539
  with torch.no_grad():
499
540
  val_epoch_loss = []
500
541
  for step, batch in enumerate(self.val_dataloader):
@@ -546,6 +587,8 @@ class RegDiffusionTrainer:
546
587
 
547
588
  with tqdm(range(n_steps)) as pbar:
548
589
  for step_idx in pbar:
590
+ if self.hp['seed'] is not None:
591
+ torch.manual_seed(self.hp['seed'] + step_idx)
549
592
  # Fetch a single batch for the current step
550
593
  x_0_batch, ct_batch = next(iter(self.train_dataloader))
551
594
  x_0_batch = x_0_batch.to(self.device)
@@ -588,19 +631,19 @@ class RegDiffusionTrainer:
588
631
  scaled_loss = loss_sample / batch_size
589
632
  scaled_loss.backward()
590
633
 
591
- # Handle sparse loss once per effective batch
592
- with torch.autocast(
593
- device_type=self.amp_device_type,
594
- dtype=torch.bfloat16,
595
- enabled=self.use_amp
596
- ):
597
- if hasattr(self.model, 'get_sampled_sparse_loss'):
598
- loss_sparse = self.model.get_sampled_sparse_loss() * self.hp['sparse_loss_coef']
599
- else:
600
- adj_m = self.model.get_adj_()
601
- loss_sparse = adj_m.mean() * self.hp['sparse_loss_coef']
602
-
634
+ # Handle sparse loss once per effective batch. Only computed
635
+ # past the warmup window, where it is actually applied.
603
636
  if step_idx > 10:
637
+ with torch.autocast(
638
+ device_type=self.amp_device_type,
639
+ dtype=torch.bfloat16,
640
+ enabled=self.use_amp
641
+ ):
642
+ loss_sparse = (
643
+ self.model.get_sparse_loss()
644
+ * self.hp['sparse_loss_coef']
645
+ )
646
+
604
647
  loss_sparse.backward()
605
648
 
606
649
  # Perform the optimizer step after accumulating all gradients
@@ -627,6 +670,8 @@ class RegDiffusionTrainer:
627
670
  epoch_log[k] = eval_result[k]
628
671
 
629
672
  if self.hp['train_split'] < 1:
673
+ if self.hp['seed'] is not None:
674
+ torch.manual_seed(self.hp['seed'] + n_steps + step_idx)
630
675
  with torch.no_grad():
631
676
  val_epoch_loss = []
632
677
  for step, batch in enumerate(self.val_dataloader):
@@ -680,28 +725,33 @@ class RegDiffusionTrainer:
680
725
 
681
726
  def get_grn(self, gene_names, tf_names=None, top_gene_percentile=None):
682
727
  """
683
- Obtain a GRN object. You need to provide the genes names.
728
+ Obtain a GRN object. You need to provide the gene names.
684
729
 
685
730
  Args:
686
- gene_names (np.ndarray): An array of names of all genes. The order
731
+ gene_names (np.ndarray): An array of names of all genes. The order
687
732
  of genes should be the same as the order used in your expression
688
733
  table.
689
- tf_names (np.ndarray):An array of names of all transcriptional
690
- factors. The order of genes should be the same as the order
691
- used in your expression table.
692
- top_gene_percentile (int): If provided, we will set the value on
693
- weak links to be zero. It is useful if you want to save the
694
- regulatory relationship in a GRN object as a sparse matrix.
695
-
734
+ tf_names (np.ndarray): An array of names of all transcriptional
735
+ factors. The order should be the same as the order used in
736
+ your expression table.
737
+ top_gene_percentile (int): If provided, we will set the value on
738
+ weak links to be zero. It is useful if you want to save the
739
+ regulatory relationship in a GRN object as a sparse matrix.
740
+
741
+ Returns:
742
+ GRN: A GRN object containing the inferred regulatory network.
696
743
  """
697
744
  adj = self.model.get_adj()
698
745
  return GRN(adj, gene_names, tf_names, top_gene_percentile)
699
746
 
700
747
  def get_adj(self):
701
748
  """
702
- Obtain the adjacency matrix. The values in this adjacency matix has
749
+ Obtain the adjacency matrix. The values in this adjacency matrix have
703
750
  been scaled using regulatory norm. You may expect strong links to go
704
- beyond 5 or 10 in most cases.
751
+ beyond 5 or 10 in most cases.
752
+
753
+ Returns:
754
+ np.ndarray: 2D adjacency matrix of shape (n_gene, n_gene).
705
755
  """
706
756
  return self.model.get_adj()
707
757
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: regdiffusion
3
- Version: 0.2.2
3
+ Version: 0.2.3
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>
@@ -0,0 +1,21 @@
1
+ regdiffusion/__init__.py,sha256=0vuZ57xw8Bhf91fcCfXPNY_oLmrHtvcBCjxOBMqo3EU,444
2
+ regdiffusion/cli.py,sha256=E2grkvRagj5P2PGT7Yv6fXOTX5IvzrXgb9Qth2Nv_js,2982
3
+ regdiffusion/evaluator.py,sha256=RYJL2c5dfVB4hXGUbI4V5OtxPMm81dlqY-uhGFzSmkU,3666
4
+ regdiffusion/grn.py,sha256=RH1c6VrxHr8P7vFDrbvS_aNh6VeOd8F9yjpH5qoANp0,25596
5
+ regdiffusion/logger.py,sha256=ldo0tT2wK7GiHaxx9OgtEGoW8NIAPVH2ZMim6GI2ZWY,6378
6
+ regdiffusion/trainer.py,sha256=KFVWEB1c5_wVm84wXAdr-K6evnny7t6C-8UgtrCW8mA,34081
7
+ regdiffusion/data/__init__.py,sha256=G-eDyYgjY9xqu9v6mN7Py110Lz8O6cDuc4cMAFEecYQ,366
8
+ regdiffusion/data/beeline.py,sha256=RGuvIJ6hvAI7IWAP4-4qIiO10fakX7tggjDPDY2rl9w,3718
9
+ regdiffusion/data/microglia.py,sha256=KhD07oZliMKZ2PaxdIZRyxrRHEQtr5kVPxIVr2eIOxo,4291
10
+ regdiffusion/data/utils.py,sha256=jF95ueUyzI9fhJlJQ3SkXLOGfibT6YhqZqkxbVfPAVw,572
11
+ regdiffusion/models/__init__.py,sha256=Bo5-RKjQLSJZ2P6MnKR8O_aoHjKgVAF0J1-9ULhkcxw,83
12
+ regdiffusion/models/regdiffusion.py,sha256=3-avc-IuzjvK6hSWF1D2adF96HjoB9-VWuMiyUqpC8s,7785
13
+ regdiffusion/models/regdiffusion_me.py,sha256=_IkW6WOC-RQk9f8laRXGQXsGtxHq13jYqD6XIi7w9HI,7244
14
+ regdiffusion/plot/__init__.py,sha256=mXJbpYBc2-noIWrQVx-s_ka0eYsKByj4l_OZYKwUGBU,277
15
+ regdiffusion/plot/pyvis.py,sha256=ajM1lr2SX1XI06VdgPEiLxo9pw8wStRI0B3McIa0mO4,4581
16
+ regdiffusion/plot/static.py,sha256=bhDB-xB8C-3ZDUKoDJaoLQc0EqEXYgcO9a-sY_Uvpyo,11776
17
+ regdiffusion-0.2.3.dist-info/entry_points.txt,sha256=A737tP1RgN6tYHktWvmZByLxaW__S6-LE7mRTn0PQF0,54
18
+ regdiffusion-0.2.3.dist-info/licenses/LICENSE,sha256=jzkY6g_rbcJvt5Ehsqxr6IazE2Nj55hBtW4hkb6QMmw,11341
19
+ regdiffusion-0.2.3.dist-info/WHEEL,sha256=Dyt6SBfaasWElUrURkknVFAZDHSTwxg3PaTza7RSbkY,100
20
+ regdiffusion-0.2.3.dist-info/METADATA,sha256=v9Fjjuh5QT5HHLy3PhFwXlBaUoGo9WLLIi_q-QdrI10,4621
21
+ regdiffusion-0.2.3.dist-info/RECORD,,
@@ -1,21 +0,0 @@
1
- regdiffusion/__init__.py,sha256=iwbYh6AlX9yldwUp3X_7gfgUNzBSAGBcSoe39HV3zoQ,423
2
- regdiffusion/cli.py,sha256=qUI7W1qDuTGAJvsGVJxJDw-5rWATR5WmzfWF9A7zPSI,2810
3
- regdiffusion/evaluator.py,sha256=bfuKVtbYIXcmUPIRXz4oBVahM3-wsSodXTTmsbbzJvQ,3350
4
- regdiffusion/grn.py,sha256=NJSE3-wpMuyjbwvtQIkfTWK1tLikdvvwSKU4d7uSf1Q,25822
5
- regdiffusion/logger.py,sha256=3l1fPbtT2mGM94cv_8NlbKuowzeajLaBoIDgKf_UR6M,5906
6
- regdiffusion/trainer.py,sha256=XQb7ABzl-s-oVElNUhrdfyHu5iCN4pnAP5giFlqt5dI,32126
7
- regdiffusion/data/__init__.py,sha256=G-eDyYgjY9xqu9v6mN7Py110Lz8O6cDuc4cMAFEecYQ,366
8
- regdiffusion/data/beeline.py,sha256=ULETEb7rv7h5OUOQRguMIbF0WBDN5F32TcXGRerM9D8,3697
9
- regdiffusion/data/microglia.py,sha256=B-19H8QAUHYMgv1K6i1n3i1SbMRxM7XZ3CE4LFPeVFA,4278
10
- regdiffusion/data/utils.py,sha256=WQXyYq6i9pv5bOoYtVvI1nstPzhMgyQDOjPs7Fp_eRA,567
11
- regdiffusion/models/__init__.py,sha256=Bo5-RKjQLSJZ2P6MnKR8O_aoHjKgVAF0J1-9ULhkcxw,83
12
- regdiffusion/models/regdiffusion.py,sha256=X_B4aD1M7COlMvgJQupaouPY-YaP9iy-3JTI6YAkylM,6469
13
- regdiffusion/models/regdiffusion_me.py,sha256=86Wm7zC-526Kf0KCEN-1gY13kJ-Kz3t5w0n1bJTe39c,6301
14
- regdiffusion/plot/__init__.py,sha256=mXJbpYBc2-noIWrQVx-s_ka0eYsKByj4l_OZYKwUGBU,277
15
- regdiffusion/plot/pyvis.py,sha256=ajM1lr2SX1XI06VdgPEiLxo9pw8wStRI0B3McIa0mO4,4581
16
- regdiffusion/plot/static.py,sha256=bhDB-xB8C-3ZDUKoDJaoLQc0EqEXYgcO9a-sY_Uvpyo,11776
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,,