regdiffusion 0.2.2__py2.py3-none-any.whl → 0.2.4__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 +3 -3
- regdiffusion/cli.py +7 -1
- regdiffusion/data/beeline.py +9 -9
- regdiffusion/data/microglia.py +5 -6
- regdiffusion/data/utils.py +1 -1
- regdiffusion/evaluator.py +10 -0
- regdiffusion/grn.py +75 -60
- regdiffusion/logger.py +13 -0
- regdiffusion/models/regdiffusion.py +43 -19
- regdiffusion/models/regdiffusion_me.py +40 -21
- regdiffusion/plot/__init__.py +2 -2
- regdiffusion/plot/interactive.py +104 -0
- regdiffusion/trainer.py +98 -48
- {regdiffusion-0.2.2.dist-info → regdiffusion-0.2.4.dist-info}/METADATA +29 -11
- regdiffusion-0.2.4.dist-info/RECORD +21 -0
- regdiffusion/plot/pyvis.py +0 -108
- regdiffusion-0.2.2.dist-info/RECORD +0 -21
- {regdiffusion-0.2.2.dist-info → regdiffusion-0.2.4.dist-info}/WHEEL +0 -0
- {regdiffusion-0.2.2.dist-info → regdiffusion-0.2.4.dist-info}/entry_points.txt +0 -0
- {regdiffusion-0.2.2.dist-info → regdiffusion-0.2.4.dist-info}/licenses/LICENSE +0 -0
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(
|
regdiffusion/data/beeline.py
CHANGED
|
@@ -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
|
-
|
|
51
|
-
|
|
52
|
-
benchmark_data (str): Benchmark datasets. Choose among "hESC", "hHep",
|
|
53
|
-
|
|
54
|
-
benchmark_setting (str): Benchmark settings. Choose among "500_STRING",
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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.
|
regdiffusion/data/microglia.py
CHANGED
|
@@ -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
|
-
|
|
30
|
-
|
|
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
|
-
|
|
77
|
-
|
|
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)
|
regdiffusion/data/utils.py
CHANGED
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,51 +1,50 @@
|
|
|
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
|
|
7
7
|
import h5py
|
|
8
|
-
from typing import List, Dict, Union
|
|
8
|
+
from typing import List, Dict, Union, Optional
|
|
9
9
|
import concurrent.futures
|
|
10
|
-
from .plot import
|
|
10
|
+
from .plot import plot_lightgraph
|
|
11
11
|
|
|
12
12
|
class GRN:
|
|
13
|
-
"""
|
|
14
|
-
|
|
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
|
|
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
|
|
26
|
-
the GRN class. You can load a saved GRN object using the
|
|
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
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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
|
|
38
|
-
and
|
|
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
|
-
|
|
44
|
-
tf_names (np.ndarray, optional): A 1D numpy array with all the TF
|
|
45
|
-
|
|
46
|
-
top_gene_percentile (int): If this value is set, only the top k
|
|
47
|
-
|
|
48
|
-
|
|
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
|
-
|
|
69
|
-
|
|
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
|
|
@@ -118,9 +118,14 @@ class GRN:
|
|
|
118
118
|
) for g in list(self.gene_names)]
|
|
119
119
|
|
|
120
120
|
all_edges = [
|
|
121
|
-
future.result() for future in
|
|
121
|
+
future.result() for future in
|
|
122
122
|
concurrent.futures.as_completed(futures)]
|
|
123
|
-
|
|
123
|
+
edgelist = pd.concat(all_edges)
|
|
124
|
+
# Top-k selection returns k entries per gene even when fewer than k
|
|
125
|
+
# are non-zero, so a gene whose edges were all zeroed out (say by
|
|
126
|
+
# remove_weak_edges) would otherwise come back with phantom edges.
|
|
127
|
+
edgelist = edgelist[edgelist.weight != 0]
|
|
128
|
+
return edgelist.reset_index(drop=True)
|
|
124
129
|
|
|
125
130
|
def get_edgelist(self, k: int = 100, workers: int = 4) -> pd.DataFrame:
|
|
126
131
|
"""
|
|
@@ -137,7 +142,7 @@ class GRN:
|
|
|
137
142
|
selected gene. It is slightly faster than the dataframe version.
|
|
138
143
|
|
|
139
144
|
Args:
|
|
140
|
-
|
|
145
|
+
gene (str): A single gene to inspect.
|
|
141
146
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
142
147
|
"""
|
|
143
148
|
gene_idx = self.gene_indices[gene]
|
|
@@ -162,7 +167,7 @@ class GRN:
|
|
|
162
167
|
The dataframe will have 3 columns: `source`, `target`, `weight`.
|
|
163
168
|
|
|
164
169
|
Args:
|
|
165
|
-
|
|
170
|
+
gene (str): A single gene to inspect.
|
|
166
171
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
167
172
|
"""
|
|
168
173
|
source_indices = self.extract_node_sources_as_indices(gene, k)
|
|
@@ -182,7 +187,7 @@ class GRN:
|
|
|
182
187
|
selected gene. It is slightly faster than the dataframe version.
|
|
183
188
|
|
|
184
189
|
Args:
|
|
185
|
-
|
|
190
|
+
gene (str): A single gene to inspect.
|
|
186
191
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
187
192
|
"""
|
|
188
193
|
gene_idx = self.tf_indices[gene]
|
|
@@ -207,7 +212,7 @@ class GRN:
|
|
|
207
212
|
The dataframe will have 3 columns: `source`, `target`, `weight`.
|
|
208
213
|
|
|
209
214
|
Args:
|
|
210
|
-
|
|
215
|
+
gene (str): A single gene to inspect.
|
|
211
216
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
212
217
|
"""
|
|
213
218
|
target_indices = self.extract_node_targets_as_indices(gene, k)
|
|
@@ -227,7 +232,7 @@ class GRN:
|
|
|
227
232
|
It is slightly faster than the dataframe version.
|
|
228
233
|
|
|
229
234
|
Args:
|
|
230
|
-
|
|
235
|
+
gene (str): A single gene to inspect.
|
|
231
236
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
232
237
|
"""
|
|
233
238
|
gene_idx = self.gene_indices[gene]
|
|
@@ -261,7 +266,7 @@ class GRN:
|
|
|
261
266
|
The dataframe will have 3 columns: `source`, `target`, `weight`.
|
|
262
267
|
|
|
263
268
|
Args:
|
|
264
|
-
|
|
269
|
+
gene (str): A single gene to inspect.
|
|
265
270
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
266
271
|
"""
|
|
267
272
|
neighbor_indices = self.extract_node_neighbors_as_indices(gene, k)
|
|
@@ -294,10 +299,10 @@ class GRN:
|
|
|
294
299
|
is defined in a similar way but smaller.
|
|
295
300
|
|
|
296
301
|
Args:
|
|
297
|
-
|
|
302
|
+
gene (str): A single gene to inspect.
|
|
298
303
|
k (int): Top-k edges to inspect on each node. If k=-1, export all
|
|
299
304
|
hops (str): Number of hops to explore. We can either do a "2.5" or
|
|
300
|
-
"1.5" hop
|
|
305
|
+
"1.5" hop traversal around selected genes. Default is "2.5".
|
|
301
306
|
"""
|
|
302
307
|
if isinstance(genes, str):
|
|
303
308
|
genes = [genes]
|
|
@@ -357,34 +362,40 @@ class GRN:
|
|
|
357
362
|
|
|
358
363
|
def visualize_local_neighborhood(
|
|
359
364
|
self, genes: Union[str, List[str]], k: int = 20, hops: str = "2.5",
|
|
360
|
-
edge_widths: List[
|
|
361
|
-
plot_engine: str = '
|
|
365
|
+
edge_widths: Optional[List[float]] = None,
|
|
366
|
+
plot_engine: str = 'lightgraph', *args, **kwargs):
|
|
362
367
|
"""
|
|
363
|
-
Generate
|
|
364
|
-
(2-hop) around selected gene(s).
|
|
368
|
+
Generate an interactive network visualization of the local
|
|
369
|
+
neighborhood (2-hop) around selected gene(s).
|
|
365
370
|
|
|
366
371
|
Args:
|
|
367
|
-
|
|
372
|
+
gene (str): A single gene to inspect.
|
|
368
373
|
k (int): Top-k edges to inspect on each node. If k=-1, export all.
|
|
369
374
|
hops (str): Number of hops of the neighborhood to explore. Default
|
|
370
|
-
is "2.5".
|
|
371
|
-
edge_widths (List):
|
|
372
|
-
|
|
375
|
+
is "2.5".
|
|
376
|
+
edge_widths (List): Deprecated and ignored. Edge width is now
|
|
377
|
+
scaled by the absolute regulatory strength of each edge rather
|
|
378
|
+
than by hop level.
|
|
373
379
|
plot_engine (str): Choose which network plot engine to use. Default
|
|
374
|
-
is "
|
|
375
|
-
**kwargs: Keyword arguments to be passed to ``
|
|
376
|
-
"""
|
|
380
|
+
is "lightgraph".
|
|
381
|
+
**kwargs: Keyword arguments to be passed to ``plot_lightgraph``.
|
|
382
|
+
"""
|
|
383
|
+
if edge_widths is not None:
|
|
384
|
+
import warnings
|
|
385
|
+
warnings.warn(
|
|
386
|
+
"edge_widths is deprecated and ignored. Edge width is now "
|
|
387
|
+
"scaled by absolute regulatory strength.",
|
|
388
|
+
DeprecationWarning
|
|
389
|
+
)
|
|
377
390
|
if isinstance(genes, str):
|
|
378
391
|
genes = [genes]
|
|
379
392
|
local_adj_table = self.extract_local_neighborhood(genes, k, hops)
|
|
380
|
-
local_adj_table['edge_width'] = local_adj_table.hop.map(
|
|
381
|
-
lambda x: edge_widths[x])
|
|
382
393
|
|
|
383
|
-
if plot_engine == '
|
|
384
|
-
g =
|
|
385
|
-
pandas_edgelist = local_adj_table,
|
|
394
|
+
if plot_engine == 'lightgraph':
|
|
395
|
+
g = plot_lightgraph(
|
|
396
|
+
pandas_edgelist = local_adj_table,
|
|
386
397
|
star_genes = genes, *args, **kwargs)
|
|
387
|
-
else:
|
|
398
|
+
else:
|
|
388
399
|
raise Exception("Not implemented yet")
|
|
389
400
|
return g
|
|
390
401
|
|
|
@@ -399,7 +410,9 @@ class GRN:
|
|
|
399
410
|
as_sparse (bool): Whether to save as sparse matrix
|
|
400
411
|
"""
|
|
401
412
|
if as_sparse:
|
|
402
|
-
|
|
413
|
+
# scipy.sparse has no float16 support, but the stored data is
|
|
414
|
+
# downcast to float16 below anyway.
|
|
415
|
+
sp_adj = csr_matrix(self.adj_matrix.astype(np.float32))
|
|
403
416
|
if not file_path.endswith('.hdf5'):
|
|
404
417
|
file_path += '.hdf5'
|
|
405
418
|
|
|
@@ -655,6 +668,8 @@ def read_hdf5(file_path: str):
|
|
|
655
668
|
adj_matrix = sparse_dt.toarray().astype(np.float16)
|
|
656
669
|
else:
|
|
657
670
|
adj_matrix = f['adj_matrix']['data'][:]
|
|
658
|
-
|
|
659
|
-
|
|
671
|
+
# h5py hands back bytes for variable-length strings; decode so gene
|
|
672
|
+
# names round-trip as real str and stay joinable against annotations.
|
|
673
|
+
gene_names = f['gene_names'].asstr()[:]
|
|
674
|
+
tf_names = f['tf_names'].asstr()[:]
|
|
660
675
|
return GRN(adj_matrix, gene_names, tf_names)
|
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
|
-
|
|
66
|
-
time_dim (int): Dimension of time step embedding
|
|
67
|
-
n_celltype (int): Number of expected cell types. If it is not provided,
|
|
68
|
-
|
|
69
|
-
celltype_dim (int): Dimension of cell
|
|
70
|
-
hidden_dims (list[int]): List of
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
adj_dropout (float): A single number between 0 and 1 specifying the
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
init_coef (int): Coefficient to multiply with gene regulation norm
|
|
77
|
-
|
|
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
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
-
|
|
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
|
-
|
|
52
|
-
celltype_dim (int): Dimension of cell
|
|
53
|
-
hidden_dims (list[int]): List of
|
|
54
|
-
|
|
55
|
-
|
|
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
|
-
|
|
58
|
-
|
|
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
|
-
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
|
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
|
-
|
|
139
|
-
|
|
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
|
-
|
|
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/plot/__init__.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
from .
|
|
1
|
+
from .interactive import plot_lightgraph
|
|
2
2
|
from .static import (
|
|
3
3
|
plot_network,
|
|
4
4
|
plot_heatmap,
|
|
@@ -7,7 +7,7 @@ from .static import (
|
|
|
7
7
|
)
|
|
8
8
|
|
|
9
9
|
__all__ = [
|
|
10
|
-
'
|
|
10
|
+
'plot_lightgraph',
|
|
11
11
|
'plot_network',
|
|
12
12
|
'plot_heatmap',
|
|
13
13
|
'plot_degree_distribution',
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
from typing import List, Dict, Union, Optional
|
|
3
|
+
|
|
4
|
+
from lightgraph import net_vis, NetworkVisualization
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def plot_lightgraph(
|
|
8
|
+
pandas_edgelist: pd.DataFrame,
|
|
9
|
+
star_genes: List[str] = [],
|
|
10
|
+
node_size: float = 7,
|
|
11
|
+
font_size: float = 5,
|
|
12
|
+
node_color_dict: Optional[Dict[str, str]] = None,
|
|
13
|
+
node_group_dict: Optional[Dict[str, str]] = None,
|
|
14
|
+
node_metric: Optional[Dict[str, float]] = None,
|
|
15
|
+
edge_weight_to_width: bool = True,
|
|
16
|
+
edge_weight_to_opacity: bool = False,
|
|
17
|
+
layout: str = 'force',
|
|
18
|
+
show_arrows: bool = False,
|
|
19
|
+
height: str = "600px",
|
|
20
|
+
**kwargs
|
|
21
|
+
) -> NetworkVisualization:
|
|
22
|
+
"""
|
|
23
|
+
Generate an interactive network visualization given an edge list
|
|
24
|
+
representation of a graph in a data frame.
|
|
25
|
+
|
|
26
|
+
Rendering is done by `lightgraph <https://haozhu233.github.io/lightgraph/>`_,
|
|
27
|
+
which draws on an HTML canvas with viewport culling and therefore stays
|
|
28
|
+
interactive on graphs with thousands of nodes.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
pandas_edgelist (pd.DataFrame): an edge list representation of
|
|
32
|
+
a graph in a pandas data frame. It should at least have columns
|
|
33
|
+
with the name `source` and `target`. An optional `weight` column
|
|
34
|
+
is used to scale edge width and/or opacity.
|
|
35
|
+
star_genes (List): A list of genes to highlight. Highlighted genes are
|
|
36
|
+
drawn at twice the base node size. Note that when
|
|
37
|
+
``node_group_dict`` is provided, group colors take precedence over
|
|
38
|
+
per-node colors, so highlighting shows up as size only.
|
|
39
|
+
node_size (float): Base size for nodes. Default is 7.
|
|
40
|
+
font_size (float): The font size for node labels. Default is 5.
|
|
41
|
+
node_color_dict (dict): A dictionary with keys being the names of
|
|
42
|
+
genes and values being hex color strings.
|
|
43
|
+
node_group_dict (dict): A dictionary with keys being the names of
|
|
44
|
+
genes and values being the group. Pass the string ``'auto'`` to let
|
|
45
|
+
lightgraph detect communities automatically.
|
|
46
|
+
node_metric (dict): A dictionary with keys being the names of genes and
|
|
47
|
+
values being a numeric score (for example degree or PageRank). The
|
|
48
|
+
values are min-max normalized and mapped onto node size.
|
|
49
|
+
edge_weight_to_width (bool): If True, scale edge width by the `weight`
|
|
50
|
+
column. Default is True.
|
|
51
|
+
edge_weight_to_opacity (bool): If True, scale edge opacity by the
|
|
52
|
+
`weight` column. Default is False.
|
|
53
|
+
layout (str): Layout algorithm, either 'force' or 'circular'.
|
|
54
|
+
Default is 'force'.
|
|
55
|
+
show_arrows (bool): Whether to draw directional arrows on edges.
|
|
56
|
+
Default is False.
|
|
57
|
+
height (str): Height of the visualization canvas. Default is "600px".
|
|
58
|
+
**kwargs: Additional keyword arguments passed through to
|
|
59
|
+
``lightgraph.net_vis``.
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
lightgraph.NetworkVisualization: A visualization object that renders
|
|
63
|
+
itself in a Jupyter notebook. Call ``.save(path)`` to write a
|
|
64
|
+
standalone HTML file or read ``.html`` for the raw markup.
|
|
65
|
+
"""
|
|
66
|
+
if layout not in ('force', 'circular'):
|
|
67
|
+
raise ValueError("layout must be either 'force' or 'circular'.")
|
|
68
|
+
|
|
69
|
+
keep_cols = [
|
|
70
|
+
c for c in ('source', 'target', 'weight') if c in pandas_edgelist
|
|
71
|
+
]
|
|
72
|
+
edges = pandas_edgelist[keep_cols].copy()
|
|
73
|
+
|
|
74
|
+
has_weight = 'weight' in keep_cols
|
|
75
|
+
if has_weight:
|
|
76
|
+
# RegDiffusion edge weights are signed and ranked by magnitude, so the
|
|
77
|
+
# visual channels are driven by the absolute regulatory strength.
|
|
78
|
+
edges['weight'] = edges['weight'].abs()
|
|
79
|
+
edges = edges.sort_values('weight', ascending=False)
|
|
80
|
+
|
|
81
|
+
# A multi-hop neighborhood walk reaches the same edge from either end, so
|
|
82
|
+
# the same pair can show up more than once. Keep the strongest copy.
|
|
83
|
+
edges = edges.drop_duplicates(subset=['source', 'target'])
|
|
84
|
+
|
|
85
|
+
node_sizes = {g: 2 * node_size for g in set(star_genes)}
|
|
86
|
+
|
|
87
|
+
params = dict(
|
|
88
|
+
edges=edges,
|
|
89
|
+
node_groups=node_group_dict,
|
|
90
|
+
node_colors=node_color_dict,
|
|
91
|
+
node_sizes=node_sizes or None,
|
|
92
|
+
node_metric=node_metric,
|
|
93
|
+
node_size=node_size,
|
|
94
|
+
label_font_size=font_size,
|
|
95
|
+
edge_weight_to_width=edge_weight_to_width and has_weight,
|
|
96
|
+
edge_weight_to_opacity=edge_weight_to_opacity and has_weight,
|
|
97
|
+
layout=layout,
|
|
98
|
+
show_arrows=show_arrows,
|
|
99
|
+
height=height,
|
|
100
|
+
)
|
|
101
|
+
# Anything passed through by name goes straight to lightgraph and wins, so
|
|
102
|
+
# that its native argument names keep working alongside the aliases above.
|
|
103
|
+
params.update(kwargs)
|
|
104
|
+
return net_vis(**params)
|
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
|
-
|
|
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
|
-
|
|
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
|
|
123
|
-
inference speed when it works. For smaller dataset, eager execution
|
|
124
|
-
|
|
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
|
-
|
|
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
|
|
416
|
-
|
|
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=
|
|
462
|
+
self._train_with_gradient_accumulation(n_steps=n_steps)
|
|
428
463
|
else:
|
|
429
|
-
self._train_normal(n_steps=
|
|
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
|
|
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
|
|
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
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
691
|
-
|
|
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
|
|
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,7 +1,8 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: regdiffusion
|
|
3
|
-
Version: 0.2.
|
|
4
|
-
Summary: Gene
|
|
3
|
+
Version: 0.2.4
|
|
4
|
+
Summary: Gene regulatory network inference from single-cell RNA-seq using diffusion models
|
|
5
|
+
Keywords: gene regulatory network,GRN inference,single-cell RNA-seq,diffusion model,bioinformatics
|
|
5
6
|
Author-email: Hao Zhu <haozhu233@gmail.com>, Donna Slonim <donna.slonim@tufts.edu>
|
|
6
7
|
Maintainer-email: Hao Zhu <haozhu233@gmail.com>
|
|
7
8
|
Description-Content-Type: text/markdown
|
|
@@ -14,8 +15,12 @@ Requires-Dist: tqdm
|
|
|
14
15
|
Requires-Dist: scanpy
|
|
15
16
|
Requires-Dist: scikit-learn
|
|
16
17
|
Requires-Dist: h5py
|
|
17
|
-
Requires-Dist:
|
|
18
|
+
Requires-Dist: lightgraph>=1.2.0
|
|
19
|
+
Project-URL: Documentation, https://tuftsbcb.github.io/RegDiffusion/
|
|
18
20
|
Project-URL: Home, https://github.com/TuftsBCB/RegDiffusion
|
|
21
|
+
Project-URL: Issues, https://github.com/TuftsBCB/RegDiffusion/issues
|
|
22
|
+
Project-URL: Publication, https://doi.org/10.1089/cmb.2024.0607
|
|
23
|
+
Project-URL: Source, https://github.com/TuftsBCB/RegDiffusion
|
|
19
24
|
|
|
20
25
|
# RegDiffusion <a href="https://tuftsbcb.github.io/RegDiffusion/"><img src="https://raw.githubusercontent.com/TuftsBCB/RegDiffusion/master/docs/_static/rd_logo_horizontal.png" align="right" alt="logo" width="200" height = "56" style = "border: none; float: right;"></a>
|
|
21
26
|
|
|
@@ -23,7 +28,18 @@ Project-URL: Home, https://github.com/TuftsBCB/RegDiffusion
|
|
|
23
28
|
[](https://pepy.tech/project/regdiffusion)
|
|
24
29
|

|
|
25
30
|
|
|
26
|
-
RegDiffusion is
|
|
31
|
+
RegDiffusion is an open-source Python package for **gene regulatory network (GRN) inference from single-cell RNA-seq data** using probabilistic diffusion models. It learns candidate regulatory relationships from gene expression data without requiring a ground-truth network for training, and includes tools to evaluate, export, and visualize inferred networks.
|
|
32
|
+
|
|
33
|
+
[Documentation](https://tuftsbcb.github.io/RegDiffusion/) · [Quick start](https://tuftsbcb.github.io/RegDiffusion/quick_tour.html) · [FAQ](https://tuftsbcb.github.io/RegDiffusion/faq.html) · [PyPI](https://pypi.org/project/regdiffusion/) · [Paper](https://doi.org/10.1089/cmb.2024.0607)
|
|
34
|
+
|
|
35
|
+
## What can RegDiffusion do?
|
|
36
|
+
|
|
37
|
+
- Infer GRNs from a cells-by-genes expression matrix with GPU acceleration or on CPU.
|
|
38
|
+
- Accept log-transformed NumPy arrays or SciPy sparse matrices through the Python API. The CLI accepts raw counts in CSV or H5AD files and performs the log transformation.
|
|
39
|
+
- Work with large gene sets using [memory-efficient training](https://tuftsbcb.github.io/RegDiffusion/large_networks.html).
|
|
40
|
+
- Export inferred edges for [downstream pySCENIC analysis](https://tuftsbcb.github.io/RegDiffusion/downstream_with_pyscenic.html).
|
|
41
|
+
|
|
42
|
+
The project reports inference on a 15,000-gene network in under five minutes on an NVIDIA A100 GPU. Runtime and memory use depend on dataset size, hardware, and training settings; see the [large-network guide](https://tuftsbcb.github.io/RegDiffusion/large_networks.html) for memory benchmarks. Inferred edges are hypotheses for follow-up analysis, not experimental proof of regulation.
|
|
27
43
|
|
|
28
44
|
```
|
|
29
45
|
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.
|
|
@@ -46,14 +62,14 @@ Check out [this tutorial](https://tuftsbcb.github.io/RegDiffusion/quick_tour.htm
|
|
|
46
62
|
## Inferred Networks from RegDiffusion
|
|
47
63
|
Here are two examples of inferred networks from regdiffusion. The networks are coherent with existing literature and across datasets.
|
|
48
64
|
|
|
49
|
-

|
|
65
|
+

|
|
50
66
|
|
|
51
67
|
## Inference Speed
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
68
|
+
The project reports inference on a 15,000-gene network in under five minutes on
|
|
69
|
+
an NVIDIA A100 GPU, or roughly three hours on a 12-core CPU. These timings depend
|
|
70
|
+
on the dataset and training settings. See the [paper](https://doi.org/10.1089/cmb.2024.0607)
|
|
71
|
+
for the method's evaluation and the [large-network guide](https://tuftsbcb.github.io/RegDiffusion/large_networks.html)
|
|
72
|
+
for memory benchmarks.
|
|
57
73
|
|
|
58
74
|
## CLI tool
|
|
59
75
|
regdiffusion has a CLI tool now! It takes a count matrix as the input (different from the main API, which needs the data to be log transformed) and returns a table of inferred edges.
|
|
@@ -88,6 +104,8 @@ If you find our package useful, consider citing our paper! =)
|
|
|
88
104
|
number={11},
|
|
89
105
|
pages={1087--1103},
|
|
90
106
|
year={2024},
|
|
91
|
-
|
|
107
|
+
doi={10.1089/cmb.2024.0607},
|
|
108
|
+
url={https://doi.org/10.1089/cmb.2024.0607}
|
|
92
109
|
}
|
|
93
110
|
```
|
|
111
|
+
|
|
@@ -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=LT8eNveWf1j7u3b4_KGw1FDhR9CGaZCX4t4D_vtYuV0,26507
|
|
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=f7HELgDJDe1rZnUH0eDc8eTUVLcqTlpm5fDwPP1P-dc,293
|
|
15
|
+
regdiffusion/plot/interactive.py,sha256=aSmM2j24xn_lXrodvuycPDxoHJcmMUkuyK77S7Tr0Xg,4653
|
|
16
|
+
regdiffusion/plot/static.py,sha256=bhDB-xB8C-3ZDUKoDJaoLQc0EqEXYgcO9a-sY_Uvpyo,11776
|
|
17
|
+
regdiffusion-0.2.4.dist-info/entry_points.txt,sha256=A737tP1RgN6tYHktWvmZByLxaW__S6-LE7mRTn0PQF0,54
|
|
18
|
+
regdiffusion-0.2.4.dist-info/licenses/LICENSE,sha256=jzkY6g_rbcJvt5Ehsqxr6IazE2Nj55hBtW4hkb6QMmw,11341
|
|
19
|
+
regdiffusion-0.2.4.dist-info/WHEEL,sha256=Dyt6SBfaasWElUrURkknVFAZDHSTwxg3PaTza7RSbkY,100
|
|
20
|
+
regdiffusion-0.2.4.dist-info/METADATA,sha256=urMXmXzFHFBw7YRfA3DdG2QCavnFjAHiN40i5ycoiI8,6393
|
|
21
|
+
regdiffusion-0.2.4.dist-info/RECORD,,
|
regdiffusion/plot/pyvis.py
DELETED
|
@@ -1,108 +0,0 @@
|
|
|
1
|
-
import pyvis
|
|
2
|
-
import pandas as pd
|
|
3
|
-
import numpy as np
|
|
4
|
-
from typing import List, Dict, Union, Optional
|
|
5
|
-
|
|
6
|
-
def plot_pyvis(
|
|
7
|
-
pandas_edgelist: pd.DataFrame,
|
|
8
|
-
star_genes: List[str] = [],
|
|
9
|
-
node_size: int = 8,
|
|
10
|
-
font_size: int = 30,
|
|
11
|
-
node_color_dict: Optional[Dict[str, str]] = None,
|
|
12
|
-
node_group_dict: Optional[Dict[str, str]] = None,
|
|
13
|
-
edge_color_by_weight: bool = False,
|
|
14
|
-
layout: str = 'force',
|
|
15
|
-
physics: bool = True,
|
|
16
|
-
height: str = "600px",
|
|
17
|
-
width: str = "100%",
|
|
18
|
-
cdn_resources: str = 'remote',
|
|
19
|
-
notebook: bool = True
|
|
20
|
-
) -> pyvis.network.Network:
|
|
21
|
-
"""
|
|
22
|
-
Generate a vis.js network visualization given an edge list
|
|
23
|
-
representation of a graph in data frame.
|
|
24
|
-
|
|
25
|
-
Args:
|
|
26
|
-
pandas_edgelist (pd.DataFrame): an edge list representation of
|
|
27
|
-
a graph in a pandas data frame. It should at least have columns
|
|
28
|
-
with the name `source` and `target`. You can also (optionally)
|
|
29
|
-
provide an `edge_width` column for the width of the edges.
|
|
30
|
-
star_genes (List): A list of genes to be starred.
|
|
31
|
-
node_size (int): Base size for nodes. Default is 8.
|
|
32
|
-
font_size (int): The font size for nodes labels. Default is 30.
|
|
33
|
-
node_color_dict (dict): A dictionary with keys being the names of
|
|
34
|
-
genes and values being the color.
|
|
35
|
-
node_group_dict (dict): A dictionary with keys being the names of
|
|
36
|
-
genes and values being the group.
|
|
37
|
-
edge_color_by_weight (bool): If True, color edges based on their
|
|
38
|
-
weight values using a diverging colormap. Default is False.
|
|
39
|
-
layout (str): Layout algorithm. Currently supports 'force'.
|
|
40
|
-
Default is 'force'.
|
|
41
|
-
physics (bool): Whether to enable physics simulation. Set to False
|
|
42
|
-
for static layout after initial positioning. Default is True.
|
|
43
|
-
height (str): Height of the visualization canvas. Default is "600px".
|
|
44
|
-
width (str): Width of the visualization canvas. Default is "100%".
|
|
45
|
-
cdn_resources (str): Where to load vis.js resources. Default is
|
|
46
|
-
'remote'.
|
|
47
|
-
notebook (bool): Boolean value indicating whether the visualization
|
|
48
|
-
happens in a jupyter notebook. Default is True.
|
|
49
|
-
|
|
50
|
-
Returns:
|
|
51
|
-
pyvis.network.Network: A PyVis network object that can be displayed
|
|
52
|
-
or saved to HTML.
|
|
53
|
-
"""
|
|
54
|
-
g = pyvis.network.Network(
|
|
55
|
-
cdn_resources=cdn_resources,
|
|
56
|
-
notebook=notebook,
|
|
57
|
-
height=height,
|
|
58
|
-
width=width
|
|
59
|
-
)
|
|
60
|
-
|
|
61
|
-
star_genes = set(star_genes)
|
|
62
|
-
|
|
63
|
-
for node in set(pandas_edgelist['source']) | set(pandas_edgelist['target']):
|
|
64
|
-
if len(star_genes) == 0:
|
|
65
|
-
node_shape = 'dot'
|
|
66
|
-
this_node_size = node_size
|
|
67
|
-
else:
|
|
68
|
-
node_shape = 'star' if node in star_genes else 'dot'
|
|
69
|
-
this_node_size = 2 * node_size if node in star_genes else node_size
|
|
70
|
-
node_color = None if node_color_dict is None else node_color_dict.get(node)
|
|
71
|
-
node_group = None if node_group_dict is None else node_group_dict.get(node)
|
|
72
|
-
g.add_node(node, label=node, size=this_node_size,
|
|
73
|
-
shape=node_shape, color=node_color, group=node_group,
|
|
74
|
-
font={"size": font_size})
|
|
75
|
-
|
|
76
|
-
# Handle edge coloring by weight
|
|
77
|
-
if edge_color_by_weight and 'weight' in pandas_edgelist.columns:
|
|
78
|
-
weights = pandas_edgelist['weight'].values
|
|
79
|
-
abs_weights = np.abs(weights)
|
|
80
|
-
max_weight = abs_weights.max() if abs_weights.max() > 0 else 1
|
|
81
|
-
|
|
82
|
-
for _, row in pandas_edgelist.iterrows():
|
|
83
|
-
weight = row['weight']
|
|
84
|
-
# Normalize to [0, 1] based on sign and magnitude
|
|
85
|
-
norm_weight = weight / max_weight
|
|
86
|
-
# Red for positive, blue for negative
|
|
87
|
-
if norm_weight >= 0:
|
|
88
|
-
r = int(255 * norm_weight)
|
|
89
|
-
color = f'rgb({r}, 100, 100)'
|
|
90
|
-
else:
|
|
91
|
-
b = int(255 * abs(norm_weight))
|
|
92
|
-
color = f'rgb(100, 100, {b})'
|
|
93
|
-
|
|
94
|
-
edge_width = row.get('edge_width', 1) if 'edge_width' in pandas_edgelist.columns else 1
|
|
95
|
-
g.add_edge(row['source'], row['target'], width=edge_width, color=color)
|
|
96
|
-
elif 'edge_width' in pandas_edgelist.columns:
|
|
97
|
-
for _, row in pandas_edgelist.iterrows():
|
|
98
|
-
g.add_edge(row['source'], row['target'], width=row['edge_width'])
|
|
99
|
-
else:
|
|
100
|
-
for _, row in pandas_edgelist.iterrows():
|
|
101
|
-
g.add_edge(row['source'], row['target'])
|
|
102
|
-
|
|
103
|
-
if physics:
|
|
104
|
-
g.repulsion()
|
|
105
|
-
else:
|
|
106
|
-
g.toggle_physics(False)
|
|
107
|
-
|
|
108
|
-
return g
|
|
@@ -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,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|