risk-network 0.0.12b0__py3-none-any.whl → 0.0.12b1__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.
Files changed (41) hide show
  1. risk/__init__.py +1 -1
  2. risk/annotations/__init__.py +10 -0
  3. risk/annotations/annotations.py +354 -0
  4. risk/annotations/io.py +241 -0
  5. risk/annotations/nltk_setup.py +86 -0
  6. risk/log/__init__.py +11 -0
  7. risk/log/console.py +141 -0
  8. risk/log/parameters.py +171 -0
  9. risk/neighborhoods/__init__.py +7 -0
  10. risk/neighborhoods/api.py +442 -0
  11. risk/neighborhoods/community.py +441 -0
  12. risk/neighborhoods/domains.py +360 -0
  13. risk/neighborhoods/neighborhoods.py +514 -0
  14. risk/neighborhoods/stats/__init__.py +13 -0
  15. risk/neighborhoods/stats/permutation/__init__.py +6 -0
  16. risk/neighborhoods/stats/permutation/permutation.py +240 -0
  17. risk/neighborhoods/stats/permutation/test_functions.py +70 -0
  18. risk/neighborhoods/stats/tests.py +275 -0
  19. risk/network/__init__.py +4 -0
  20. risk/network/graph/__init__.py +4 -0
  21. risk/network/graph/api.py +200 -0
  22. risk/network/graph/graph.py +268 -0
  23. risk/network/graph/stats.py +166 -0
  24. risk/network/graph/summary.py +253 -0
  25. risk/network/io.py +693 -0
  26. risk/network/plotter/__init__.py +4 -0
  27. risk/network/plotter/api.py +54 -0
  28. risk/network/plotter/canvas.py +291 -0
  29. risk/network/plotter/contour.py +329 -0
  30. risk/network/plotter/labels.py +935 -0
  31. risk/network/plotter/network.py +294 -0
  32. risk/network/plotter/plotter.py +141 -0
  33. risk/network/plotter/utils/colors.py +419 -0
  34. risk/network/plotter/utils/layout.py +94 -0
  35. risk_network-0.0.12b1.dist-info/METADATA +122 -0
  36. risk_network-0.0.12b1.dist-info/RECORD +40 -0
  37. {risk_network-0.0.12b0.dist-info → risk_network-0.0.12b1.dist-info}/WHEEL +1 -1
  38. risk_network-0.0.12b0.dist-info/METADATA +0 -796
  39. risk_network-0.0.12b0.dist-info/RECORD +0 -7
  40. {risk_network-0.0.12b0.dist-info → risk_network-0.0.12b1.dist-info}/licenses/LICENSE +0 -0
  41. {risk_network-0.0.12b0.dist-info → risk_network-0.0.12b1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,294 @@
1
+ """
2
+ risk/network/plotter/network
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4
+ """
5
+
6
+ from typing import Any, Dict, List, Tuple, Union
7
+
8
+ import networkx as nx
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.utils.colors import get_domain_colors, to_rgba
14
+
15
+
16
+ class Network:
17
+ """A class for plotting network graphs with customizable options.
18
+
19
+ The Network class provides methods to plot network graphs with flexible node and edge properties.
20
+ """
21
+
22
+ def __init__(self, graph: Graph, ax: Any = None) -> None:
23
+ """Initialize the Plotter class.
24
+
25
+ Args:
26
+ graph (Graph): The network data and attributes to be visualized.
27
+ ax (Any, optional): Axes object to plot the network graph. Defaults to None.
28
+ """
29
+ self.graph = graph
30
+ self.ax = ax
31
+
32
+ def plot_network(
33
+ self,
34
+ node_size: Union[int, np.ndarray] = 50,
35
+ node_shape: str = "o",
36
+ node_edgewidth: float = 1.0,
37
+ edge_width: float = 1.0,
38
+ node_color: Union[str, List, Tuple, np.ndarray] = "white",
39
+ node_edgecolor: Union[str, List, Tuple, np.ndarray] = "black",
40
+ edge_color: Union[str, List, Tuple, np.ndarray] = "black",
41
+ node_alpha: Union[float, None] = 1.0,
42
+ edge_alpha: Union[float, None] = 1.0,
43
+ ) -> None:
44
+ """Plot the network graph with customizable node colors, sizes, edge widths, and node edge widths.
45
+
46
+ Args:
47
+ node_size (int or np.ndarray, optional): Size of the nodes. Can be a single integer or an array of sizes. Defaults to 50.
48
+ node_shape (str, optional): Shape of the nodes. Defaults to "o".
49
+ node_edgewidth (float, optional): Width of the node edges. Defaults to 1.0.
50
+ edge_width (float, optional): Width of the edges. Defaults to 1.0.
51
+ node_color (str, List, Tuple, or np.ndarray, optional): Color of the nodes. Can be a single color or an array of colors.
52
+ Defaults to "white".
53
+ node_edgecolor (str, List, Tuple, or np.ndarray, optional): Color of the node edges. Can be a single color or an array of colors.
54
+ Defaults to "black".
55
+ edge_color (str, List, Tuple, or np.ndarray, optional): Color of the edges. Can be a single color or an array of colors.
56
+ Defaults to "black".
57
+ node_alpha (float, None, optional): Alpha value (transparency) for the nodes. If provided, it overrides any existing alpha
58
+ values found in node_color. Defaults to 1.0. Annotated node_color alphas will override this value.
59
+ edge_alpha (float, None, optional): Alpha value (transparency) for the edges. If provided, it overrides any existing alpha
60
+ values found in edge_color. Defaults to 1.0.
61
+ """
62
+ # Log the plotting parameters
63
+ params.log_plotter(
64
+ network_node_size=(
65
+ "custom" if isinstance(node_size, np.ndarray) else node_size
66
+ ), # np.ndarray usually indicates custom sizes
67
+ network_node_shape=node_shape,
68
+ network_node_edgewidth=node_edgewidth,
69
+ network_edge_width=edge_width,
70
+ network_node_color=(
71
+ "custom" if isinstance(node_color, np.ndarray) else node_color
72
+ ), # np.ndarray usually indicates custom colors
73
+ network_node_edgecolor=node_edgecolor,
74
+ network_edge_color=edge_color,
75
+ network_node_alpha=node_alpha,
76
+ network_edge_alpha=edge_alpha,
77
+ )
78
+
79
+ # Convert colors to RGBA using the to_rgba helper function
80
+ # If node_colors was generated using get_annotated_node_colors, its alpha values will override node_alpha
81
+ node_color_rgba = to_rgba(
82
+ color=node_color, alpha=node_alpha, num_repeats=len(self.graph.network.nodes)
83
+ )
84
+ node_edgecolor_rgba = to_rgba(
85
+ color=node_edgecolor, alpha=1.0, num_repeats=len(self.graph.network.nodes)
86
+ )
87
+ edge_color_rgba = to_rgba(
88
+ color=edge_color, alpha=edge_alpha, num_repeats=len(self.graph.network.edges)
89
+ )
90
+
91
+ # Extract node coordinates from the network graph
92
+ node_coordinates = self.graph.node_coordinates
93
+
94
+ # Draw the nodes of the graph
95
+ nx.draw_networkx_nodes(
96
+ self.graph.network,
97
+ pos=node_coordinates,
98
+ node_size=node_size,
99
+ node_shape=node_shape,
100
+ node_color=node_color_rgba,
101
+ edgecolors=node_edgecolor_rgba,
102
+ linewidths=node_edgewidth,
103
+ ax=self.ax,
104
+ )
105
+ # Draw the edges of the graph
106
+ nx.draw_networkx_edges(
107
+ self.graph.network,
108
+ pos=node_coordinates,
109
+ width=edge_width,
110
+ edge_color=edge_color_rgba,
111
+ ax=self.ax,
112
+ )
113
+
114
+ def plot_subnetwork(
115
+ self,
116
+ nodes: Union[List, Tuple, np.ndarray],
117
+ node_size: Union[int, np.ndarray] = 50,
118
+ node_shape: str = "o",
119
+ node_edgewidth: float = 1.0,
120
+ edge_width: float = 1.0,
121
+ node_color: Union[str, List, Tuple, np.ndarray] = "white",
122
+ node_edgecolor: Union[str, List, Tuple, np.ndarray] = "black",
123
+ edge_color: Union[str, List, Tuple, np.ndarray] = "black",
124
+ node_alpha: Union[float, None] = None,
125
+ edge_alpha: Union[float, None] = None,
126
+ ) -> None:
127
+ """Plot a subnetwork of selected nodes with customizable node and edge attributes.
128
+
129
+ Args:
130
+ nodes (List, Tuple, or np.ndarray): List of node labels to include in the subnetwork. Accepts nested lists.
131
+ node_size (int or np.ndarray, optional): Size of the nodes. Can be a single integer or an array of sizes. Defaults to 50.
132
+ node_shape (str, optional): Shape of the nodes. Defaults to "o".
133
+ node_edgewidth (float, optional): Width of the node edges. Defaults to 1.0.
134
+ edge_width (float, optional): Width of the edges. Defaults to 1.0.
135
+ node_color (str, List, Tuple, or np.ndarray, optional): Color of the nodes. Defaults to "white".
136
+ node_edgecolor (str, List, Tuple, or np.ndarray, optional): Color of the node edges. Defaults to "black".
137
+ edge_color (str, List, Tuple, or np.ndarray, optional): Color of the edges. Defaults to "black".
138
+ node_alpha (float, None, optional): Transparency for the nodes. If provided, it overrides any existing alpha values
139
+ found in node_color. Defaults to 1.0.
140
+ edge_alpha (float, None, optional): Transparency for the edges. If provided, it overrides any existing alpha values
141
+ found in node_color. Defaults to 1.0.
142
+
143
+ Raises:
144
+ ValueError: If no valid nodes are found in the network graph.
145
+ """
146
+ # Flatten nested lists of nodes, if necessary
147
+ if any(isinstance(item, (list, tuple, np.ndarray)) for item in nodes):
148
+ nodes = [node for sublist in nodes for node in sublist]
149
+
150
+ # Filter to get node IDs and their coordinates
151
+ node_ids = [
152
+ self.graph.node_label_to_node_id_map.get(node)
153
+ for node in nodes
154
+ if node in self.graph.node_label_to_node_id_map
155
+ ]
156
+ if not node_ids:
157
+ raise ValueError("No nodes found in the network graph.")
158
+
159
+ # Check if node_color is a single color or a list of colors
160
+ if not isinstance(node_color, (str, Tuple, np.ndarray)):
161
+ node_color = [
162
+ node_color[nodes.index(node)]
163
+ for node in nodes
164
+ if node in self.graph.node_label_to_node_id_map
165
+ ]
166
+
167
+ # Convert colors to RGBA using the to_rgba helper function
168
+ node_color_rgba = to_rgba(color=node_color, alpha=node_alpha, num_repeats=len(node_ids))
169
+ node_edgecolor_rgba = to_rgba(color=node_edgecolor, alpha=1.0, num_repeats=len(node_ids))
170
+ edge_color_rgba = to_rgba(
171
+ color=edge_color, alpha=edge_alpha, num_repeats=len(self.graph.network.edges)
172
+ )
173
+
174
+ # Get the coordinates of the filtered nodes
175
+ node_coordinates = {node_id: self.graph.node_coordinates[node_id] for node_id in node_ids}
176
+
177
+ # Draw the nodes in the subnetwork
178
+ nx.draw_networkx_nodes(
179
+ self.graph.network,
180
+ pos=node_coordinates,
181
+ nodelist=node_ids,
182
+ node_size=node_size,
183
+ node_shape=node_shape,
184
+ node_color=node_color_rgba,
185
+ edgecolors=node_edgecolor_rgba,
186
+ linewidths=node_edgewidth,
187
+ ax=self.ax,
188
+ )
189
+ # Draw the edges between the specified nodes in the subnetwork
190
+ subgraph = self.graph.network.subgraph(node_ids)
191
+ nx.draw_networkx_edges(
192
+ subgraph,
193
+ pos=node_coordinates,
194
+ width=edge_width,
195
+ edge_color=edge_color_rgba,
196
+ ax=self.ax,
197
+ )
198
+
199
+ def get_annotated_node_colors(
200
+ self,
201
+ cmap: str = "gist_rainbow",
202
+ color: Union[str, List, Tuple, np.ndarray, None] = None,
203
+ blend_colors: bool = False,
204
+ blend_gamma: float = 2.2,
205
+ min_scale: float = 0.8,
206
+ max_scale: float = 1.0,
207
+ scale_factor: float = 1.0,
208
+ alpha: Union[float, None] = 1.0,
209
+ nonsignificant_color: Union[str, List, Tuple, np.ndarray] = "white",
210
+ nonsignificant_alpha: Union[float, None] = 1.0,
211
+ ids_to_colors: Union[Dict[int, Any], None] = None,
212
+ random_seed: int = 888,
213
+ ) -> np.ndarray:
214
+ """Adjust the colors of nodes in the network graph based on significance.
215
+
216
+ Args:
217
+ cmap (str, optional): Colormap to use for coloring the nodes. Defaults to "gist_rainbow".
218
+ color (str, List, Tuple, np.ndarray, or None, optional): Color to use for the nodes. Can be a single color or an array of colors.
219
+ If None, the colormap will be used. Defaults to None.
220
+ blend_colors (bool, optional): Whether to blend colors for nodes with multiple domains. Defaults to False.
221
+ blend_gamma (float, optional): Gamma correction factor for perceptual color blending. Defaults to 2.2.
222
+ min_scale (float, optional): Minimum scale for color intensity. Defaults to 0.8.
223
+ max_scale (float, optional): Maximum scale for color intensity. Defaults to 1.0.
224
+ scale_factor (float, optional): Factor for adjusting the color scaling intensity. Defaults to 1.0.
225
+ alpha (float, None, optional): Alpha value for significant nodes. If provided, it overrides any existing alpha values found in `color`.
226
+ Defaults to 1.0.
227
+ nonsignificant_color (str, List, Tuple, or np.ndarray, optional): Color for non-significant nodes. Can be a single color or an array of colors.
228
+ Defaults to "white".
229
+ nonsignificant_alpha (float, None, optional): Alpha value for non-significant nodes. If provided, it overrides any existing alpha values found
230
+ in `nonsignificant_color`. Defaults to 1.0.
231
+ ids_to_colors (Dict[int, Any], None, optional): Mapping of domain IDs to specific colors. Defaults to None.
232
+ random_seed (int, optional): Seed for random number generation. Defaults to 888.
233
+
234
+ Returns:
235
+ np.ndarray: Array of RGBA colors adjusted for significance status.
236
+ """
237
+ # Get the initial domain colors for each node, which are returned as RGBA
238
+ network_colors = get_domain_colors(
239
+ graph=self.graph,
240
+ cmap=cmap,
241
+ color=color,
242
+ blend_colors=blend_colors,
243
+ blend_gamma=blend_gamma,
244
+ min_scale=min_scale,
245
+ max_scale=max_scale,
246
+ scale_factor=scale_factor,
247
+ ids_to_colors=ids_to_colors,
248
+ random_seed=random_seed,
249
+ )
250
+ # Apply the alpha value for significant nodes
251
+ network_colors[:, 3] = alpha # Apply the alpha value to the significant nodes' A channel
252
+ # Convert the non-significant color to RGBA using the to_rgba helper function
253
+ nonsignificant_color_rgba = to_rgba(
254
+ color=nonsignificant_color, alpha=nonsignificant_alpha, num_repeats=1
255
+ ) # num_repeats=1 for a single color
256
+ # Adjust node colors: replace any nodes where all three RGB values are equal and less than or equal to 0.1
257
+ # 0.1 is a predefined threshold for the minimum color intensity
258
+ adjusted_network_colors = np.where(
259
+ (
260
+ np.all(network_colors[:, :3] <= 0.1, axis=1)
261
+ & np.all(network_colors[:, :3] == network_colors[:, 0:1], axis=1)
262
+ )[:, None],
263
+ np.tile(
264
+ np.array(nonsignificant_color_rgba), (network_colors.shape[0], 1)
265
+ ), # Replace with the full RGBA non-significant color
266
+ network_colors, # Keep the original colors where no match is found
267
+ )
268
+ return adjusted_network_colors
269
+
270
+ def get_annotated_node_sizes(
271
+ self, significant_size: int = 50, nonsignificant_size: int = 25
272
+ ) -> np.ndarray:
273
+ """Adjust the sizes of nodes in the network graph based on whether they are significant or not.
274
+
275
+ Args:
276
+ significant_size (int): Size for significant nodes. Defaults to 50.
277
+ nonsignificant_size (int): Size for non-significant nodes. Defaults to 25.
278
+
279
+ Returns:
280
+ np.ndarray: Array of node sizes, with significant nodes larger than non-significant ones.
281
+ """
282
+ # Merge all significant nodes from the domain_id_to_node_ids_map dictionary
283
+ significant_nodes = set()
284
+ for _, node_ids in self.graph.domain_id_to_node_ids_map.items():
285
+ significant_nodes.update(node_ids)
286
+
287
+ # Initialize all node sizes to the non-significant size
288
+ node_sizes = np.full(len(self.graph.network.nodes), nonsignificant_size)
289
+ # Set the size for significant nodes
290
+ for node in significant_nodes:
291
+ if node in self.graph.network.nodes:
292
+ node_sizes[node] = significant_size
293
+
294
+ return node_sizes
@@ -0,0 +1,141 @@
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
+ def savefig(self, *args, pad_inches: float = 0.5, dpi: int = 100, **kwargs) -> None:
118
+ """Save the current plot to a file with additional export options.
119
+
120
+ Args:
121
+ *args: Positional arguments passed to `plt.savefig`.
122
+ pad_inches (float, optional): Padding around the figure when saving. Defaults to 0.5.
123
+ dpi (int, optional): Dots per inch (DPI) for the exported image. Defaults to 300.
124
+ **kwargs: Keyword arguments passed to `plt.savefig`, such as filename and format.
125
+ """
126
+ # Ensure user-provided kwargs take precedence
127
+ kwargs.setdefault("dpi", dpi)
128
+ kwargs.setdefault("pad_inches", pad_inches)
129
+ # Ensure the plot is saved with tight bounding box if not specified
130
+ kwargs.setdefault("bbox_inches", "tight")
131
+ # Call plt.savefig with combined arguments
132
+ plt.savefig(*args, **kwargs)
133
+
134
+ def show(self, *args, **kwargs) -> None:
135
+ """Display the current plot.
136
+
137
+ Args:
138
+ *args: Positional arguments passed to `plt.show`.
139
+ **kwargs: Keyword arguments passed to `plt.show`.
140
+ """
141
+ plt.show(*args, **kwargs)