risk-network 0.0.3b0__cp38-cp38-win32.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/network/plot.py ADDED
@@ -0,0 +1,804 @@
1
+ """
2
+ risk/network/plot
3
+ ~~~~~~~~~~~~~~~~~
4
+ """
5
+
6
+ from typing import Any, Dict, List, Tuple, Union
7
+
8
+ import matplotlib
9
+ import matplotlib.colors as mcolors
10
+ import matplotlib.pyplot as plt
11
+ import networkx as nx
12
+ import numpy as np
13
+ from scipy.ndimage import label
14
+ from scipy.stats import gaussian_kde
15
+
16
+ from risk.log import params
17
+ from risk.network.graph import NetworkGraph
18
+
19
+
20
+ class NetworkPlotter:
21
+ """A class responsible for visualizing network graphs with various customization options.
22
+
23
+ The NetworkPlotter class takes in a NetworkGraph object, which contains the network's data and attributes,
24
+ and provides methods for plotting the network with customizable node and edge properties,
25
+ as well as optional features like drawing the network's perimeter and setting background colors.
26
+ """
27
+
28
+ def __init__(
29
+ self,
30
+ network_graph: NetworkGraph,
31
+ figsize: tuple = (10, 10),
32
+ background_color: str = "white",
33
+ plot_outline: bool = True,
34
+ outline_color: str = "black",
35
+ outline_scale: float = 1.0,
36
+ ) -> None:
37
+ """Initialize the NetworkPlotter with a NetworkGraph object and plotting parameters.
38
+
39
+ Args:
40
+ network_graph (NetworkGraph): 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, optional): Background color of the plot. Defaults to "white".
43
+ plot_outline (bool, optional): Whether to plot the network perimeter circle. Defaults to True.
44
+ outline_color (str, optional): Color of the network perimeter circle. Defaults to "black".
45
+ outline_scale (float, optional): Outline scaling factor for the perimeter diameter. Defaults to 1.0.
46
+ """
47
+ self.network_graph = network_graph
48
+ self.ax = None # Initialize the axis attribute
49
+ # Initialize the plot with the given parameters
50
+ self._initialize_plot(figsize, background_color, plot_outline, outline_color, outline_scale)
51
+
52
+ def _initialize_plot(
53
+ self,
54
+ figsize: tuple,
55
+ background_color: str,
56
+ plot_outline: bool,
57
+ outline_color: str,
58
+ outline_scale: float,
59
+ ) -> tuple:
60
+ """Set up the plot with figure size, optional circle perimeter, and background color.
61
+
62
+ Args:
63
+ figsize (tuple): Size of the figure in inches (width, height).
64
+ background_color (str): Background color of the plot.
65
+ plot_outline (bool): Whether to plot the network perimeter circle.
66
+ outline_color (str): Color of the network perimeter circle.
67
+ outline_scale (float): Outline scaling factor for the perimeter diameter.
68
+
69
+ Returns:
70
+ tuple: The created matplotlib figure and axis.
71
+ """
72
+ # Extract node coordinates from the network graph
73
+ node_coordinates = self.network_graph.node_coordinates
74
+ # Calculate the center and radius of the bounding box around the network
75
+ center, radius = _calculate_bounding_box(node_coordinates)
76
+ # Scale the radius by the outline_scale factor
77
+ scaled_radius = radius * outline_scale
78
+
79
+ # Create a new figure and axis for plotting
80
+ fig, ax = plt.subplots(figsize=figsize)
81
+ fig.tight_layout() # Adjust subplot parameters to give specified padding
82
+ if plot_outline:
83
+ # Draw a circle to represent the network perimeter
84
+ circle = plt.Circle(
85
+ center,
86
+ scaled_radius,
87
+ linestyle="--",
88
+ color=outline_color,
89
+ fill=False,
90
+ linewidth=1.5,
91
+ )
92
+ ax.add_artist(circle) # Add the circle to the plot
93
+
94
+ # Set axis limits based on the calculated bounding box and scaled radius
95
+ ax.set_xlim([center[0] - scaled_radius - 0.3, center[0] + scaled_radius + 0.3])
96
+ ax.set_ylim([center[1] - scaled_radius - 0.3, center[1] + scaled_radius + 0.3])
97
+ ax.set_aspect("equal") # Ensure the aspect ratio is equal
98
+ fig.patch.set_facecolor(background_color) # Set the figure background color
99
+ ax.invert_yaxis() # Invert the y-axis to match typical image coordinates
100
+
101
+ # Remove axis spines for a cleaner look
102
+ for spine in ax.spines.values():
103
+ spine.set_visible(False)
104
+
105
+ # Hide axis ticks and labels
106
+ ax.set_xticks([])
107
+ ax.set_yticks([])
108
+ ax.patch.set_visible(False) # Hide the axis background
109
+
110
+ # Store the axis for further use and return the figure and axis
111
+ self.ax = ax
112
+ return fig, ax
113
+
114
+ def plot_network(
115
+ self,
116
+ node_size: Union[int, np.ndarray] = 50,
117
+ edge_width: float = 1.0,
118
+ node_color: Union[str, np.ndarray] = "white",
119
+ node_edgecolor: str = "black",
120
+ edge_color: str = "black",
121
+ node_shape: str = "o",
122
+ ) -> None:
123
+ """Plot the network graph with customizable node colors, sizes, and edge widths.
124
+
125
+ Args:
126
+ node_size (int or np.ndarray, optional): Size of the nodes. Can be a single integer or an array of sizes. Defaults to 50.
127
+ edge_width (float, optional): Width of the edges. Defaults to 1.0.
128
+ node_color (str or np.ndarray, optional): Color of the nodes. Can be a single color or an array of colors. Defaults to "white".
129
+ node_edgecolor (str, optional): Color of the node edges. Defaults to "black".
130
+ edge_color (str, optional): Color of the edges. Defaults to "black".
131
+ node_shape (str, optional): Shape of the nodes. Defaults to "o".
132
+ """
133
+ # Log the plotting parameters
134
+ params.log_plotter(
135
+ network_node_size="custom" if isinstance(node_size, np.ndarray) else node_size,
136
+ network_edge_width=edge_width,
137
+ network_node_color="custom" if isinstance(node_color, np.ndarray) else node_color,
138
+ network_node_edgecolor=node_edgecolor,
139
+ network_edge_color=edge_color,
140
+ network_node_shape=node_shape,
141
+ )
142
+ # Extract node coordinates from the network graph
143
+ node_coordinates = self.network_graph.node_coordinates
144
+ # Draw the nodes of the graph
145
+ nx.draw_networkx_nodes(
146
+ self.network_graph.G,
147
+ pos=node_coordinates,
148
+ node_size=node_size,
149
+ node_color=node_color,
150
+ node_shape=node_shape,
151
+ alpha=1.00,
152
+ edgecolors=node_edgecolor,
153
+ ax=self.ax,
154
+ )
155
+ # Draw the edges of the graph
156
+ nx.draw_networkx_edges(
157
+ self.network_graph.G,
158
+ pos=node_coordinates,
159
+ width=edge_width,
160
+ edge_color=edge_color,
161
+ ax=self.ax,
162
+ )
163
+
164
+ def plot_subnetwork(
165
+ self,
166
+ nodes: list,
167
+ node_size: Union[int, np.ndarray] = 50,
168
+ edge_width: float = 1.0,
169
+ node_color: Union[str, np.ndarray] = "white",
170
+ node_edgecolor: str = "black",
171
+ edge_color: str = "black",
172
+ node_shape: str = "o",
173
+ ) -> None:
174
+ """Plot a subnetwork of selected nodes with customizable node and edge attributes.
175
+
176
+ Args:
177
+ nodes (list): List of node labels to include in the subnetwork.
178
+ node_size (int or np.ndarray, optional): Size of the nodes. Can be a single integer or an array of sizes. Defaults to 50.
179
+ edge_width (float, optional): Width of the edges. Defaults to 1.0.
180
+ node_color (str or np.ndarray, optional): Color of the nodes. Can be a single color or an array of colors. Defaults to "white".
181
+ node_edgecolor (str, optional): Color of the node edges. Defaults to "black".
182
+ edge_color (str, optional): Color of the edges. Defaults to "black".
183
+ node_shape (str, optional): Shape of the nodes. Defaults to "o".
184
+
185
+ Raises:
186
+ ValueError: If no valid nodes are found in the network graph.
187
+ """
188
+ # Log the plotting parameters for the subnetwork
189
+ params.log_plotter(
190
+ subnetwork_node_size="custom" if isinstance(node_size, np.ndarray) else node_size,
191
+ subnetwork_edge_width=edge_width,
192
+ subnetwork_node_color="custom" if isinstance(node_color, np.ndarray) else node_color,
193
+ subnetwork_node_edgecolor=node_edgecolor,
194
+ subnetwork_edge_color=edge_color,
195
+ subnet_node_shape=node_shape,
196
+ )
197
+ # Filter to get node IDs and their coordinates
198
+ node_ids = [
199
+ self.network_graph.node_label_to_id_map.get(node)
200
+ for node in nodes
201
+ if node in self.network_graph.node_label_to_id_map
202
+ ]
203
+ if not node_ids:
204
+ raise ValueError("No nodes found in the network graph.")
205
+
206
+ # Get the coordinates of the filtered nodes
207
+ node_coordinates = {
208
+ node_id: self.network_graph.node_coordinates[node_id] for node_id in node_ids
209
+ }
210
+ # Draw the nodes in the subnetwork
211
+ nx.draw_networkx_nodes(
212
+ self.network_graph.G,
213
+ pos=node_coordinates,
214
+ nodelist=node_ids,
215
+ node_size=node_size,
216
+ node_color=node_color,
217
+ node_shape=node_shape,
218
+ alpha=1.00,
219
+ edgecolors=node_edgecolor,
220
+ ax=self.ax,
221
+ )
222
+ # Draw the edges between the specified nodes in the subnetwork
223
+ subgraph = self.network_graph.G.subgraph(node_ids)
224
+ nx.draw_networkx_edges(
225
+ subgraph,
226
+ pos=node_coordinates,
227
+ width=edge_width,
228
+ edge_color=edge_color,
229
+ ax=self.ax,
230
+ )
231
+
232
+ def plot_contours(
233
+ self,
234
+ levels: int = 5,
235
+ bandwidth: float = 0.8,
236
+ grid_size: int = 250,
237
+ alpha: float = 0.2,
238
+ color: Union[str, np.ndarray] = "white",
239
+ ) -> None:
240
+ """Draw KDE contours for nodes in various domains of a network graph, highlighting areas of high density.
241
+
242
+ Args:
243
+ levels (int, optional): Number of contour levels to plot. Defaults to 5.
244
+ bandwidth (float, optional): Bandwidth for KDE. Controls the smoothness of the contour. Defaults to 0.8.
245
+ grid_size (int, optional): Resolution of the grid for KDE. Higher values create finer contours. Defaults to 250.
246
+ alpha (float, optional): Transparency level of the contour fill. Defaults to 0.2.
247
+ color (str or np.ndarray, optional): Color of the contours. Can be a string (e.g., 'white') or an array of colors. Defaults to "white".
248
+ """
249
+ # Log the contour plotting parameters
250
+ params.log_plotter(
251
+ contour_levels=levels,
252
+ contour_bandwidth=bandwidth,
253
+ contour_grid_size=grid_size,
254
+ contour_alpha=alpha,
255
+ contour_color="custom" if isinstance(color, np.ndarray) else color,
256
+ )
257
+ # Convert color string to RGBA array if necessary
258
+ if isinstance(color, str):
259
+ color = self.get_annotated_contour_colors(color=color)
260
+
261
+ # Extract node coordinates from the network graph
262
+ node_coordinates = self.network_graph.node_coordinates
263
+ # Draw contours for each domain in the network
264
+ for idx, (_, nodes) in enumerate(self.network_graph.domain_to_nodes.items()):
265
+ if len(nodes) > 1:
266
+ self._draw_kde_contour(
267
+ self.ax,
268
+ node_coordinates,
269
+ nodes,
270
+ color=color[idx],
271
+ levels=levels,
272
+ bandwidth=bandwidth,
273
+ grid_size=grid_size,
274
+ alpha=alpha,
275
+ )
276
+
277
+ def plot_subcontour(
278
+ self,
279
+ nodes: list,
280
+ levels: int = 5,
281
+ bandwidth: float = 0.8,
282
+ grid_size: int = 250,
283
+ alpha: float = 0.2,
284
+ color: Union[str, np.ndarray] = "white",
285
+ ) -> None:
286
+ """Plot a subcontour for a given set of nodes using Kernel Density Estimation (KDE).
287
+
288
+ Args:
289
+ nodes (list): List of node labels to plot the contour for.
290
+ levels (int, optional): Number of contour levels to plot. Defaults to 5.
291
+ bandwidth (float, optional): Bandwidth for KDE. Controls the smoothness of the contour. Defaults to 0.8.
292
+ grid_size (int, optional): Resolution of the grid for KDE. Higher values create finer contours. Defaults to 250.
293
+ alpha (float, optional): Transparency level of the contour fill. Defaults to 0.2.
294
+ color (str or np.ndarray, optional): Color of the contour. Can be a string (e.g., 'white') or RGBA array. Defaults to "white".
295
+
296
+ Raises:
297
+ ValueError: If no valid nodes are found in the network graph.
298
+ """
299
+ # Log the plotting parameters
300
+ params.log_plotter(
301
+ contour_levels=levels,
302
+ contour_bandwidth=bandwidth,
303
+ contour_grid_size=grid_size,
304
+ contour_alpha=alpha,
305
+ contour_color="custom" if isinstance(color, np.ndarray) else color,
306
+ )
307
+ # Filter to get node IDs and their coordinates
308
+ node_ids = [
309
+ self.network_graph.node_label_to_id_map.get(node)
310
+ for node in nodes
311
+ if node in self.network_graph.node_label_to_id_map
312
+ ]
313
+ if not node_ids or len(node_ids) == 1:
314
+ raise ValueError("No nodes found in the network graph or insufficient nodes to plot.")
315
+
316
+ # Draw the KDE contour for the specified nodes
317
+ node_coordinates = self.network_graph.node_coordinates
318
+ self._draw_kde_contour(
319
+ self.ax,
320
+ node_coordinates,
321
+ node_ids,
322
+ color=color,
323
+ levels=levels,
324
+ bandwidth=bandwidth,
325
+ grid_size=grid_size,
326
+ alpha=alpha,
327
+ )
328
+
329
+ def _draw_kde_contour(
330
+ self,
331
+ ax: plt.Axes,
332
+ pos: np.ndarray,
333
+ nodes: list,
334
+ color: Union[str, np.ndarray],
335
+ levels: int = 5,
336
+ bandwidth: float = 0.8,
337
+ grid_size: int = 250,
338
+ alpha: float = 0.5,
339
+ ) -> None:
340
+ """Draw a Kernel Density Estimate (KDE) contour plot for a set of nodes on a given axis.
341
+
342
+ Args:
343
+ ax (plt.Axes): The axis to draw the contour on.
344
+ pos (np.ndarray): Array of node positions (x, y).
345
+ nodes (list): List of node indices to include in the contour.
346
+ color (str or np.ndarray): Color for the contour.
347
+ levels (int, optional): Number of contour levels. Defaults to 5.
348
+ bandwidth (float, optional): Bandwidth for the KDE. Controls smoothness. Defaults to 0.8.
349
+ grid_size (int, optional): Grid resolution for the KDE. Higher values yield finer contours. Defaults to 250.
350
+ alpha (float, optional): Transparency level for the contour fill. Defaults to 0.5.
351
+ """
352
+ # Extract the positions of the specified nodes
353
+ points = np.array([pos[n] for n in nodes])
354
+ if len(points) <= 1:
355
+ return # Not enough points to form a contour
356
+
357
+ connected = False
358
+ while not connected and bandwidth <= 100.0:
359
+ # Perform KDE on the points with the given bandwidth
360
+ kde = gaussian_kde(points.T, bw_method=bandwidth)
361
+ xmin, ymin = points.min(axis=0) - bandwidth
362
+ xmax, ymax = points.max(axis=0) + bandwidth
363
+ x, y = np.mgrid[
364
+ xmin : xmax : complex(0, grid_size), ymin : ymax : complex(0, grid_size)
365
+ ]
366
+ z = kde(np.vstack([x.ravel(), y.ravel()])).reshape(x.shape)
367
+ # Check if the KDE forms a single connected component
368
+ connected = _is_connected(z)
369
+ if not connected:
370
+ bandwidth += 0.05 # Increase bandwidth slightly and retry
371
+
372
+ # Define contour levels based on the density
373
+ min_density, max_density = z.min(), z.max()
374
+ contour_levels = np.linspace(min_density, max_density, levels)[1:]
375
+ contour_colors = [color for _ in range(levels - 1)]
376
+
377
+ # Plot the filled contours if alpha > 0
378
+ if alpha > 0:
379
+ ax.contourf(
380
+ x,
381
+ y,
382
+ z,
383
+ levels=contour_levels,
384
+ colors=contour_colors,
385
+ alpha=alpha,
386
+ extend="neither",
387
+ antialiased=True,
388
+ )
389
+
390
+ # Plot the contour lines without antialiasing for clarity
391
+ c = ax.contour(x, y, z, levels=contour_levels, colors=contour_colors)
392
+ for i in range(1, len(contour_levels)):
393
+ c.collections[i].set_linewidth(0)
394
+
395
+ def plot_labels(
396
+ self,
397
+ perimeter_scale: float = 1.05,
398
+ offset: float = 0.10,
399
+ font: str = "Arial",
400
+ fontsize: int = 10,
401
+ fontcolor: Union[str, np.ndarray] = "black",
402
+ arrow_linewidth: float = 1,
403
+ arrow_color: Union[str, np.ndarray] = "black",
404
+ num_words: int = 10,
405
+ min_words: int = 1,
406
+ ) -> None:
407
+ """Annotate the network graph with labels for different domains, positioned around the network for clarity.
408
+
409
+ Args:
410
+ perimeter_scale (float, optional): Scale factor for positioning labels around the perimeter. Defaults to 1.05.
411
+ offset (float, optional): Offset distance for labels from the perimeter. Defaults to 0.10.
412
+ font (str, optional): Font name for the labels. Defaults to "Arial".
413
+ fontsize (int, optional): Font size for the labels. Defaults to 10.
414
+ fontcolor (str or np.ndarray, optional): Color of the label text. Can be a string or RGBA array. Defaults to "black".
415
+ arrow_linewidth (float, optional): Line width of the arrows pointing to centroids. Defaults to 1.
416
+ arrow_color (str or np.ndarray, optional): Color of the arrows. Can be a string or RGBA array. Defaults to "black".
417
+ num_words (int, optional): Maximum number of words in a label. Defaults to 10.
418
+ min_words (int, optional): Minimum number of words required to display a label. Defaults to 1.
419
+ """
420
+ # Log the plotting parameters
421
+ params.log_plotter(
422
+ label_perimeter_scale=perimeter_scale,
423
+ label_offset=offset,
424
+ label_font=font,
425
+ label_fontsize=fontsize,
426
+ label_fontcolor="custom" if isinstance(fontcolor, np.ndarray) else fontcolor,
427
+ label_arrow_linewidth=arrow_linewidth,
428
+ label_arrow_color="custom" if isinstance(arrow_color, np.ndarray) else arrow_color,
429
+ label_num_words=num_words,
430
+ label_min_words=min_words,
431
+ )
432
+ # Convert color strings to RGBA arrays if necessary
433
+ if isinstance(fontcolor, str):
434
+ fontcolor = self.get_annotated_contour_colors(color=fontcolor)
435
+ if isinstance(arrow_color, str):
436
+ arrow_color = self.get_annotated_contour_colors(color=arrow_color)
437
+
438
+ # Calculate the center and radius of the network
439
+ domain_centroids = self._calculate_domain_centroids()
440
+ center, radius = _calculate_bounding_box(
441
+ self.network_graph.node_coordinates, radius_margin=perimeter_scale
442
+ )
443
+
444
+ # Filter out domains with insufficient words for labeling
445
+ filtered_domains = {
446
+ domain: centroid
447
+ for domain, centroid in domain_centroids.items()
448
+ if len(self.network_graph.trimmed_domain_to_term[domain].split(" ")[:num_words])
449
+ >= min_words
450
+ }
451
+ # Calculate the best positions for labels around the perimeter
452
+ best_label_positions = _best_label_positions(filtered_domains, center, radius, offset)
453
+ # Annotate the network with labels
454
+ for idx, (domain, pos) in enumerate(best_label_positions.items()):
455
+ centroid = filtered_domains[domain]
456
+ annotations = self.network_graph.trimmed_domain_to_term[domain].split(" ")[:num_words]
457
+ self.ax.annotate(
458
+ "\n".join(annotations),
459
+ xy=centroid,
460
+ xytext=pos,
461
+ textcoords="data",
462
+ ha="center",
463
+ va="center",
464
+ fontsize=fontsize,
465
+ fontname=font,
466
+ color=fontcolor[idx],
467
+ arrowprops=dict(arrowstyle="->", color=arrow_color[idx], linewidth=arrow_linewidth),
468
+ )
469
+
470
+ def _calculate_domain_centroids(self) -> Dict[Any, np.ndarray]:
471
+ """Calculate the most centrally located node within each domain based on the node positions.
472
+
473
+ Returns:
474
+ Dict[Any, np.ndarray]: A dictionary mapping each domain to its central node's coordinates.
475
+ """
476
+ domain_central_nodes = {}
477
+ for domain, nodes in self.network_graph.domain_to_nodes.items():
478
+ if not nodes: # Skip if the domain has no nodes
479
+ continue
480
+
481
+ # Extract positions of all nodes in the domain
482
+ node_positions = self.network_graph.node_coordinates[nodes, :]
483
+ # Calculate the pairwise distance matrix between all nodes in the domain
484
+ distances_matrix = np.linalg.norm(
485
+ node_positions[:, np.newaxis] - node_positions, axis=2
486
+ )
487
+ # Sum the distances for each node to all other nodes in the domain
488
+ sum_distances = np.sum(distances_matrix, axis=1)
489
+ # Identify the node with the smallest total distance to others (the centroid)
490
+ central_node_idx = np.argmin(sum_distances)
491
+ # Map the domain to the coordinates of its central node
492
+ domain_central_nodes[domain] = node_positions[central_node_idx]
493
+
494
+ return domain_central_nodes
495
+
496
+ def get_annotated_node_colors(
497
+ self, nonenriched_color: str = "white", random_seed: int = 888, **kwargs
498
+ ) -> np.ndarray:
499
+ """Adjust the colors of nodes in the network graph based on enrichment.
500
+
501
+ Args:
502
+ nonenriched_color (str, optional): Color for non-enriched nodes. Defaults to "white".
503
+ random_seed (int, optional): Seed for random number generation. Defaults to 888.
504
+ **kwargs: Additional keyword arguments for `get_domain_colors`.
505
+
506
+ Returns:
507
+ np.ndarray: Array of RGBA colors adjusted for enrichment status.
508
+ """
509
+ # Get the initial domain colors for each node
510
+ network_colors = self.network_graph.get_domain_colors(**kwargs, random_seed=random_seed)
511
+ if isinstance(nonenriched_color, str):
512
+ # Convert the non-enriched color from string to RGBA
513
+ nonenriched_color = mcolors.to_rgba(nonenriched_color)
514
+
515
+ # Adjust node colors: replace any fully transparent nodes (enriched) with the non-enriched color
516
+ adjusted_network_colors = np.where(
517
+ np.all(network_colors == 0, axis=1, keepdims=True),
518
+ np.array([nonenriched_color]),
519
+ network_colors,
520
+ )
521
+ return adjusted_network_colors
522
+
523
+ def get_annotated_node_sizes(
524
+ self, enriched_nodesize: int = 50, nonenriched_nodesize: int = 25
525
+ ) -> np.ndarray:
526
+ """Adjust the sizes of nodes in the network graph based on whether they are enriched or not.
527
+
528
+ Args:
529
+ enriched_nodesize (int): Size for enriched nodes. Defaults to 50.
530
+ nonenriched_nodesize (int): Size for non-enriched nodes. Defaults to 25.
531
+
532
+ Returns:
533
+ np.ndarray: Array of node sizes, with enriched nodes larger than non-enriched ones.
534
+ """
535
+ # Merge all enriched nodes from the domain_to_nodes dictionary
536
+ enriched_nodes = set()
537
+ for _, nodes in self.network_graph.domain_to_nodes.items():
538
+ enriched_nodes.update(nodes)
539
+
540
+ # Initialize all node sizes to the non-enriched size
541
+ node_sizes = np.full(len(self.network_graph.G.nodes), nonenriched_nodesize)
542
+ # Set the size for enriched nodes
543
+ for node in enriched_nodes:
544
+ if node in self.network_graph.G.nodes:
545
+ node_sizes[node] = enriched_nodesize
546
+
547
+ return node_sizes
548
+
549
+ def get_annotated_contour_colors(self, random_seed: int = 888, **kwargs) -> np.ndarray:
550
+ """Get colors for the contours based on node annotations.
551
+
552
+ Args:
553
+ random_seed (int, optional): Seed for random number generation. Defaults to 888.
554
+ **kwargs: Additional keyword arguments for `_get_annotated_domain_colors`.
555
+
556
+ Returns:
557
+ np.ndarray: Array of RGBA colors for contour annotations.
558
+ """
559
+ return self._get_annotated_domain_colors(**kwargs, random_seed=random_seed)
560
+
561
+ def get_annotated_label_colors(self, random_seed: int = 888, **kwargs) -> np.ndarray:
562
+ """Get colors for the labels based on node annotations.
563
+
564
+ Args:
565
+ random_seed (int, optional): Seed for random number generation. Defaults to 888.
566
+ **kwargs: Additional keyword arguments for `_get_annotated_domain_colors`.
567
+
568
+ Returns:
569
+ np.ndarray: Array of RGBA colors for label annotations.
570
+ """
571
+ return self._get_annotated_domain_colors(**kwargs, random_seed=random_seed)
572
+
573
+ def _get_annotated_domain_colors(
574
+ self, color: Union[str, list, None] = None, random_seed: int = 888, **kwargs
575
+ ) -> np.ndarray:
576
+ """Get colors for the domains based on node annotations.
577
+
578
+ Args:
579
+ color (str, list, or None, optional): If provided, use this color or list of colors for domains. Defaults to None.
580
+ random_seed (int, optional): Seed for random number generation. Defaults to 888.
581
+ **kwargs: Additional keyword arguments for `get_domain_colors`.
582
+
583
+ Returns:
584
+ np.ndarray: Array of RGBA colors for each domain.
585
+ """
586
+ if isinstance(color, str):
587
+ # If a single color string is provided, convert it to RGBA and apply to all domains
588
+ rgba_color = np.array(matplotlib.colors.to_rgba(color))
589
+ return np.array([rgba_color for _ in self.network_graph.domain_to_nodes])
590
+
591
+ # Generate colors for each domain using the provided arguments and random seed
592
+ node_colors = self.network_graph.get_domain_colors(**kwargs, random_seed=random_seed)
593
+ annotated_colors = []
594
+ for _, nodes in self.network_graph.domain_to_nodes.items():
595
+ if len(nodes) > 1:
596
+ # For domains with multiple nodes, choose the brightest color (sum of RGB values)
597
+ domain_colors = np.array([node_colors[node] for node in nodes])
598
+ brightest_color = domain_colors[np.argmax(domain_colors.sum(axis=1))]
599
+ annotated_colors.append(brightest_color)
600
+ else:
601
+ # Assign a default color (white) for single-node domains
602
+ default_color = np.array([1.0, 1.0, 1.0, 1.0])
603
+ annotated_colors.append(default_color)
604
+
605
+ return np.array(annotated_colors)
606
+
607
+ @staticmethod
608
+ def close(*args, **kwargs) -> None:
609
+ """Close the current plot.
610
+
611
+ Args:
612
+ *args: Positional arguments passed to `plt.close`.
613
+ **kwargs: Keyword arguments passed to `plt.close`.
614
+ """
615
+ plt.close(*args, **kwargs)
616
+
617
+ @staticmethod
618
+ def savefig(*args, **kwargs) -> None:
619
+ """Save the current plot to a file.
620
+
621
+ Args:
622
+ *args: Positional arguments passed to `plt.savefig`.
623
+ **kwargs: Keyword arguments passed to `plt.savefig`, such as filename and format.
624
+ """
625
+ plt.savefig(*args, bbox_inches="tight", **kwargs)
626
+
627
+ @staticmethod
628
+ def show(*args, **kwargs) -> None:
629
+ """Display the current plot.
630
+
631
+ Args:
632
+ *args: Positional arguments passed to `plt.show`.
633
+ **kwargs: Keyword arguments passed to `plt.show`.
634
+ """
635
+ plt.show(*args, **kwargs)
636
+
637
+
638
+ def _is_connected(z: np.ndarray) -> bool:
639
+ """Determine if a thresholded grid represents a single, connected component.
640
+
641
+ Args:
642
+ z (np.ndarray): A binary grid where the component connectivity is evaluated.
643
+
644
+ Returns:
645
+ bool: True if the grid represents a single connected component, False otherwise.
646
+ """
647
+ _, num_features = label(z)
648
+ return num_features == 1 # Return True if only one connected component is found
649
+
650
+
651
+ def _calculate_bounding_box(
652
+ node_coordinates: np.ndarray, radius_margin: float = 1.05
653
+ ) -> Tuple[np.ndarray, float]:
654
+ """Calculate the bounding box of the network based on node coordinates.
655
+
656
+ Args:
657
+ node_coordinates (np.ndarray): Array of node coordinates (x, y).
658
+ radius_margin (float, optional): Margin factor to apply to the bounding box radius. Defaults to 1.05.
659
+
660
+ Returns:
661
+ tuple: Center of the bounding box and the radius (adjusted by the radius margin).
662
+ """
663
+ # Find minimum and maximum x, y coordinates
664
+ x_min, y_min = np.min(node_coordinates, axis=0)
665
+ x_max, y_max = np.max(node_coordinates, axis=0)
666
+ # Calculate the center of the bounding box
667
+ center = np.array([(x_min + x_max) / 2, (y_min + y_max) / 2])
668
+ # Calculate the radius of the bounding box, adjusted by the margin
669
+ radius = max(x_max - x_min, y_max - y_min) / 2 * radius_margin
670
+ return center, radius
671
+
672
+
673
+ def _best_label_positions(
674
+ filtered_domains: Dict[str, Any], center: np.ndarray, radius: float, offset: float
675
+ ) -> Dict[str, Any]:
676
+ """Calculate and optimize label positions for clarity.
677
+
678
+ Args:
679
+ filtered_domains (dict): Centroids of the filtered domains.
680
+ center (np.ndarray): The center coordinates for label positioning.
681
+ radius (float): The radius for positioning labels around the center.
682
+ offset (float): The offset distance from the radius for positioning labels.
683
+
684
+ Returns:
685
+ dict: Optimized positions for labels.
686
+ """
687
+ num_domains = len(filtered_domains)
688
+ # Calculate equidistant positions around the center for initial label placement
689
+ equidistant_positions = _equidistant_angles_around_center(center, radius, offset, num_domains)
690
+ # Create a mapping of domains to their initial label positions
691
+ label_positions = {
692
+ domain: position for domain, position in zip(filtered_domains.keys(), equidistant_positions)
693
+ }
694
+ # Optimize the label positions to minimize distance to domain centroids
695
+ return _optimize_label_positions(label_positions, filtered_domains)
696
+
697
+
698
+ def _equidistant_angles_around_center(
699
+ center: np.ndarray, radius: float, label_offset: float, num_domains: int
700
+ ) -> List[np.ndarray]:
701
+ """Calculate positions around a center at equidistant angles.
702
+
703
+ Args:
704
+ center (np.ndarray): The central point around which positions are calculated.
705
+ radius (float): The radius at which positions are calculated.
706
+ label_offset (float): The offset added to the radius for label positioning.
707
+ num_domains (int): The number of positions (or domains) to calculate.
708
+
709
+ Returns:
710
+ list[np.ndarray]: List of positions (as 2D numpy arrays) around the center.
711
+ """
712
+ # Calculate equidistant angles in radians around the center
713
+ angles = np.linspace(0, 2 * np.pi, num_domains, endpoint=False)
714
+ # Compute the positions around the center using the angles
715
+ return [
716
+ center + (radius + label_offset) * np.array([np.cos(angle), np.sin(angle)])
717
+ for angle in angles
718
+ ]
719
+
720
+
721
+ def _optimize_label_positions(
722
+ best_label_positions: Dict[str, Any], domain_centroids: Dict[str, Any]
723
+ ) -> Dict[str, Any]:
724
+ """Optimize label positions around the perimeter to minimize total distance to centroids.
725
+
726
+ Args:
727
+ best_label_positions (dict): Initial positions of labels around the perimeter.
728
+ domain_centroids (dict): Centroid positions of the domains.
729
+
730
+ Returns:
731
+ dict: Optimized label positions.
732
+ """
733
+ while True:
734
+ improvement = False # Start each iteration assuming no improvement
735
+ # Iterate through each pair of labels to check for potential improvements
736
+ for i in range(len(domain_centroids)):
737
+ for j in range(i + 1, len(domain_centroids)):
738
+ # Calculate the current total distance
739
+ current_distance = _calculate_total_distance(best_label_positions, domain_centroids)
740
+ # Evaluate the total distance after swapping two labels
741
+ swapped_distance = _swap_and_evaluate(best_label_positions, i, j, domain_centroids)
742
+ # If the swap improves the total distance, perform the swap
743
+ if swapped_distance < current_distance:
744
+ labels = list(best_label_positions.keys())
745
+ best_label_positions[labels[i]], best_label_positions[labels[j]] = (
746
+ best_label_positions[labels[j]],
747
+ best_label_positions[labels[i]],
748
+ )
749
+ improvement = True # Found an improvement, so continue optimizing
750
+
751
+ if not improvement:
752
+ break # Exit the loop if no improvement was found in this iteration
753
+
754
+ return best_label_positions
755
+
756
+
757
+ def _calculate_total_distance(
758
+ label_positions: Dict[str, Any], domain_centroids: Dict[str, Any]
759
+ ) -> float:
760
+ """Calculate the total distance from label positions to their domain centroids.
761
+
762
+ Args:
763
+ label_positions (dict): Positions of labels around the perimeter.
764
+ domain_centroids (dict): Centroid positions of the domains.
765
+
766
+ Returns:
767
+ float: The total distance from labels to centroids.
768
+ """
769
+ total_distance = 0
770
+ # Iterate through each domain and calculate the distance to its centroid
771
+ for domain, pos in label_positions.items():
772
+ centroid = domain_centroids[domain]
773
+ total_distance += np.linalg.norm(centroid - pos)
774
+
775
+ return total_distance
776
+
777
+
778
+ def _swap_and_evaluate(
779
+ label_positions: Dict[str, Any],
780
+ i: int,
781
+ j: int,
782
+ domain_centroids: Dict[str, Any],
783
+ ) -> float:
784
+ """Swap two labels and evaluate the total distance after the swap.
785
+
786
+ Args:
787
+ label_positions (dict): Positions of labels around the perimeter.
788
+ i (int): Index of the first label to swap.
789
+ j (int): Index of the second label to swap.
790
+ domain_centroids (dict): Centroid positions of the domains.
791
+
792
+ Returns:
793
+ float: The total distance after swapping the two labels.
794
+ """
795
+ # Get the list of labels from the dictionary keys
796
+ labels = list(label_positions.keys())
797
+ swapped_positions = label_positions.copy()
798
+ # Swap the positions of the two specified labels
799
+ swapped_positions[labels[i]], swapped_positions[labels[j]] = (
800
+ swapped_positions[labels[j]],
801
+ swapped_positions[labels[i]],
802
+ )
803
+ # Calculate and return the total distance after the swap
804
+ return _calculate_total_distance(swapped_positions, domain_centroids)