risk-network 0.0.9b27__py3-none-any.whl → 0.0.9b28__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.
- risk/__init__.py +1 -1
- risk/network/graph/api.py +6 -6
- risk/network/graph/{network.py → graph.py} +7 -7
- risk/network/graph/summary.py +3 -3
- risk/network/plotter/__init__.py +2 -2
- risk/network/plotter/api.py +12 -12
- risk/network/plotter/canvas.py +7 -7
- risk/network/plotter/contour.py +6 -6
- risk/network/plotter/labels.py +5 -5
- risk/network/plotter/network.py +6 -136
- risk/network/plotter/plotter.py +143 -0
- risk/network/plotter/utils/colors.py +11 -11
- risk/network/plotter/utils/layout.py +2 -2
- risk/stats/stat_tests.py +20 -15
- {risk_network-0.0.9b27.dist-info → risk_network-0.0.9b28.dist-info}/METADATA +1 -1
- {risk_network-0.0.9b27.dist-info → risk_network-0.0.9b28.dist-info}/RECORD +19 -18
- {risk_network-0.0.9b27.dist-info → risk_network-0.0.9b28.dist-info}/LICENSE +0 -0
- {risk_network-0.0.9b27.dist-info → risk_network-0.0.9b28.dist-info}/WHEEL +0 -0
- {risk_network-0.0.9b27.dist-info → risk_network-0.0.9b28.dist-info}/top_level.txt +0 -0
risk/__init__.py
CHANGED
risk/network/graph/api.py
CHANGED
@@ -16,7 +16,7 @@ from risk.neighborhoods import (
|
|
16
16
|
process_neighborhoods,
|
17
17
|
trim_domains,
|
18
18
|
)
|
19
|
-
from risk.network.graph.
|
19
|
+
from risk.network.graph.graph import Graph
|
20
20
|
from risk.stats import calculate_significance_matrices
|
21
21
|
|
22
22
|
|
@@ -44,7 +44,7 @@ class GraphAPI:
|
|
44
44
|
linkage_metric: str = "yule",
|
45
45
|
min_cluster_size: int = 5,
|
46
46
|
max_cluster_size: int = 1000,
|
47
|
-
) ->
|
47
|
+
) -> Graph:
|
48
48
|
"""Load and process the network graph, defining top annotations and domains.
|
49
49
|
|
50
50
|
Args:
|
@@ -63,7 +63,7 @@ class GraphAPI:
|
|
63
63
|
max_cluster_size (int, optional): Maximum size for clusters. Defaults to 1000.
|
64
64
|
|
65
65
|
Returns:
|
66
|
-
|
66
|
+
Graph: A fully initialized and processed Graph object.
|
67
67
|
"""
|
68
68
|
# Log the parameters and display headers
|
69
69
|
log_header("Finding significant neighborhoods")
|
@@ -139,13 +139,13 @@ class GraphAPI:
|
|
139
139
|
max_cluster_size=max_cluster_size,
|
140
140
|
)
|
141
141
|
|
142
|
-
# Prepare node mapping and significance sums for the final
|
142
|
+
# Prepare node mapping and significance sums for the final Graph object
|
143
143
|
ordered_nodes = annotations["ordered_nodes"]
|
144
144
|
node_label_to_id = dict(zip(ordered_nodes, range(len(ordered_nodes))))
|
145
145
|
node_significance_sums = processed_neighborhoods["node_significance_sums"]
|
146
146
|
|
147
|
-
# Return the fully initialized
|
148
|
-
return
|
147
|
+
# Return the fully initialized Graph object
|
148
|
+
return Graph(
|
149
149
|
network=network,
|
150
150
|
annotations=annotations,
|
151
151
|
neighborhoods=neighborhoods,
|
@@ -1,6 +1,6 @@
|
|
1
1
|
"""
|
2
|
-
risk/network/graph/
|
3
|
-
|
2
|
+
risk/network/graph/graph
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
4
4
|
"""
|
5
5
|
|
6
6
|
from collections import defaultdict
|
@@ -10,13 +10,13 @@ import networkx as nx
|
|
10
10
|
import numpy as np
|
11
11
|
import pandas as pd
|
12
12
|
|
13
|
-
from risk.network.graph.summary import
|
13
|
+
from risk.network.graph.summary import Summary
|
14
14
|
|
15
15
|
|
16
|
-
class
|
16
|
+
class Graph:
|
17
17
|
"""A class to represent a network graph and process its nodes and edges.
|
18
18
|
|
19
|
-
The
|
19
|
+
The Graph class provides functionality to handle and manipulate a network graph,
|
20
20
|
including managing domains, annotations, and node significance data. It also includes methods
|
21
21
|
for transforming and mapping graph coordinates, as well as generating colors based on node
|
22
22
|
significance.
|
@@ -32,7 +32,7 @@ class NetworkGraph:
|
|
32
32
|
node_label_to_node_id_map: Dict[str, Any],
|
33
33
|
node_significance_sums: np.ndarray,
|
34
34
|
):
|
35
|
-
"""Initialize the
|
35
|
+
"""Initialize the Graph object.
|
36
36
|
|
37
37
|
Args:
|
38
38
|
network (nx.Graph): The network graph.
|
@@ -69,7 +69,7 @@ class NetworkGraph:
|
|
69
69
|
self.node_coordinates = _extract_node_coordinates(self.network)
|
70
70
|
|
71
71
|
# NOTE: Only after the above attributes are initialized, we can create the summary
|
72
|
-
self.summary =
|
72
|
+
self.summary = Summary(annotations, neighborhoods, self)
|
73
73
|
|
74
74
|
def pop(self, domain_id: str) -> None:
|
75
75
|
"""Remove domain ID from instance domain ID mappings. This can be useful for cleaning up
|
risk/network/graph/summary.py
CHANGED
@@ -12,7 +12,7 @@ from statsmodels.stats.multitest import fdrcorrection
|
|
12
12
|
from risk.log.console import logger, log_header
|
13
13
|
|
14
14
|
|
15
|
-
class
|
15
|
+
class Summary:
|
16
16
|
"""Handles the processing, storage, and export of network analysis results.
|
17
17
|
|
18
18
|
The Results class provides methods to process significance and depletion data, compute
|
@@ -25,14 +25,14 @@ class AnalysisSummary:
|
|
25
25
|
self,
|
26
26
|
annotations: Dict[str, Any],
|
27
27
|
neighborhoods: Dict[str, Any],
|
28
|
-
graph, # Avoid type hinting
|
28
|
+
graph, # Avoid type hinting Graph to prevent circular imports
|
29
29
|
):
|
30
30
|
"""Initialize the Results object with analysis components.
|
31
31
|
|
32
32
|
Args:
|
33
33
|
annotations (Dict[str, Any]): Annotation data, including ordered annotations and matrix of associations.
|
34
34
|
neighborhoods (Dict[str, Any]): Neighborhood data containing p-values for significance and depletion analysis.
|
35
|
-
graph (
|
35
|
+
graph (Graph): Graph object representing domain-to-node and node-to-label mappings.
|
36
36
|
"""
|
37
37
|
self.annotations = annotations
|
38
38
|
self.neighborhoods = neighborhoods
|
risk/network/plotter/__init__.py
CHANGED
risk/network/plotter/api.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"""
|
2
|
-
risk/network/
|
3
|
-
|
2
|
+
risk/network/plotter/api
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~
|
4
4
|
"""
|
5
5
|
|
6
6
|
from typing import List, Tuple, Union
|
@@ -8,14 +8,14 @@ from typing import List, Tuple, Union
|
|
8
8
|
import numpy as np
|
9
9
|
|
10
10
|
from risk.log import log_header
|
11
|
-
from risk.network.graph.
|
12
|
-
from risk.network.plotter.
|
11
|
+
from risk.network.graph.graph import Graph
|
12
|
+
from risk.network.plotter.plotter import Plotter
|
13
13
|
|
14
14
|
|
15
15
|
class PlotterAPI:
|
16
16
|
"""Handles the loading of network plotter objects.
|
17
17
|
|
18
|
-
The PlotterAPI class provides methods to load and configure
|
18
|
+
The PlotterAPI class provides methods to load and configure Plotter objects for plotting network graphs.
|
19
19
|
"""
|
20
20
|
|
21
21
|
def __init__() -> None:
|
@@ -23,16 +23,16 @@ class PlotterAPI:
|
|
23
23
|
|
24
24
|
def load_plotter(
|
25
25
|
self,
|
26
|
-
graph:
|
26
|
+
graph: Graph,
|
27
27
|
figsize: Union[List, Tuple, np.ndarray] = (10, 10),
|
28
28
|
background_color: str = "white",
|
29
29
|
background_alpha: Union[float, None] = 1.0,
|
30
30
|
pad: float = 0.3,
|
31
|
-
) ->
|
32
|
-
"""Get a
|
31
|
+
) -> Plotter:
|
32
|
+
"""Get a Plotter object for plotting.
|
33
33
|
|
34
34
|
Args:
|
35
|
-
graph (
|
35
|
+
graph (Graph): The graph to plot.
|
36
36
|
figsize (List, Tuple, or np.ndarray, optional): Size of the plot. Defaults to (10, 10)., optional): Size of the figure. Defaults to (10, 10).
|
37
37
|
background_color (str, optional): Background color of the plot. Defaults to "white".
|
38
38
|
background_alpha (float, None, optional): Transparency level of the background color. If provided, it overrides
|
@@ -40,12 +40,12 @@ class PlotterAPI:
|
|
40
40
|
pad (float, optional): Padding value to adjust the axis limits. Defaults to 0.3.
|
41
41
|
|
42
42
|
Returns:
|
43
|
-
|
43
|
+
Plotter: A Plotter object configured with the given parameters.
|
44
44
|
"""
|
45
45
|
log_header("Loading plotter")
|
46
46
|
|
47
|
-
# Initialize and return a
|
48
|
-
return
|
47
|
+
# Initialize and return a Plotter object
|
48
|
+
return Plotter(
|
49
49
|
graph,
|
50
50
|
figsize=figsize,
|
51
51
|
background_color=background_color,
|
risk/network/plotter/canvas.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"""
|
2
|
-
risk/network/
|
3
|
-
|
2
|
+
risk/network/plotter/canvas
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
4
4
|
"""
|
5
5
|
|
6
6
|
from typing import List, Tuple, Union
|
@@ -9,7 +9,7 @@ import matplotlib.pyplot as plt
|
|
9
9
|
import numpy as np
|
10
10
|
|
11
11
|
from risk.log import params
|
12
|
-
from risk.network.graph.
|
12
|
+
from risk.network.graph.graph import Graph
|
13
13
|
from risk.network.plotter.utils.colors import to_rgba
|
14
14
|
from risk.network.plotter.utils.layout import calculate_bounding_box
|
15
15
|
|
@@ -17,11 +17,11 @@ from risk.network.plotter.utils.layout import calculate_bounding_box
|
|
17
17
|
class Canvas:
|
18
18
|
"""A class for laying out the canvas in a network graph."""
|
19
19
|
|
20
|
-
def __init__(self, graph:
|
21
|
-
"""Initialize the Canvas with a
|
20
|
+
def __init__(self, graph: Graph, ax: plt.Axes) -> None:
|
21
|
+
"""Initialize the Canvas with a Graph and axis for plotting.
|
22
22
|
|
23
23
|
Args:
|
24
|
-
graph (
|
24
|
+
graph (Graph): The Graph object containing the network data.
|
25
25
|
ax (plt.Axes): The axis to plot the canvas on.
|
26
26
|
"""
|
27
27
|
self.graph = graph
|
@@ -236,7 +236,7 @@ class Canvas:
|
|
236
236
|
# Scale the node coordinates if needed
|
237
237
|
scaled_coordinates = node_coordinates * scale
|
238
238
|
# Use the existing _draw_kde_contour method
|
239
|
-
# NOTE: This is a technical debt that should be refactored in the future - only works when inherited by
|
239
|
+
# NOTE: This is a technical debt that should be refactored in the future - only works when inherited by Plotter
|
240
240
|
self._draw_kde_contour(
|
241
241
|
ax=self.ax,
|
242
242
|
pos=scaled_coordinates,
|
risk/network/plotter/contour.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"""
|
2
|
-
risk/network/
|
3
|
-
|
2
|
+
risk/network/plotter/contour
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
4
4
|
"""
|
5
5
|
|
6
6
|
from typing import Any, Dict, List, Tuple, Union
|
@@ -12,18 +12,18 @@ from scipy.ndimage import label
|
|
12
12
|
from scipy.stats import gaussian_kde
|
13
13
|
|
14
14
|
from risk.log import params, logger
|
15
|
-
from risk.network.graph.
|
15
|
+
from risk.network.graph.graph import Graph
|
16
16
|
from risk.network.plotter.utils.colors import get_annotated_domain_colors, to_rgba
|
17
17
|
|
18
18
|
|
19
19
|
class Contour:
|
20
20
|
"""Class to generate Kernel Density Estimate (KDE) contours for nodes in a network graph."""
|
21
21
|
|
22
|
-
def __init__(self, graph:
|
23
|
-
"""Initialize the Contour with a
|
22
|
+
def __init__(self, graph: Graph, ax: plt.Axes) -> None:
|
23
|
+
"""Initialize the Contour with a Graph and axis for plotting.
|
24
24
|
|
25
25
|
Args:
|
26
|
-
graph (
|
26
|
+
graph (Graph): The Graph object containing the network data.
|
27
27
|
ax (plt.Axes): The axis to plot the contours on.
|
28
28
|
"""
|
29
29
|
self.graph = graph
|
risk/network/plotter/labels.py
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
"""
|
2
|
-
risk/network/
|
3
|
-
|
2
|
+
risk/network/plotter/labels
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
4
4
|
"""
|
5
5
|
|
6
6
|
import copy
|
@@ -11,7 +11,7 @@ import numpy as np
|
|
11
11
|
import pandas as pd
|
12
12
|
|
13
13
|
from risk.log import params
|
14
|
-
from risk.network.graph.
|
14
|
+
from risk.network.graph.graph import Graph
|
15
15
|
from risk.network.plotter.utils.colors import get_annotated_domain_colors, to_rgba
|
16
16
|
from risk.network.plotter.utils.layout import calculate_bounding_box
|
17
17
|
|
@@ -21,11 +21,11 @@ TERM_DELIMITER = "::::" # String used to separate multiple domain terms when co
|
|
21
21
|
class Labels:
|
22
22
|
"""Class to handle the annotation of network graphs with labels for different domains."""
|
23
23
|
|
24
|
-
def __init__(self, graph:
|
24
|
+
def __init__(self, graph: Graph, ax: plt.Axes):
|
25
25
|
"""Initialize the Labeler object with a network graph and matplotlib axes.
|
26
26
|
|
27
27
|
Args:
|
28
|
-
graph (
|
28
|
+
graph (Graph): Graph object containing the network data.
|
29
29
|
ax (plt.Axes): Matplotlib axes object to plot the labels on.
|
30
30
|
"""
|
31
31
|
self.graph = graph
|
risk/network/plotter/network.py
CHANGED
@@ -1,21 +1,16 @@
|
|
1
1
|
"""
|
2
|
-
risk/network/
|
3
|
-
|
2
|
+
risk/network/plotter/network
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
4
4
|
"""
|
5
5
|
|
6
6
|
from typing import Any, Dict, List, Tuple, Union
|
7
7
|
|
8
|
-
import matplotlib.pyplot as plt
|
9
8
|
import networkx as nx
|
10
9
|
import numpy as np
|
11
10
|
|
12
11
|
from risk.log import params
|
13
|
-
from risk.network.graph.
|
14
|
-
from risk.network.plotter.canvas import Canvas
|
15
|
-
from risk.network.plotter.contour import Contour
|
16
|
-
from risk.network.plotter.labels import Labels
|
12
|
+
from risk.network.graph.graph import Graph
|
17
13
|
from risk.network.plotter.utils.colors import get_domain_colors, to_rgba
|
18
|
-
from risk.network.plotter.utils.layout import calculate_bounding_box
|
19
14
|
|
20
15
|
|
21
16
|
class Network:
|
@@ -24,11 +19,11 @@ class Network:
|
|
24
19
|
The Network class provides methods to plot network graphs with flexible node and edge properties.
|
25
20
|
"""
|
26
21
|
|
27
|
-
def __init__(self, graph:
|
28
|
-
"""Initialize the
|
22
|
+
def __init__(self, graph: Graph, ax: Any = None) -> None:
|
23
|
+
"""Initialize the Plotter class.
|
29
24
|
|
30
25
|
Args:
|
31
|
-
graph (
|
26
|
+
graph (Graph): The network data and attributes to be visualized.
|
32
27
|
ax (Any, optional): Axes object to plot the network graph. Defaults to None.
|
33
28
|
"""
|
34
29
|
self.graph = graph
|
@@ -297,128 +292,3 @@ class Network:
|
|
297
292
|
node_sizes[node] = significant_size
|
298
293
|
|
299
294
|
return node_sizes
|
300
|
-
|
301
|
-
|
302
|
-
class NetworkPlotter(Canvas, Network, Contour, Labels):
|
303
|
-
"""A class for visualizing network graphs with customizable options.
|
304
|
-
|
305
|
-
The NetworkPlotter class uses a NetworkGraph object and provides methods to plot the network with
|
306
|
-
flexible node and edge properties. It also supports plotting labels, contours, drawing the network's
|
307
|
-
perimeter, and adjusting background colors.
|
308
|
-
"""
|
309
|
-
|
310
|
-
def __init__(
|
311
|
-
self,
|
312
|
-
graph: NetworkGraph,
|
313
|
-
figsize: Tuple = (10, 10),
|
314
|
-
background_color: Union[str, List, Tuple, np.ndarray] = "white",
|
315
|
-
background_alpha: Union[float, None] = 1.0,
|
316
|
-
pad: float = 0.3,
|
317
|
-
) -> None:
|
318
|
-
"""Initialize the NetworkPlotter with a NetworkGraph object and plotting parameters.
|
319
|
-
|
320
|
-
Args:
|
321
|
-
graph (NetworkGraph): The network data and attributes to be visualized.
|
322
|
-
figsize (Tuple, optional): Size of the figure in inches (width, height). Defaults to (10, 10).
|
323
|
-
background_color (str, List, Tuple, np.ndarray, optional): Background color of the plot. Defaults to "white".
|
324
|
-
background_alpha (float, None, optional): Transparency level of the background color. If provided, it overrides
|
325
|
-
any existing alpha values found in background_color. Defaults to 1.0.
|
326
|
-
pad (float, optional): Padding value to adjust the axis limits. Defaults to 0.3.
|
327
|
-
"""
|
328
|
-
self.graph = graph
|
329
|
-
# Initialize the plot with the specified parameters
|
330
|
-
self.ax = self._initialize_plot(
|
331
|
-
graph=graph,
|
332
|
-
figsize=figsize,
|
333
|
-
background_color=background_color,
|
334
|
-
background_alpha=background_alpha,
|
335
|
-
pad=pad,
|
336
|
-
)
|
337
|
-
super().__init__(graph=graph, ax=self.ax)
|
338
|
-
|
339
|
-
def _initialize_plot(
|
340
|
-
self,
|
341
|
-
graph: NetworkGraph,
|
342
|
-
figsize: Tuple,
|
343
|
-
background_color: Union[str, List, Tuple, np.ndarray],
|
344
|
-
background_alpha: Union[float, None],
|
345
|
-
pad: float,
|
346
|
-
) -> plt.Axes:
|
347
|
-
"""Set up the plot with figure size and background color.
|
348
|
-
|
349
|
-
Args:
|
350
|
-
graph (NetworkGraph): The network data and attributes to be visualized.
|
351
|
-
figsize (Tuple): Size of the figure in inches (width, height).
|
352
|
-
background_color (str, List, Tuple, or np.ndarray): Background color of the plot. Can be a single color or an array of colors.
|
353
|
-
background_alpha (float, None, optional): Transparency level of the background color. If provided, it overrides any existing
|
354
|
-
alpha values found in `background_color`.
|
355
|
-
pad (float, optional): Padding value to adjust the axis limits.
|
356
|
-
|
357
|
-
Returns:
|
358
|
-
plt.Axes: The axis object for the plot.
|
359
|
-
"""
|
360
|
-
# Log the plotter settings
|
361
|
-
params.log_plotter(
|
362
|
-
figsize=figsize,
|
363
|
-
background_color=background_color,
|
364
|
-
background_alpha=background_alpha,
|
365
|
-
pad=pad,
|
366
|
-
)
|
367
|
-
|
368
|
-
# Extract node coordinates from the network graph
|
369
|
-
node_coordinates = graph.node_coordinates
|
370
|
-
# Calculate the center and radius of the bounding box around the network
|
371
|
-
center, radius = calculate_bounding_box(node_coordinates)
|
372
|
-
|
373
|
-
# Create a new figure and axis for plotting
|
374
|
-
fig, ax = plt.subplots(figsize=figsize)
|
375
|
-
fig.tight_layout() # Adjust subplot parameters to give specified padding
|
376
|
-
# Set axis limits based on the calculated bounding box and radius
|
377
|
-
ax.set_xlim([center[0] - radius - pad, center[0] + radius + pad])
|
378
|
-
ax.set_ylim([center[1] - radius - pad, center[1] + radius + pad])
|
379
|
-
ax.set_aspect("equal") # Ensure the aspect ratio is equal
|
380
|
-
|
381
|
-
# Set the background color of the plot
|
382
|
-
# Convert color to RGBA using the to_rgba helper function
|
383
|
-
fig.patch.set_facecolor(
|
384
|
-
to_rgba(color=background_color, alpha=background_alpha, num_repeats=1)
|
385
|
-
) # num_repeats=1 for single color
|
386
|
-
ax.invert_yaxis() # Invert the y-axis to match typical image coordinates
|
387
|
-
# Remove axis spines for a cleaner look
|
388
|
-
for spine in ax.spines.values():
|
389
|
-
spine.set_visible(False)
|
390
|
-
|
391
|
-
# Hide axis ticks and labels
|
392
|
-
ax.set_xticks([])
|
393
|
-
ax.set_yticks([])
|
394
|
-
ax.patch.set_visible(False) # Hide the axis background
|
395
|
-
|
396
|
-
return ax
|
397
|
-
|
398
|
-
@staticmethod
|
399
|
-
def savefig(*args, pad_inches: float = 0.5, dpi: int = 100, **kwargs) -> None:
|
400
|
-
"""Save the current plot to a file with additional export options.
|
401
|
-
|
402
|
-
Args:
|
403
|
-
*args: Positional arguments passed to `plt.savefig`.
|
404
|
-
pad_inches (float, optional): Padding around the figure when saving. Defaults to 0.5.
|
405
|
-
dpi (int, optional): Dots per inch (DPI) for the exported image. Defaults to 300.
|
406
|
-
**kwargs: Keyword arguments passed to `plt.savefig`, such as filename and format.
|
407
|
-
"""
|
408
|
-
# Ensure user-provided kwargs take precedence
|
409
|
-
kwargs.setdefault("dpi", dpi)
|
410
|
-
kwargs.setdefault("pad_inches", pad_inches)
|
411
|
-
# Ensure the plot is saved with tight bounding box if not specified
|
412
|
-
kwargs.setdefault("bbox_inches", "tight")
|
413
|
-
# Call plt.savefig with combined arguments
|
414
|
-
plt.savefig(*args, **kwargs)
|
415
|
-
|
416
|
-
@staticmethod
|
417
|
-
def show(*args, **kwargs) -> None:
|
418
|
-
"""Display the current plot.
|
419
|
-
|
420
|
-
Args:
|
421
|
-
*args: Positional arguments passed to `plt.show`.
|
422
|
-
**kwargs: Keyword arguments passed to `plt.show`.
|
423
|
-
"""
|
424
|
-
plt.show(*args, **kwargs)
|
@@ -0,0 +1,143 @@
|
|
1
|
+
"""
|
2
|
+
risk/network/plotter/plotter
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
4
|
+
"""
|
5
|
+
|
6
|
+
from typing import List, Tuple, Union
|
7
|
+
|
8
|
+
import matplotlib.pyplot as plt
|
9
|
+
import numpy as np
|
10
|
+
|
11
|
+
from risk.log import params
|
12
|
+
from risk.network.graph.graph import Graph
|
13
|
+
from risk.network.plotter.canvas import Canvas
|
14
|
+
from risk.network.plotter.contour import Contour
|
15
|
+
from risk.network.plotter.labels import Labels
|
16
|
+
from risk.network.plotter.network import Network
|
17
|
+
from risk.network.plotter.utils.colors import to_rgba
|
18
|
+
from risk.network.plotter.utils.layout import calculate_bounding_box
|
19
|
+
|
20
|
+
|
21
|
+
class Plotter(Canvas, Network, Contour, Labels):
|
22
|
+
"""A class for visualizing network graphs with customizable options.
|
23
|
+
|
24
|
+
The Plotter class uses a Graph object and provides methods to plot the network with
|
25
|
+
flexible node and edge properties. It also supports plotting labels, contours, drawing the network's
|
26
|
+
perimeter, and adjusting background colors.
|
27
|
+
"""
|
28
|
+
|
29
|
+
def __init__(
|
30
|
+
self,
|
31
|
+
graph: Graph,
|
32
|
+
figsize: Tuple = (10, 10),
|
33
|
+
background_color: Union[str, List, Tuple, np.ndarray] = "white",
|
34
|
+
background_alpha: Union[float, None] = 1.0,
|
35
|
+
pad: float = 0.3,
|
36
|
+
) -> None:
|
37
|
+
"""Initialize the Plotter with a Graph object and plotting parameters.
|
38
|
+
|
39
|
+
Args:
|
40
|
+
graph (Graph): The network data and attributes to be visualized.
|
41
|
+
figsize (Tuple, optional): Size of the figure in inches (width, height). Defaults to (10, 10).
|
42
|
+
background_color (str, List, Tuple, np.ndarray, optional): Background color of the plot. Defaults to "white".
|
43
|
+
background_alpha (float, None, optional): Transparency level of the background color. If provided, it overrides
|
44
|
+
any existing alpha values found in background_color. Defaults to 1.0.
|
45
|
+
pad (float, optional): Padding value to adjust the axis limits. Defaults to 0.3.
|
46
|
+
"""
|
47
|
+
self.graph = graph
|
48
|
+
# Initialize the plot with the specified parameters
|
49
|
+
self.ax = self._initialize_plot(
|
50
|
+
graph=graph,
|
51
|
+
figsize=figsize,
|
52
|
+
background_color=background_color,
|
53
|
+
background_alpha=background_alpha,
|
54
|
+
pad=pad,
|
55
|
+
)
|
56
|
+
super().__init__(graph=graph, ax=self.ax)
|
57
|
+
|
58
|
+
def _initialize_plot(
|
59
|
+
self,
|
60
|
+
graph: Graph,
|
61
|
+
figsize: Tuple,
|
62
|
+
background_color: Union[str, List, Tuple, np.ndarray],
|
63
|
+
background_alpha: Union[float, None],
|
64
|
+
pad: float,
|
65
|
+
) -> plt.Axes:
|
66
|
+
"""Set up the plot with figure size and background color.
|
67
|
+
|
68
|
+
Args:
|
69
|
+
graph (Graph): The network data and attributes to be visualized.
|
70
|
+
figsize (Tuple): Size of the figure in inches (width, height).
|
71
|
+
background_color (str, List, Tuple, or np.ndarray): Background color of the plot. Can be a single color or an array of colors.
|
72
|
+
background_alpha (float, None, optional): Transparency level of the background color. If provided, it overrides any existing
|
73
|
+
alpha values found in `background_color`.
|
74
|
+
pad (float, optional): Padding value to adjust the axis limits.
|
75
|
+
|
76
|
+
Returns:
|
77
|
+
plt.Axes: The axis object for the plot.
|
78
|
+
"""
|
79
|
+
# Log the plotter settings
|
80
|
+
params.log_plotter(
|
81
|
+
figsize=figsize,
|
82
|
+
background_color=background_color,
|
83
|
+
background_alpha=background_alpha,
|
84
|
+
pad=pad,
|
85
|
+
)
|
86
|
+
|
87
|
+
# Extract node coordinates from the network graph
|
88
|
+
node_coordinates = graph.node_coordinates
|
89
|
+
# Calculate the center and radius of the bounding box around the network
|
90
|
+
center, radius = calculate_bounding_box(node_coordinates)
|
91
|
+
|
92
|
+
# Create a new figure and axis for plotting
|
93
|
+
fig, ax = plt.subplots(figsize=figsize)
|
94
|
+
fig.tight_layout() # Adjust subplot parameters to give specified padding
|
95
|
+
# Set axis limits based on the calculated bounding box and radius
|
96
|
+
ax.set_xlim([center[0] - radius - pad, center[0] + radius + pad])
|
97
|
+
ax.set_ylim([center[1] - radius - pad, center[1] + radius + pad])
|
98
|
+
ax.set_aspect("equal") # Ensure the aspect ratio is equal
|
99
|
+
|
100
|
+
# Set the background color of the plot
|
101
|
+
# Convert color to RGBA using the to_rgba helper function
|
102
|
+
fig.patch.set_facecolor(
|
103
|
+
to_rgba(color=background_color, alpha=background_alpha, num_repeats=1)
|
104
|
+
) # num_repeats=1 for single color
|
105
|
+
ax.invert_yaxis() # Invert the y-axis to match typical image coordinates
|
106
|
+
# Remove axis spines for a cleaner look
|
107
|
+
for spine in ax.spines.values():
|
108
|
+
spine.set_visible(False)
|
109
|
+
|
110
|
+
# Hide axis ticks and labels
|
111
|
+
ax.set_xticks([])
|
112
|
+
ax.set_yticks([])
|
113
|
+
ax.patch.set_visible(False) # Hide the axis background
|
114
|
+
|
115
|
+
return ax
|
116
|
+
|
117
|
+
@staticmethod
|
118
|
+
def savefig(*args, pad_inches: float = 0.5, dpi: int = 100, **kwargs) -> None:
|
119
|
+
"""Save the current plot to a file with additional export options.
|
120
|
+
|
121
|
+
Args:
|
122
|
+
*args: Positional arguments passed to `plt.savefig`.
|
123
|
+
pad_inches (float, optional): Padding around the figure when saving. Defaults to 0.5.
|
124
|
+
dpi (int, optional): Dots per inch (DPI) for the exported image. Defaults to 300.
|
125
|
+
**kwargs: Keyword arguments passed to `plt.savefig`, such as filename and format.
|
126
|
+
"""
|
127
|
+
# Ensure user-provided kwargs take precedence
|
128
|
+
kwargs.setdefault("dpi", dpi)
|
129
|
+
kwargs.setdefault("pad_inches", pad_inches)
|
130
|
+
# Ensure the plot is saved with tight bounding box if not specified
|
131
|
+
kwargs.setdefault("bbox_inches", "tight")
|
132
|
+
# Call plt.savefig with combined arguments
|
133
|
+
plt.savefig(*args, **kwargs)
|
134
|
+
|
135
|
+
@staticmethod
|
136
|
+
def show(*args, **kwargs) -> None:
|
137
|
+
"""Display the current plot.
|
138
|
+
|
139
|
+
Args:
|
140
|
+
*args: Positional arguments passed to `plt.show`.
|
141
|
+
**kwargs: Keyword arguments passed to `plt.show`.
|
142
|
+
"""
|
143
|
+
plt.show(*args, **kwargs)
|
@@ -1,6 +1,6 @@
|
|
1
1
|
"""
|
2
|
-
risk/network/
|
3
|
-
|
2
|
+
risk/network/plotter/utils/colors
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
4
4
|
"""
|
5
5
|
|
6
6
|
from typing import Any, Dict, List, Tuple, Union
|
@@ -9,11 +9,11 @@ import matplotlib
|
|
9
9
|
import matplotlib.colors as mcolors
|
10
10
|
import numpy as np
|
11
11
|
|
12
|
-
from risk.network.graph.
|
12
|
+
from risk.network.graph.graph import Graph
|
13
13
|
|
14
14
|
|
15
15
|
def get_annotated_domain_colors(
|
16
|
-
graph:
|
16
|
+
graph: Graph,
|
17
17
|
cmap: str = "gist_rainbow",
|
18
18
|
color: Union[str, List, Tuple, np.ndarray, None] = None,
|
19
19
|
blend_colors: bool = False,
|
@@ -27,7 +27,7 @@ def get_annotated_domain_colors(
|
|
27
27
|
"""Get colors for the domains based on node annotations, or use a specified color.
|
28
28
|
|
29
29
|
Args:
|
30
|
-
graph (
|
30
|
+
graph (Graph): The network data and attributes to be visualized.
|
31
31
|
cmap (str, optional): Colormap to use for generating domain colors. Defaults to "gist_rainbow".
|
32
32
|
color (str, List, Tuple, np.ndarray, or None, optional): Color to use for the domains. Can be a single color or an array of colors.
|
33
33
|
If None, the colormap will be used. Defaults to None.
|
@@ -72,7 +72,7 @@ def get_annotated_domain_colors(
|
|
72
72
|
|
73
73
|
|
74
74
|
def get_domain_colors(
|
75
|
-
graph:
|
75
|
+
graph: Graph,
|
76
76
|
cmap: str = "gist_rainbow",
|
77
77
|
color: Union[str, List, Tuple, np.ndarray, None] = None,
|
78
78
|
blend_colors: bool = False,
|
@@ -86,7 +86,7 @@ def get_domain_colors(
|
|
86
86
|
"""Generate composite colors for domains based on significance or specified colors.
|
87
87
|
|
88
88
|
Args:
|
89
|
-
graph (
|
89
|
+
graph (Graph): The network data and attributes to be visualized.
|
90
90
|
cmap (str, optional): Name of the colormap to use for generating domain colors. Defaults to "gist_rainbow".
|
91
91
|
color (str, List, Tuple, np.ndarray, or None, optional): A specific color or array of colors to use for all domains.
|
92
92
|
If None, the colormap will be used. Defaults to None.
|
@@ -127,7 +127,7 @@ def get_domain_colors(
|
|
127
127
|
|
128
128
|
|
129
129
|
def _get_domain_ids_to_colors(
|
130
|
-
graph:
|
130
|
+
graph: Graph,
|
131
131
|
cmap: str = "gist_rainbow",
|
132
132
|
color: Union[str, List, Tuple, np.ndarray, None] = None,
|
133
133
|
ids_to_colors: Union[Dict[int, Any], None] = None,
|
@@ -136,7 +136,7 @@ def _get_domain_ids_to_colors(
|
|
136
136
|
"""Get colors for each domain.
|
137
137
|
|
138
138
|
Args:
|
139
|
-
graph (
|
139
|
+
graph (Graph): The network data and attributes to be visualized.
|
140
140
|
cmap (str, optional): The name of the colormap to use. Defaults to "gist_rainbow".
|
141
141
|
color (str, List, Tuple, np.ndarray, or None, optional): A specific color or array of colors to use for the domains.
|
142
142
|
If None, the colormap will be used. Defaults to None.
|
@@ -167,7 +167,7 @@ def _get_domain_ids_to_colors(
|
|
167
167
|
|
168
168
|
|
169
169
|
def _get_composite_node_colors(
|
170
|
-
graph:
|
170
|
+
graph: Graph,
|
171
171
|
domain_ids_to_colors: Dict[int, Any],
|
172
172
|
blend_colors: bool = False,
|
173
173
|
blend_gamma: float = 2.2,
|
@@ -175,7 +175,7 @@ def _get_composite_node_colors(
|
|
175
175
|
"""Generate composite colors for nodes based on domain colors and significance values, with optional color blending.
|
176
176
|
|
177
177
|
Args:
|
178
|
-
graph (
|
178
|
+
graph (Graph): The network data and attributes to be visualized.
|
179
179
|
domain_ids_to_colors (Dict[int, Any]): Mapping of domain IDs to RGBA colors.
|
180
180
|
blend_colors (bool): Whether to blend colors for nodes with multiple domains. Defaults to False.
|
181
181
|
blend_gamma (float, optional): Gamma correction factor to be used for perceptual color blending.
|
risk/stats/stat_tests.py
CHANGED
@@ -10,8 +10,8 @@ from scipy.sparse import csr_matrix
|
|
10
10
|
from scipy.stats import binom
|
11
11
|
from scipy.stats import chi2
|
12
12
|
from scipy.stats import hypergeom
|
13
|
-
from scipy.stats import poisson
|
14
13
|
from scipy.stats import norm
|
14
|
+
from scipy.stats import poisson
|
15
15
|
|
16
16
|
|
17
17
|
def compute_binom_test(
|
@@ -131,34 +131,39 @@ def compute_hypergeom_test(
|
|
131
131
|
Returns:
|
132
132
|
Dict[str, Any]: Dictionary containing depletion and enrichment p-values.
|
133
133
|
"""
|
134
|
-
#
|
134
|
+
# Total number of nodes
|
135
135
|
total_nodes = neighborhoods.shape[1]
|
136
136
|
|
137
|
-
# Compute sums
|
138
|
-
neighborhood_sums = neighborhoods.sum(axis=0).A.flatten()
|
139
|
-
annotation_sums = annotations.sum(axis=0).A.flatten()
|
137
|
+
# Compute sums directly using sparse operations
|
138
|
+
neighborhood_sums = neighborhoods.sum(axis=0).A.flatten()
|
139
|
+
annotation_sums = annotations.sum(axis=0).A.flatten()
|
140
140
|
|
141
141
|
if null_distribution == "network":
|
142
142
|
background_population = total_nodes
|
143
143
|
elif null_distribution == "annotations":
|
144
|
-
|
144
|
+
# Boolean mask for nodes with annotations
|
145
|
+
annotated_nodes = annotations.getnnz(axis=1) > 0
|
145
146
|
background_population = annotated_nodes.sum()
|
146
|
-
|
147
|
-
|
147
|
+
# Filter neighborhoods and annotations to include only annotated nodes
|
148
|
+
neighborhoods = neighborhoods[annotated_nodes]
|
149
|
+
annotations = annotations[annotated_nodes]
|
150
|
+
neighborhood_sums = neighborhoods.sum(axis=0).A.flatten()
|
151
|
+
annotation_sums = annotations.sum(axis=0).A.flatten()
|
148
152
|
else:
|
149
153
|
raise ValueError(
|
150
154
|
"Invalid null_distribution value. Choose either 'network' or 'annotations'."
|
151
155
|
)
|
152
156
|
|
153
|
-
#
|
154
|
-
annotated_in_neighborhood = neighborhoods.T @ annotations # Sparse
|
155
|
-
|
157
|
+
# Compute annotated nodes in each neighborhood
|
158
|
+
annotated_in_neighborhood = neighborhoods.T @ annotations # Sparse multiplication
|
159
|
+
# Convert to dense arrays for vectorized operations
|
160
|
+
annotated_in_neighborhood = annotated_in_neighborhood.toarray()
|
156
161
|
# Align shapes for broadcasting
|
157
|
-
neighborhood_sums = neighborhood_sums.
|
158
|
-
annotation_sums = annotation_sums.
|
159
|
-
background_population = np.array(background_population)
|
162
|
+
neighborhood_sums = neighborhood_sums[:, np.newaxis]
|
163
|
+
annotation_sums = annotation_sums[np.newaxis, :]
|
164
|
+
background_population = np.array([[background_population]])
|
160
165
|
|
161
|
-
#
|
166
|
+
# Fully vectorized hypergeometric calculations
|
162
167
|
depletion_pvals = hypergeom.cdf(
|
163
168
|
annotated_in_neighborhood, background_population, annotation_sums, neighborhood_sums
|
164
169
|
)
|
@@ -1,4 +1,4 @@
|
|
1
|
-
risk/__init__.py,sha256=
|
1
|
+
risk/__init__.py,sha256=32Lq_wPcVY8stW7c0jkvgihM15jnYka5Hnw8M9gbjN0,127
|
2
2
|
risk/constants.py,sha256=XInRaH78Slnw_sWgAsBFbUHkyA0h0jL0DKGuQNbOvjM,550
|
3
3
|
risk/risk.py,sha256=s827_lRknFseOP9O4zW8sP-IcCd2EzrpV_tnVY_tz5s,1104
|
4
4
|
risk/annotations/__init__.py,sha256=parsbcux1U4urpUqh9AdzbDWuLj9HlMidycMPkpSQFo,179
|
@@ -16,25 +16,26 @@ risk/network/__init__.py,sha256=oVi3FA1XXKD84014Cykq-9bpX4_s0F3aAUfNOU-07Qw,73
|
|
16
16
|
risk/network/geometry.py,sha256=dU1hMq4j9gG0nkDqGRl_NiZ2Z-xvT_HF11FwEQ7oOR4,6570
|
17
17
|
risk/network/io.py,sha256=PqsRw1g7nfJJ3xs4aYcim3JWWLMFS1irgtg5hIyht5I,24376
|
18
18
|
risk/network/graph/__init__.py,sha256=ziGJew3yhtqvrb9LUuneDu_LwW2Wa9vd4UuhoL5l1CA,91
|
19
|
-
risk/network/graph/api.py,sha256=
|
20
|
-
risk/network/graph/
|
21
|
-
risk/network/graph/summary.py,sha256=
|
22
|
-
risk/network/plotter/__init__.py,sha256=
|
23
|
-
risk/network/plotter/api.py,sha256=
|
24
|
-
risk/network/plotter/canvas.py,sha256=
|
25
|
-
risk/network/plotter/contour.py,sha256=
|
26
|
-
risk/network/plotter/labels.py,sha256=
|
27
|
-
risk/network/plotter/network.py,sha256=
|
28
|
-
risk/network/plotter/
|
29
|
-
risk/network/plotter/utils/
|
19
|
+
risk/network/graph/api.py,sha256=t5Mh5_lD2uTLioEJFfCRe7ncc5iLNYzxd6r05wSiv7s,8169
|
20
|
+
risk/network/graph/graph.py,sha256=qEWyZvuaGT_vvjhreBdmRPX3gst2wQFaXhFAvikPSqw,12158
|
21
|
+
risk/network/graph/summary.py,sha256=eYJP78EHxu3ZhKoDCFshNxuEIB3dvH0PUg2T7qNkjC8,10289
|
22
|
+
risk/network/plotter/__init__.py,sha256=4gWtQHGzQVNHmEBXi31Zf0tX0y2sTcE66J_yGnn7268,99
|
23
|
+
risk/network/plotter/api.py,sha256=oJIj7vYv-3VpfN41ndCNtxcWIuhT2ULwAaPPU2f4oeM,1785
|
24
|
+
risk/network/plotter/canvas.py,sha256=ifyTMyXYRzlcdSYy6C23k3dmwtbLDrOfdMvEjkW2gLg,13460
|
25
|
+
risk/network/plotter/contour.py,sha256=oQDKmAKaEasnK1zqY7_bNctZ_IevZW2vxrbsnSrOSCI,15459
|
26
|
+
risk/network/plotter/labels.py,sha256=k5GWvgHS8bLekJk7Gtxy6G7tDeJDZPQ-z3VxYWjAWRM,45489
|
27
|
+
risk/network/plotter/network.py,sha256=0VySlJ4n3tkHsOhVVSa3yiSppT8y1dmIwa-DhRn0tcM,14131
|
28
|
+
risk/network/plotter/plotter.py,sha256=4PeAeutJbgvwy4USh5RdHALLtkmeAtaxQcd48r7Zxa0,5999
|
29
|
+
risk/network/plotter/utils/colors.py,sha256=VU1sLPRC99ll6EGK4vRNgLMUXU8lja1vjiXUL8GdfBE,18910
|
30
|
+
risk/network/plotter/utils/layout.py,sha256=OPqV8jzV9dpnOhYU4SYMSfsIXalVzESrlBSI_Y43OGU,3640
|
30
31
|
risk/stats/__init__.py,sha256=2zdLv3tUHKyAjwAo7LprVXRaak1cHgrpYMVMSik6JM4,324
|
31
32
|
risk/stats/significance.py,sha256=6cKv2xBQXWTHZ6HpNWIqlNfKKS5pG_BcCUdMM3r_zw4,7336
|
32
|
-
risk/stats/stat_tests.py,sha256=
|
33
|
+
risk/stats/stat_tests.py,sha256=qYn85VrNJeIlEptkEUoYsPco4BQ604CLJxXczgekXgc,11986
|
33
34
|
risk/stats/permutation/__init__.py,sha256=OLmYLm2uj96hPsSaUs0vUqFYw6Thwch_aHtpL7L0ZFw,127
|
34
35
|
risk/stats/permutation/permutation.py,sha256=BWjgdBpLVcHvmwHy0bmD4aJFccxifNBSrrCBPppyKf4,10569
|
35
36
|
risk/stats/permutation/test_functions.py,sha256=D3XMPM8CasUNytWSRce22TI6KK6XulYn5uGG4lWxaHs,3120
|
36
|
-
risk_network-0.0.
|
37
|
-
risk_network-0.0.
|
38
|
-
risk_network-0.0.
|
39
|
-
risk_network-0.0.
|
40
|
-
risk_network-0.0.
|
37
|
+
risk_network-0.0.9b28.dist-info/LICENSE,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
|
38
|
+
risk_network-0.0.9b28.dist-info/METADATA,sha256=v9uuUQ9EwyI5WzIirw_ONry2KPaiHqTiw2TDWX60Y6c,47627
|
39
|
+
risk_network-0.0.9b28.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
|
40
|
+
risk_network-0.0.9b28.dist-info/top_level.txt,sha256=NX7C2PFKTvC1JhVKv14DFlFAIFnKc6Lpsu1ZfxvQwVw,5
|
41
|
+
risk_network-0.0.9b28.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|