regdiffusion 0.2.3__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/grn.py +38 -23
- regdiffusion/plot/__init__.py +2 -2
- regdiffusion/plot/interactive.py +104 -0
- {regdiffusion-0.2.3.dist-info → regdiffusion-0.2.4.dist-info}/METADATA +29 -11
- {regdiffusion-0.2.3.dist-info → regdiffusion-0.2.4.dist-info}/RECORD +8 -8
- regdiffusion/plot/pyvis.py +0 -108
- {regdiffusion-0.2.3.dist-info → regdiffusion-0.2.4.dist-info}/WHEEL +0 -0
- {regdiffusion-0.2.3.dist-info → regdiffusion-0.2.4.dist-info}/entry_points.txt +0 -0
- {regdiffusion-0.2.3.dist-info → regdiffusion-0.2.4.dist-info}/licenses/LICENSE +0 -0
regdiffusion/grn.py
CHANGED
|
@@ -5,9 +5,9 @@ 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
13
|
"""
|
|
@@ -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
|
"""
|
|
@@ -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/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)
|
|
@@ -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
|
+
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
regdiffusion/__init__.py,sha256=0vuZ57xw8Bhf91fcCfXPNY_oLmrHtvcBCjxOBMqo3EU,444
|
|
2
2
|
regdiffusion/cli.py,sha256=E2grkvRagj5P2PGT7Yv6fXOTX5IvzrXgb9Qth2Nv_js,2982
|
|
3
3
|
regdiffusion/evaluator.py,sha256=RYJL2c5dfVB4hXGUbI4V5OtxPMm81dlqY-uhGFzSmkU,3666
|
|
4
|
-
regdiffusion/grn.py,sha256=
|
|
4
|
+
regdiffusion/grn.py,sha256=LT8eNveWf1j7u3b4_KGw1FDhR9CGaZCX4t4D_vtYuV0,26507
|
|
5
5
|
regdiffusion/logger.py,sha256=ldo0tT2wK7GiHaxx9OgtEGoW8NIAPVH2ZMim6GI2ZWY,6378
|
|
6
6
|
regdiffusion/trainer.py,sha256=KFVWEB1c5_wVm84wXAdr-K6evnny7t6C-8UgtrCW8mA,34081
|
|
7
7
|
regdiffusion/data/__init__.py,sha256=G-eDyYgjY9xqu9v6mN7Py110Lz8O6cDuc4cMAFEecYQ,366
|
|
@@ -11,11 +11,11 @@ regdiffusion/data/utils.py,sha256=jF95ueUyzI9fhJlJQ3SkXLOGfibT6YhqZqkxbVfPAVw,57
|
|
|
11
11
|
regdiffusion/models/__init__.py,sha256=Bo5-RKjQLSJZ2P6MnKR8O_aoHjKgVAF0J1-9ULhkcxw,83
|
|
12
12
|
regdiffusion/models/regdiffusion.py,sha256=3-avc-IuzjvK6hSWF1D2adF96HjoB9-VWuMiyUqpC8s,7785
|
|
13
13
|
regdiffusion/models/regdiffusion_me.py,sha256=_IkW6WOC-RQk9f8laRXGQXsGtxHq13jYqD6XIi7w9HI,7244
|
|
14
|
-
regdiffusion/plot/__init__.py,sha256=
|
|
15
|
-
regdiffusion/plot/
|
|
14
|
+
regdiffusion/plot/__init__.py,sha256=f7HELgDJDe1rZnUH0eDc8eTUVLcqTlpm5fDwPP1P-dc,293
|
|
15
|
+
regdiffusion/plot/interactive.py,sha256=aSmM2j24xn_lXrodvuycPDxoHJcmMUkuyK77S7Tr0Xg,4653
|
|
16
16
|
regdiffusion/plot/static.py,sha256=bhDB-xB8C-3ZDUKoDJaoLQc0EqEXYgcO9a-sY_Uvpyo,11776
|
|
17
|
-
regdiffusion-0.2.
|
|
18
|
-
regdiffusion-0.2.
|
|
19
|
-
regdiffusion-0.2.
|
|
20
|
-
regdiffusion-0.2.
|
|
21
|
-
regdiffusion-0.2.
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|