risk-network 0.0.7b12__py3-none-any.whl → 0.0.8__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/network/plot.py DELETED
@@ -1,1450 +0,0 @@
1
- """
2
- risk/network/plot
3
- ~~~~~~~~~~~~~~~~~
4
- """
5
-
6
- from typing import Any, Dict, List, Tuple, Union
7
-
8
- import matplotlib.colors as mcolors
9
- import matplotlib.pyplot as plt
10
- import networkx as nx
11
- import numpy as np
12
- import pandas as pd
13
- from scipy import linalg
14
- from scipy.ndimage import label
15
- from scipy.stats import gaussian_kde
16
-
17
- from risk.log import params, logger
18
- from risk.network.graph import NetworkGraph
19
-
20
-
21
- class NetworkPlotter:
22
- """A class for visualizing network graphs with customizable options.
23
-
24
- The NetworkPlotter class uses a NetworkGraph 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: NetworkGraph,
32
- figsize: Tuple = (10, 10),
33
- background_color: Union[str, List, Tuple, np.ndarray] = "white",
34
- ) -> None:
35
- """Initialize the NetworkPlotter with a NetworkGraph object and plotting parameters.
36
-
37
- Args:
38
- graph (NetworkGraph): The network data and attributes to be visualized.
39
- figsize (tuple, optional): Size of the figure in inches (width, height). Defaults to (10, 10).
40
- background_color (str, list, tuple, np.ndarray, optional): Background color of the plot. Defaults to "white".
41
- """
42
- self.graph = graph
43
- # Initialize the plot with the specified parameters
44
- self.ax = self._initialize_plot(graph, figsize, background_color)
45
-
46
- def _initialize_plot(
47
- self,
48
- graph: NetworkGraph,
49
- figsize: Tuple,
50
- background_color: Union[str, List, Tuple, np.ndarray],
51
- ) -> plt.Axes:
52
- """Set up the plot with figure size and background color.
53
-
54
- Args:
55
- graph (NetworkGraph): The network data and attributes to be visualized.
56
- figsize (tuple): Size of the figure in inches (width, height).
57
- background_color (str): Background color of the plot.
58
-
59
- Returns:
60
- plt.Axes: The axis object for the plot.
61
- """
62
- # Extract node coordinates from the network graph
63
- node_coordinates = graph.node_coordinates
64
- # Calculate the center and radius of the bounding box around the network
65
- center, radius = _calculate_bounding_box(node_coordinates)
66
-
67
- # Create a new figure and axis for plotting
68
- fig, ax = plt.subplots(figsize=figsize)
69
- fig.tight_layout() # Adjust subplot parameters to give specified padding
70
- # Set axis limits based on the calculated bounding box and radius
71
- ax.set_xlim([center[0] - radius - 0.3, center[0] + radius + 0.3])
72
- ax.set_ylim([center[1] - radius - 0.3, center[1] + radius + 0.3])
73
- ax.set_aspect("equal") # Ensure the aspect ratio is equal
74
-
75
- # Set the background color of the plot
76
- # Convert color to RGBA using the _to_rgba helper function
77
- fig.patch.set_facecolor(_to_rgba(background_color, 1.0))
78
- ax.invert_yaxis() # Invert the y-axis to match typical image coordinates
79
- # Remove axis spines for a cleaner look
80
- for spine in ax.spines.values():
81
- spine.set_visible(False)
82
-
83
- # Hide axis ticks and labels
84
- ax.set_xticks([])
85
- ax.set_yticks([])
86
- ax.patch.set_visible(False) # Hide the axis background
87
-
88
- return ax
89
-
90
- def plot_title(
91
- self,
92
- title: Union[str, None] = None,
93
- subtitle: Union[str, None] = None,
94
- title_fontsize: int = 20,
95
- subtitle_fontsize: int = 14,
96
- font: str = "Arial",
97
- title_color: str = "black",
98
- subtitle_color: str = "gray",
99
- title_y: float = 0.975,
100
- title_space_offset: float = 0.075,
101
- subtitle_offset: float = 0.025,
102
- ) -> None:
103
- """Plot title and subtitle on the network graph with customizable parameters.
104
-
105
- Args:
106
- title (str, optional): Title of the plot. Defaults to None.
107
- subtitle (str, optional): Subtitle of the plot. Defaults to None.
108
- title_fontsize (int, optional): Font size for the title. Defaults to 16.
109
- subtitle_fontsize (int, optional): Font size for the subtitle. Defaults to 12.
110
- font (str, optional): Font family used for both title and subtitle. Defaults to "Arial".
111
- title_color (str, optional): Color of the title text. Defaults to "black".
112
- subtitle_color (str, optional): Color of the subtitle text. Defaults to "gray".
113
- title_y (float, optional): Y-axis position of the title. Defaults to 0.975.
114
- title_space_offset (float, optional): Fraction of figure height to leave for the space above the plot. Defaults to 0.075.
115
- subtitle_offset (float, optional): Offset factor to position the subtitle below the title. Defaults to 0.025.
116
- """
117
- # Log the title and subtitle parameters
118
- params.log_plotter(
119
- title=title,
120
- subtitle=subtitle,
121
- title_fontsize=title_fontsize,
122
- subtitle_fontsize=subtitle_fontsize,
123
- title_subtitle_font=font,
124
- title_color=title_color,
125
- subtitle_color=subtitle_color,
126
- subtitle_offset=subtitle_offset,
127
- title_y=title_y,
128
- title_space_offset=title_space_offset,
129
- )
130
-
131
- # Get the current figure and axis dimensions
132
- fig = self.ax.figure
133
- # Use a tight layout to ensure that title and subtitle do not overlap with the original plot
134
- fig.tight_layout(
135
- rect=[0, 0, 1, 1 - title_space_offset]
136
- ) # Leave space above the plot for title
137
-
138
- # Plot title if provided
139
- if title:
140
- # Set the title using figure's suptitle to ensure centering
141
- self.ax.figure.suptitle(
142
- title,
143
- fontsize=title_fontsize,
144
- color=title_color,
145
- fontname=font,
146
- x=0.5, # Center the title horizontally
147
- ha="center",
148
- va="top",
149
- y=title_y,
150
- )
151
-
152
- # Plot subtitle if provided
153
- if subtitle:
154
- # Calculate the subtitle's y position based on title's position and subtitle_offset
155
- subtitle_y_position = title_y - subtitle_offset
156
- self.ax.figure.text(
157
- 0.5, # Ensure horizontal centering for subtitle
158
- subtitle_y_position,
159
- subtitle,
160
- ha="center",
161
- va="top",
162
- fontname=font,
163
- fontsize=subtitle_fontsize,
164
- color=subtitle_color,
165
- )
166
-
167
- def plot_circle_perimeter(
168
- self,
169
- scale: float = 1.0,
170
- linestyle: str = "dashed",
171
- linewidth: float = 1.5,
172
- color: Union[str, List, Tuple, np.ndarray] = "black",
173
- outline_alpha: float = 1.0,
174
- fill_alpha: float = 0.0,
175
- ) -> None:
176
- """Plot a circle around the network graph to represent the network perimeter.
177
-
178
- Args:
179
- scale (float, optional): Scaling factor for the perimeter diameter. Defaults to 1.0.
180
- linestyle (str, optional): Line style for the network perimeter circle (e.g., dashed, solid). Defaults to "dashed".
181
- linewidth (float, optional): Width of the circle's outline. Defaults to 1.5.
182
- color (str, list, tuple, or np.ndarray, optional): Color of the network perimeter circle. Defaults to "black".
183
- outline_alpha (float, optional): Transparency level of the circle outline. Defaults to 1.0.
184
- fill_alpha (float, optional): Transparency level of the circle fill. Defaults to 0.0.
185
- """
186
- # Log the circle perimeter plotting parameters
187
- params.log_plotter(
188
- perimeter_type="circle",
189
- perimeter_scale=scale,
190
- perimeter_linestyle=linestyle,
191
- perimeter_linewidth=linewidth,
192
- perimeter_color=(
193
- "custom" if isinstance(color, (list, tuple, np.ndarray)) else color
194
- ), # np.ndarray usually indicates custom colors
195
- perimeter_outline_alpha=outline_alpha,
196
- perimeter_fill_alpha=fill_alpha,
197
- )
198
-
199
- # Convert color to RGBA using the _to_rgba helper function - use outline_alpha for the perimeter
200
- color = _to_rgba(color, outline_alpha)
201
- # Extract node coordinates from the network graph
202
- node_coordinates = self.graph.node_coordinates
203
- # Calculate the center and radius of the bounding box around the network
204
- center, radius = _calculate_bounding_box(node_coordinates)
205
- # Scale the radius by the scale factor
206
- scaled_radius = radius * scale
207
-
208
- # Draw a circle to represent the network perimeter
209
- circle = plt.Circle(
210
- center,
211
- scaled_radius,
212
- linestyle=linestyle,
213
- linewidth=linewidth,
214
- color=color,
215
- fill=fill_alpha > 0, # Fill the circle if fill_alpha is greater than 0
216
- )
217
- # Set the transparency of the fill if applicable
218
- if fill_alpha > 0:
219
- circle.set_facecolor(_to_rgba(color, fill_alpha))
220
-
221
- self.ax.add_artist(circle)
222
-
223
- def plot_contour_perimeter(
224
- self,
225
- scale: float = 1.0,
226
- levels: int = 3,
227
- bandwidth: float = 0.8,
228
- grid_size: int = 250,
229
- color: Union[str, List, Tuple, np.ndarray] = "black",
230
- linestyle: str = "solid",
231
- linewidth: float = 1.5,
232
- outline_alpha: float = 1.0,
233
- fill_alpha: float = 0.0,
234
- ) -> None:
235
- """
236
- Plot a KDE-based contour around the network graph to represent the network perimeter.
237
-
238
- Args:
239
- scale (float, optional): Scaling factor for the perimeter size. Defaults to 1.0.
240
- levels (int, optional): Number of contour levels. Defaults to 3.
241
- bandwidth (float, optional): Bandwidth for the KDE. Controls smoothness. Defaults to 0.8.
242
- grid_size (int, optional): Grid resolution for the KDE. Higher values yield finer contours. Defaults to 250.
243
- color (str, list, tuple, or np.ndarray, optional): Color of the network perimeter contour. Defaults to "black".
244
- linestyle (str, optional): Line style for the network perimeter contour (e.g., dashed, solid). Defaults to "solid".
245
- linewidth (float, optional): Width of the contour's outline. Defaults to 1.5.
246
- outline_alpha (float, optional): Transparency level of the contour outline. Defaults to 1.0.
247
- fill_alpha (float, optional): Transparency level of the contour fill. Defaults to 0.0.
248
- """
249
- # Log the contour perimeter plotting parameters
250
- params.log_plotter(
251
- perimeter_type="contour",
252
- perimeter_scale=scale,
253
- perimeter_levels=levels,
254
- perimeter_bandwidth=bandwidth,
255
- perimeter_grid_size=grid_size,
256
- perimeter_linestyle=linestyle,
257
- perimeter_linewidth=linewidth,
258
- perimeter_color=("custom" if isinstance(color, (list, tuple, np.ndarray)) else color),
259
- perimeter_outline_alpha=outline_alpha,
260
- perimeter_fill_alpha=fill_alpha,
261
- )
262
-
263
- # Convert color to RGBA using the _to_rgba helper function - use outline_alpha for the perimeter
264
- color = _to_rgba(color, outline_alpha)
265
- # Extract node coordinates from the network graph
266
- node_coordinates = self.graph.node_coordinates
267
- # Scale the node coordinates if needed
268
- scaled_coordinates = node_coordinates * scale
269
- # Use the existing _draw_kde_contour method
270
- self._draw_kde_contour(
271
- ax=self.ax,
272
- pos=scaled_coordinates,
273
- nodes=list(range(len(node_coordinates))), # All nodes are included
274
- levels=levels,
275
- bandwidth=bandwidth,
276
- grid_size=grid_size,
277
- color=color,
278
- linestyle=linestyle,
279
- linewidth=linewidth,
280
- alpha=fill_alpha,
281
- )
282
-
283
- def plot_network(
284
- self,
285
- node_size: Union[int, np.ndarray] = 50,
286
- node_shape: str = "o",
287
- node_edgewidth: float = 1.0,
288
- edge_width: float = 1.0,
289
- node_color: Union[str, List, Tuple, np.ndarray] = "white",
290
- node_edgecolor: Union[str, List, Tuple, np.ndarray] = "black",
291
- edge_color: Union[str, List, Tuple, np.ndarray] = "black",
292
- node_alpha: float = 1.0,
293
- edge_alpha: float = 1.0,
294
- ) -> None:
295
- """Plot the network graph with customizable node colors, sizes, edge widths, and node edge widths.
296
-
297
- Args:
298
- node_size (int or np.ndarray, optional): Size of the nodes. Can be a single integer or an array of sizes. Defaults to 50.
299
- node_shape (str, optional): Shape of the nodes. Defaults to "o".
300
- node_edgewidth (float, optional): Width of the node edges. Defaults to 1.0.
301
- edge_width (float, optional): Width of the edges. Defaults to 1.0.
302
- node_color (str, list, tuple, or np.ndarray, optional): Color of the nodes. Can be a single color or an array of colors. Defaults to "white".
303
- node_edgecolor (str, list, tuple, or np.ndarray, optional): Color of the node edges. Defaults to "black".
304
- edge_color (str, list, tuple, or np.ndarray, optional): Color of the edges. Defaults to "black".
305
- node_alpha (float, optional): Alpha value (transparency) for the nodes. Defaults to 1.0. Annotated node_color alphas will override this value.
306
- edge_alpha (float, optional): Alpha value (transparency) for the edges. Defaults to 1.0.
307
- """
308
- # Log the plotting parameters
309
- params.log_plotter(
310
- network_node_size=(
311
- "custom" if isinstance(node_size, np.ndarray) else node_size
312
- ), # np.ndarray usually indicates custom sizes
313
- network_node_shape=node_shape,
314
- network_node_edgewidth=node_edgewidth,
315
- network_edge_width=edge_width,
316
- network_node_color=(
317
- "custom" if isinstance(node_color, np.ndarray) else node_color
318
- ), # np.ndarray usually indicates custom colors
319
- network_node_edgecolor=node_edgecolor,
320
- network_edge_color=edge_color,
321
- network_node_alpha=node_alpha,
322
- network_edge_alpha=edge_alpha,
323
- )
324
-
325
- # Convert colors to RGBA using the _to_rgba helper function
326
- # If node_colors was generated using get_annotated_node_colors, its alpha values will override node_alpha
327
- node_color = _to_rgba(node_color, node_alpha, num_repeats=len(self.graph.network.nodes))
328
- node_edgecolor = _to_rgba(node_edgecolor, 1.0, num_repeats=len(self.graph.network.nodes))
329
- edge_color = _to_rgba(edge_color, edge_alpha, num_repeats=len(self.graph.network.edges))
330
-
331
- # Extract node coordinates from the network graph
332
- node_coordinates = self.graph.node_coordinates
333
-
334
- # Draw the nodes of the graph
335
- nx.draw_networkx_nodes(
336
- self.graph.network,
337
- pos=node_coordinates,
338
- node_size=node_size,
339
- node_shape=node_shape,
340
- node_color=node_color,
341
- edgecolors=node_edgecolor,
342
- linewidths=node_edgewidth,
343
- ax=self.ax,
344
- )
345
- # Draw the edges of the graph
346
- nx.draw_networkx_edges(
347
- self.graph.network,
348
- pos=node_coordinates,
349
- width=edge_width,
350
- edge_color=edge_color,
351
- ax=self.ax,
352
- )
353
-
354
- def plot_subnetwork(
355
- self,
356
- nodes: Union[List, Tuple, np.ndarray],
357
- node_size: Union[int, np.ndarray] = 50,
358
- node_shape: str = "o",
359
- node_edgewidth: float = 1.0,
360
- edge_width: float = 1.0,
361
- node_color: Union[str, List, Tuple, np.ndarray] = "white",
362
- node_edgecolor: Union[str, List, Tuple, np.ndarray] = "black",
363
- edge_color: Union[str, List, Tuple, np.ndarray] = "black",
364
- node_alpha: float = 1.0,
365
- edge_alpha: float = 1.0,
366
- ) -> None:
367
- """Plot a subnetwork of selected nodes with customizable node and edge attributes.
368
-
369
- Args:
370
- nodes (list, tuple, or np.ndarray): List of node labels to include in the subnetwork. Accepts nested lists.
371
- node_size (int or np.ndarray, optional): Size of the nodes. Can be a single integer or an array of sizes. Defaults to 50.
372
- node_shape (str, optional): Shape of the nodes. Defaults to "o".
373
- node_edgewidth (float, optional): Width of the node edges. Defaults to 1.0.
374
- edge_width (float, optional): Width of the edges. Defaults to 1.0.
375
- node_color (str, list, tuple, or np.ndarray, optional): Color of the nodes. Defaults to "white".
376
- node_edgecolor (str, list, tuple, or np.ndarray, optional): Color of the node edges. Defaults to "black".
377
- edge_color (str, list, tuple, or np.ndarray, optional): Color of the edges. Defaults to "black".
378
- node_alpha (float, optional): Transparency for the nodes. Defaults to 1.0.
379
- edge_alpha (float, optional): Transparency for the edges. Defaults to 1.0.
380
-
381
- Raises:
382
- ValueError: If no valid nodes are found in the network graph.
383
- """
384
- # Flatten nested lists of nodes, if necessary
385
- if any(isinstance(item, (list, tuple, np.ndarray)) for item in nodes):
386
- nodes = [node for sublist in nodes for node in sublist]
387
-
388
- # Filter to get node IDs and their coordinates
389
- node_ids = [
390
- self.graph.node_label_to_node_id_map.get(node)
391
- for node in nodes
392
- if node in self.graph.node_label_to_node_id_map
393
- ]
394
- if not node_ids:
395
- raise ValueError("No nodes found in the network graph.")
396
-
397
- # Check if node_color is a single color or a list of colors
398
- if not isinstance(node_color, (str, tuple, np.ndarray)):
399
- node_color = [
400
- node_color[nodes.index(node)]
401
- for node in nodes
402
- if node in self.graph.node_label_to_node_id_map
403
- ]
404
-
405
- # Convert colors to RGBA using the _to_rgba helper function
406
- node_color = _to_rgba(node_color, node_alpha, num_repeats=len(node_ids))
407
- node_edgecolor = _to_rgba(node_edgecolor, 1.0, num_repeats=len(node_ids))
408
- edge_color = _to_rgba(edge_color, edge_alpha, num_repeats=len(self.graph.network.edges))
409
-
410
- # Get the coordinates of the filtered nodes
411
- node_coordinates = {node_id: self.graph.node_coordinates[node_id] for node_id in node_ids}
412
-
413
- # Draw the nodes in the subnetwork
414
- nx.draw_networkx_nodes(
415
- self.graph.network,
416
- pos=node_coordinates,
417
- nodelist=node_ids,
418
- node_size=node_size,
419
- node_shape=node_shape,
420
- node_color=node_color,
421
- edgecolors=node_edgecolor,
422
- linewidths=node_edgewidth,
423
- ax=self.ax,
424
- )
425
- # Draw the edges between the specified nodes in the subnetwork
426
- subgraph = self.graph.network.subgraph(node_ids)
427
- nx.draw_networkx_edges(
428
- subgraph,
429
- pos=node_coordinates,
430
- width=edge_width,
431
- edge_color=edge_color,
432
- ax=self.ax,
433
- )
434
-
435
- def plot_contours(
436
- self,
437
- levels: int = 5,
438
- bandwidth: float = 0.8,
439
- grid_size: int = 250,
440
- color: Union[str, List, Tuple, np.ndarray] = "white",
441
- linestyle: str = "solid",
442
- linewidth: float = 1.5,
443
- alpha: float = 1.0,
444
- fill_alpha: float = 0.2,
445
- ) -> None:
446
- """Draw KDE contours for nodes in various domains of a network graph, highlighting areas of high density.
447
-
448
- Args:
449
- levels (int, optional): Number of contour levels to plot. Defaults to 5.
450
- bandwidth (float, optional): Bandwidth for KDE. Controls the smoothness of the contour. Defaults to 0.8.
451
- grid_size (int, optional): Resolution of the grid for KDE. Higher values create finer contours. Defaults to 250.
452
- color (str, list, tuple, or np.ndarray, optional): Color of the contours. Can be a single color or an array of colors. Defaults to "white".
453
- linestyle (str, optional): Line style for the contours. Defaults to "solid".
454
- linewidth (float, optional): Line width for the contours. Defaults to 1.5.
455
- alpha (float, optional): Transparency level of the contour lines. Defaults to 1.0.
456
- fill_alpha (float, optional): Transparency level of the contour fill. Defaults to 0.2.
457
- """
458
- # Log the contour plotting parameters
459
- params.log_plotter(
460
- contour_levels=levels,
461
- contour_bandwidth=bandwidth,
462
- contour_grid_size=grid_size,
463
- contour_color=(
464
- "custom" if isinstance(color, np.ndarray) else color
465
- ), # np.ndarray usually indicates custom colors
466
- contour_alpha=alpha,
467
- contour_fill_alpha=fill_alpha,
468
- )
469
-
470
- # Ensure color is converted to RGBA with repetition matching the number of domains
471
- color = _to_rgba(color, alpha, num_repeats=len(self.graph.domain_id_to_node_ids_map))
472
- # Extract node coordinates from the network graph
473
- node_coordinates = self.graph.node_coordinates
474
- # Draw contours for each domain in the network
475
- for idx, (_, node_ids) in enumerate(self.graph.domain_id_to_node_ids_map.items()):
476
- if len(node_ids) > 1:
477
- self._draw_kde_contour(
478
- self.ax,
479
- node_coordinates,
480
- node_ids,
481
- color=color[idx],
482
- levels=levels,
483
- bandwidth=bandwidth,
484
- grid_size=grid_size,
485
- linestyle=linestyle,
486
- linewidth=linewidth,
487
- alpha=alpha,
488
- fill_alpha=fill_alpha,
489
- )
490
-
491
- def plot_subcontour(
492
- self,
493
- nodes: Union[List, Tuple, np.ndarray],
494
- levels: int = 5,
495
- bandwidth: float = 0.8,
496
- grid_size: int = 250,
497
- color: Union[str, List, Tuple, np.ndarray] = "white",
498
- linestyle: str = "solid",
499
- linewidth: float = 1.5,
500
- alpha: float = 1.0,
501
- fill_alpha: float = 0.2,
502
- ) -> None:
503
- """Plot a subcontour for a given set of nodes or a list of node sets using Kernel Density Estimation (KDE).
504
-
505
- Args:
506
- nodes (list, tuple, or np.ndarray): List of node labels or list of lists of node labels to plot the contour for.
507
- levels (int, optional): Number of contour levels to plot. Defaults to 5.
508
- bandwidth (float, optional): Bandwidth for KDE. Controls the smoothness of the contour. Defaults to 0.8.
509
- grid_size (int, optional): Resolution of the grid for KDE. Higher values create finer contours. Defaults to 250.
510
- color (str, list, tuple, or np.ndarray, optional): Color of the contour. Can be a string (e.g., 'white') or RGBA array. Defaults to "white".
511
- linestyle (str, optional): Line style for the contour. Defaults to "solid".
512
- linewidth (float, optional): Line width for the contour. Defaults to 1.5.
513
- alpha (float, optional): Transparency level of the contour lines. Defaults to 1.0.
514
- fill_alpha (float, optional): Transparency level of the contour fill. Defaults to 0.2.
515
-
516
- Raises:
517
- ValueError: If no valid nodes are found in the network graph.
518
- """
519
- # Check if nodes is a list of lists or a flat list
520
- if any(isinstance(item, (list, tuple, np.ndarray)) for item in nodes):
521
- # If it's a list of lists, iterate over sublists
522
- node_groups = nodes
523
- else:
524
- # If it's a flat list of nodes, treat it as a single group
525
- node_groups = [nodes]
526
-
527
- # Convert color to RGBA using the _to_rgba helper function
528
- color_rgba = _to_rgba(color, alpha)
529
-
530
- # Iterate over each group of nodes (either sublists or flat list)
531
- for sublist in node_groups:
532
- # Filter to get node IDs and their coordinates for each sublist
533
- node_ids = [
534
- self.graph.node_label_to_node_id_map.get(node)
535
- for node in sublist
536
- if node in self.graph.node_label_to_node_id_map
537
- ]
538
- if not node_ids or len(node_ids) == 1:
539
- raise ValueError(
540
- "No nodes found in the network graph or insufficient nodes to plot."
541
- )
542
-
543
- # Draw the KDE contour for the specified nodes
544
- node_coordinates = self.graph.node_coordinates
545
- self._draw_kde_contour(
546
- self.ax,
547
- node_coordinates,
548
- node_ids,
549
- color=color_rgba,
550
- levels=levels,
551
- bandwidth=bandwidth,
552
- grid_size=grid_size,
553
- linestyle=linestyle,
554
- linewidth=linewidth,
555
- alpha=alpha,
556
- fill_alpha=fill_alpha,
557
- )
558
-
559
- def _draw_kde_contour(
560
- self,
561
- ax: plt.Axes,
562
- pos: np.ndarray,
563
- nodes: List,
564
- levels: int = 5,
565
- bandwidth: float = 0.8,
566
- grid_size: int = 250,
567
- color: Union[str, np.ndarray] = "white",
568
- linestyle: str = "solid",
569
- linewidth: float = 1.5,
570
- alpha: float = 1.0,
571
- fill_alpha: float = 0.2,
572
- ) -> None:
573
- """Draw a Kernel Density Estimate (KDE) contour plot for a set of nodes on a given axis.
574
-
575
- Args:
576
- ax (plt.Axes): The axis to draw the contour on.
577
- pos (np.ndarray): Array of node positions (x, y).
578
- nodes (list): List of node indices to include in the contour.
579
- levels (int, optional): Number of contour levels. Defaults to 5.
580
- bandwidth (float, optional): Bandwidth for the KDE. Controls smoothness. Defaults to 0.8.
581
- grid_size (int, optional): Grid resolution for the KDE. Higher values yield finer contours. Defaults to 250.
582
- color (str or np.ndarray): Color for the contour. Can be a string or RGBA array. Defaults to "white".
583
- linestyle (str, optional): Line style for the contour. Defaults to "solid".
584
- linewidth (float, optional): Line width for the contour. Defaults to 1.5.
585
- alpha (float, optional): Transparency level for the contour lines. Defaults to 1.0.
586
- fill_alpha (float, optional): Transparency level for the contour fill. Defaults to 0.2.
587
- """
588
- # Extract the positions of the specified nodes
589
- points = np.array([pos[n] for n in nodes])
590
- if len(points) <= 1:
591
- return None # Not enough points to form a contour
592
-
593
- # Check if the KDE forms a single connected component
594
- connected = False
595
- z = None # Initialize z to None to avoid UnboundLocalError
596
- while not connected and bandwidth <= 100.0:
597
- try:
598
- # Perform KDE on the points with the given bandwidth
599
- kde = gaussian_kde(points.T, bw_method=bandwidth)
600
- xmin, ymin = points.min(axis=0) - bandwidth
601
- xmax, ymax = points.max(axis=0) + bandwidth
602
- x, y = np.mgrid[
603
- xmin : xmax : complex(0, grid_size), ymin : ymax : complex(0, grid_size)
604
- ]
605
- z = kde(np.vstack([x.ravel(), y.ravel()])).reshape(x.shape)
606
- # Check if the KDE forms a single connected component
607
- connected = _is_connected(z)
608
- if not connected:
609
- bandwidth += 0.05 # Increase bandwidth slightly and retry
610
- except linalg.LinAlgError:
611
- bandwidth += 0.05 # Increase bandwidth and retry
612
- except Exception as e:
613
- # Catch any other exceptions and log them
614
- logger.error(f"Unexpected error when drawing KDE contour: {e}")
615
- return None
616
-
617
- # If z is still None, the KDE computation failed
618
- if z is None:
619
- logger.error("Failed to compute KDE. Skipping contour plot for these nodes.")
620
- return None
621
-
622
- # Define contour levels based on the density
623
- min_density, max_density = z.min(), z.max()
624
- if min_density == max_density:
625
- logger.warning(
626
- "Contour levels could not be created due to lack of variation in density."
627
- )
628
- return None
629
-
630
- # Create contour levels based on the density values
631
- contour_levels = np.linspace(min_density, max_density, levels)[1:]
632
- if len(contour_levels) < 2 or not np.all(np.diff(contour_levels) > 0):
633
- logger.error("Contour levels must be strictly increasing. Skipping contour plot.")
634
- return None
635
-
636
- # Set the contour color and linestyle
637
- contour_colors = [color for _ in range(levels - 1)]
638
- # Plot the filled contours using fill_alpha for transparency
639
- if fill_alpha > 0:
640
- ax.contourf(
641
- x,
642
- y,
643
- z,
644
- levels=contour_levels,
645
- colors=contour_colors,
646
- antialiased=True,
647
- alpha=fill_alpha,
648
- )
649
-
650
- # Plot the contour lines with the specified alpha for transparency
651
- c = ax.contour(
652
- x,
653
- y,
654
- z,
655
- levels=contour_levels,
656
- colors=contour_colors,
657
- linestyles=linestyle,
658
- linewidths=linewidth,
659
- alpha=alpha,
660
- )
661
-
662
- # Set linewidth for the contour lines to 0 for levels other than the base level
663
- for i in range(1, len(contour_levels)):
664
- c.collections[i].set_linewidth(0)
665
-
666
- def plot_labels(
667
- self,
668
- scale: float = 1.05,
669
- offset: float = 0.10,
670
- font: str = "Arial",
671
- fontsize: int = 10,
672
- fontcolor: Union[str, List, Tuple, np.ndarray] = "black",
673
- fontalpha: float = 1.0,
674
- arrow_linewidth: float = 1,
675
- arrow_style: str = "->",
676
- arrow_color: Union[str, List, Tuple, np.ndarray] = "black",
677
- arrow_alpha: float = 1.0,
678
- arrow_base_shrink: float = 0.0,
679
- arrow_tip_shrink: float = 0.0,
680
- max_labels: Union[int, None] = None,
681
- max_words: int = 10,
682
- min_words: int = 1,
683
- max_word_length: int = 20,
684
- min_word_length: int = 1,
685
- words_to_omit: Union[List, None] = None,
686
- overlay_ids: bool = False,
687
- ids_to_keep: Union[List, Tuple, np.ndarray, None] = None,
688
- ids_to_replace: Union[Dict, None] = None,
689
- ) -> None:
690
- """Annotate the network graph with labels for different domains, positioned around the network for clarity.
691
-
692
- Args:
693
- scale (float, optional): Scale factor for positioning labels around the perimeter. Defaults to 1.05.
694
- offset (float, optional): Offset distance for labels from the perimeter. Defaults to 0.10.
695
- font (str, optional): Font name for the labels. Defaults to "Arial".
696
- fontsize (int, optional): Font size for the labels. Defaults to 10.
697
- fontcolor (str, list, tuple, or np.ndarray, optional): Color of the label text. Can be a string or RGBA array. Defaults to "black".
698
- fontalpha (float, optional): Transparency level for the font color. Defaults to 1.0.
699
- arrow_linewidth (float, optional): Line width of the arrows pointing to centroids. Defaults to 1.
700
- arrow_style (str, optional): Style of the arrows pointing to centroids. Defaults to "->".
701
- arrow_color (str, list, tuple, or np.ndarray, optional): Color of the arrows. Defaults to "black".
702
- arrow_alpha (float, optional): Transparency level for the arrow color. Defaults to 1.0.
703
- arrow_base_shrink (float, optional): Distance between the text and the base of the arrow. Defaults to 0.0.
704
- arrow_tip_shrink (float, optional): Distance between the arrow tip and the centroid. Defaults to 0.0.
705
- max_labels (int, optional): Maximum number of labels to plot. Defaults to None (no limit).
706
- max_words (int, optional): Maximum number of words in a label. Defaults to 10.
707
- min_words (int, optional): Minimum number of words required to display a label. Defaults to 1.
708
- max_word_length (int, optional): Maximum number of characters in a word to display. Defaults to 20.
709
- min_word_length (int, optional): Minimum number of characters in a word to display. Defaults to 1.
710
- words_to_omit (list, optional): List of words to omit from the labels. Defaults to None.
711
- overlay_ids (bool, optional): Whether to overlay domain IDs in the center of the centroids. Defaults to False.
712
- ids_to_keep (list, tuple, np.ndarray, or None, optional): IDs of domains that must be labeled. To discover domain IDs,
713
- you can set `overlay_ids=True`. Defaults to None.
714
- ids_to_replace (dict, optional): A dictionary mapping domain IDs to custom labels (strings). The labels should be space-separated words.
715
- If provided, the custom labels will replace the default domain terms. To discover domain IDs, you can set `overlay_ids=True`.
716
- Defaults to None.
717
-
718
- Raises:
719
- ValueError: If the number of provided `ids_to_keep` exceeds `max_labels`.
720
- """
721
- # Log the plotting parameters
722
- params.log_plotter(
723
- label_perimeter_scale=scale,
724
- label_offset=offset,
725
- label_font=font,
726
- label_fontsize=fontsize,
727
- label_fontcolor=(
728
- "custom" if isinstance(fontcolor, np.ndarray) else fontcolor
729
- ), # np.ndarray usually indicates custom colors
730
- label_fontalpha=fontalpha,
731
- label_arrow_linewidth=arrow_linewidth,
732
- label_arrow_style=arrow_style,
733
- label_arrow_color="custom" if isinstance(arrow_color, np.ndarray) else arrow_color,
734
- label_arrow_alpha=arrow_alpha,
735
- label_arrow_base_shrink=arrow_base_shrink,
736
- label_arrow_tip_shrink=arrow_tip_shrink,
737
- label_max_labels=max_labels,
738
- label_max_words=max_words,
739
- label_min_words=min_words,
740
- label_max_word_length=max_word_length,
741
- label_min_word_length=min_word_length,
742
- label_words_to_omit=words_to_omit,
743
- label_overlay_ids=overlay_ids,
744
- label_ids_to_keep=ids_to_keep,
745
- label_ids_to_replace=ids_to_replace,
746
- )
747
-
748
- # Set max_labels to the total number of domains if not provided (None)
749
- if max_labels is None:
750
- max_labels = len(self.graph.domain_id_to_node_ids_map)
751
-
752
- # Convert colors to RGBA using the _to_rgba helper function
753
- fontcolor = _to_rgba(
754
- fontcolor, fontalpha, num_repeats=len(self.graph.domain_id_to_node_ids_map)
755
- )
756
- arrow_color = _to_rgba(
757
- arrow_color, arrow_alpha, num_repeats=len(self.graph.domain_id_to_node_ids_map)
758
- )
759
-
760
- # Normalize words_to_omit to lowercase
761
- if words_to_omit:
762
- words_to_omit = set(word.lower() for word in words_to_omit)
763
-
764
- # Calculate the center and radius of the network
765
- domain_centroids = {}
766
- for domain_id, node_ids in self.graph.domain_id_to_node_ids_map.items():
767
- if node_ids: # Skip if the domain has no nodes
768
- domain_centroids[domain_id] = self._calculate_domain_centroid(node_ids)
769
-
770
- # Initialize dictionaries and lists for valid indices
771
- valid_indices = []
772
- filtered_domain_centroids = {}
773
- filtered_domain_terms = {}
774
- # Handle the ids_to_keep logic
775
- if ids_to_keep:
776
- # Convert ids_to_keep to remove accidental duplicates
777
- ids_to_keep = set(ids_to_keep)
778
- # Check if the number of provided ids_to_keep exceeds max_labels
779
- if max_labels is not None and len(ids_to_keep) > max_labels:
780
- raise ValueError(
781
- f"Number of provided IDs ({len(ids_to_keep)}) exceeds max_labels ({max_labels})."
782
- )
783
-
784
- # Process the specified IDs first
785
- for domain in ids_to_keep:
786
- if (
787
- domain in self.graph.domain_id_to_domain_terms_map
788
- and domain in domain_centroids
789
- ):
790
- # Handle ids_to_replace logic here for ids_to_keep
791
- if ids_to_replace and domain in ids_to_replace:
792
- terms = ids_to_replace[domain].split(" ")
793
- else:
794
- terms = self.graph.domain_id_to_domain_terms_map[domain].split(" ")
795
-
796
- # Apply words_to_omit, word length constraints, and max_words
797
- if words_to_omit:
798
- terms = [term for term in terms if term.lower() not in words_to_omit]
799
- terms = [
800
- term for term in terms if min_word_length <= len(term) <= max_word_length
801
- ]
802
- terms = terms[:max_words]
803
-
804
- # Check if the domain passes the word count condition
805
- if len(terms) >= min_words:
806
- filtered_domain_centroids[domain] = domain_centroids[domain]
807
- filtered_domain_terms[domain] = " ".join(terms)
808
- valid_indices.append(
809
- list(domain_centroids.keys()).index(domain)
810
- ) # Track the valid index
811
-
812
- # Calculate remaining labels to plot after processing ids_to_keep
813
- remaining_labels = (
814
- max_labels - len(ids_to_keep) if ids_to_keep and max_labels else max_labels
815
- )
816
- # Process remaining domains to fill in additional labels, if there are slots left
817
- if remaining_labels and remaining_labels > 0:
818
- for idx, (domain, centroid) in enumerate(domain_centroids.items()):
819
- # Check if the domain is NaN and continue if true
820
- if pd.isna(domain) or (isinstance(domain, float) and np.isnan(domain)):
821
- continue # Skip NaN domains
822
- if ids_to_keep and domain in ids_to_keep:
823
- continue # Skip domains already handled by ids_to_keep
824
-
825
- # Handle ids_to_replace logic first
826
- if ids_to_replace and domain in ids_to_replace:
827
- terms = ids_to_replace[domain].split(" ")
828
- else:
829
- terms = self.graph.domain_id_to_domain_terms_map[domain].split(" ")
830
-
831
- # Apply words_to_omit, word length constraints, and max_words
832
- if words_to_omit:
833
- terms = [term for term in terms if term.lower() not in words_to_omit]
834
-
835
- terms = [term for term in terms if min_word_length <= len(term) <= max_word_length]
836
- terms = terms[:max_words]
837
- # Check if the domain passes the word count condition
838
- if len(terms) >= min_words:
839
- filtered_domain_centroids[domain] = centroid
840
- filtered_domain_terms[domain] = " ".join(terms)
841
- valid_indices.append(idx) # Track the valid index
842
-
843
- # Stop once we've reached the max_labels limit
844
- if len(filtered_domain_centroids) >= max_labels:
845
- break
846
-
847
- # Calculate the bounding box around the network
848
- center, radius = _calculate_bounding_box(self.graph.node_coordinates, radius_margin=scale)
849
- # Calculate the best positions for labels
850
- best_label_positions = _calculate_best_label_positions(
851
- filtered_domain_centroids, center, radius, offset
852
- )
853
-
854
- # Annotate the network with labels
855
- for idx, (domain, pos) in zip(valid_indices, best_label_positions.items()):
856
- centroid = filtered_domain_centroids[domain]
857
- annotations = filtered_domain_terms[domain].split(" ")[:max_words]
858
- self.ax.annotate(
859
- "\n".join(annotations),
860
- xy=centroid,
861
- xytext=pos,
862
- textcoords="data",
863
- ha="center",
864
- va="center",
865
- fontsize=fontsize,
866
- fontname=font,
867
- color=fontcolor[idx],
868
- arrowprops=dict(
869
- arrowstyle=arrow_style,
870
- color=arrow_color[idx],
871
- linewidth=arrow_linewidth,
872
- shrinkA=arrow_base_shrink,
873
- shrinkB=arrow_tip_shrink,
874
- ),
875
- )
876
- # Overlay domain ID at the centroid if requested
877
- if overlay_ids:
878
- self.ax.text(
879
- centroid[0],
880
- centroid[1],
881
- domain,
882
- ha="center",
883
- va="center",
884
- fontsize=fontsize,
885
- fontname=font,
886
- color=fontcolor[idx],
887
- alpha=fontalpha,
888
- )
889
-
890
- def plot_sublabel(
891
- self,
892
- nodes: Union[List, Tuple, np.ndarray],
893
- label: str,
894
- radial_position: float = 0.0,
895
- scale: float = 1.05,
896
- offset: float = 0.10,
897
- font: str = "Arial",
898
- fontsize: int = 10,
899
- fontcolor: Union[str, List, Tuple, np.ndarray] = "black",
900
- fontalpha: float = 1.0,
901
- arrow_linewidth: float = 1,
902
- arrow_style: str = "->",
903
- arrow_color: Union[str, List, Tuple, np.ndarray] = "black",
904
- arrow_alpha: float = 1.0,
905
- arrow_base_shrink: float = 0.0,
906
- arrow_tip_shrink: float = 0.0,
907
- ) -> None:
908
- """Annotate the network graph with a label for the given nodes, with one arrow pointing to each centroid of sublists of nodes.
909
-
910
- Args:
911
- nodes (list, tuple, or np.ndarray): List of node labels or list of lists of node labels.
912
- label (str): The label to be annotated on the network.
913
- radial_position (float, optional): Radial angle for positioning the label, in degrees (0-360). Defaults to 0.0.
914
- scale (float, optional): Scale factor for positioning the label around the perimeter. Defaults to 1.05.
915
- offset (float, optional): Offset distance for the label from the perimeter. Defaults to 0.10.
916
- font (str, optional): Font name for the label. Defaults to "Arial".
917
- fontsize (int, optional): Font size for the label. Defaults to 10.
918
- fontcolor (str, list, tuple, or np.ndarray, optional): Color of the label text. Defaults to "black".
919
- fontalpha (float, optional): Transparency level for the font color. Defaults to 1.0.
920
- arrow_linewidth (float, optional): Line width of the arrow pointing to the centroid. Defaults to 1.
921
- arrow_style (str, optional): Style of the arrows pointing to the centroid. Defaults to "->".
922
- arrow_color (str, list, tuple, or np.ndarray, optional): Color of the arrow. Defaults to "black".
923
- arrow_alpha (float, optional): Transparency level for the arrow color. Defaults to 1.0.
924
- arrow_base_shrink (float, optional): Distance between the text and the base of the arrow. Defaults to 0.0.
925
- arrow_tip_shrink (float, optional): Distance between the arrow tip and the centroid. Defaults to 0.0.
926
- """
927
- # Check if nodes is a list of lists or a flat list
928
- if any(isinstance(item, (list, tuple, np.ndarray)) for item in nodes):
929
- # If it's a list of lists, iterate over sublists
930
- node_groups = nodes
931
- else:
932
- # If it's a flat list of nodes, treat it as a single group
933
- node_groups = [nodes]
934
-
935
- # Convert fontcolor and arrow_color to RGBA
936
- fontcolor_rgba = _to_rgba(fontcolor, fontalpha)
937
- arrow_color_rgba = _to_rgba(arrow_color, arrow_alpha)
938
-
939
- # Calculate the bounding box around the network
940
- center, radius = _calculate_bounding_box(self.graph.node_coordinates, radius_margin=scale)
941
- # Convert radial position to radians, adjusting for a 90-degree rotation
942
- radial_radians = np.deg2rad(radial_position - 90)
943
- label_position = (
944
- center[0] + (radius + offset) * np.cos(radial_radians),
945
- center[1] + (radius + offset) * np.sin(radial_radians),
946
- )
947
-
948
- # Iterate over each group of nodes (either sublists or flat list)
949
- for sublist in node_groups:
950
- # Map node labels to IDs
951
- node_ids = [
952
- self.graph.node_label_to_node_id_map.get(node)
953
- for node in sublist
954
- if node in self.graph.node_label_to_node_id_map
955
- ]
956
- if not node_ids or len(node_ids) == 1:
957
- raise ValueError(
958
- "No nodes found in the network graph or insufficient nodes to plot."
959
- )
960
-
961
- # Calculate the centroid of the provided nodes in this sublist
962
- centroid = self._calculate_domain_centroid(node_ids)
963
- # Annotate the network with the label and an arrow pointing to each centroid
964
- self.ax.annotate(
965
- label,
966
- xy=centroid,
967
- xytext=label_position,
968
- textcoords="data",
969
- ha="center",
970
- va="center",
971
- fontsize=fontsize,
972
- fontname=font,
973
- color=fontcolor_rgba,
974
- arrowprops=dict(
975
- arrowstyle=arrow_style,
976
- color=arrow_color_rgba,
977
- linewidth=arrow_linewidth,
978
- shrinkA=arrow_base_shrink,
979
- shrinkB=arrow_tip_shrink,
980
- ),
981
- )
982
-
983
- def _calculate_domain_centroid(self, nodes: List) -> tuple:
984
- """Calculate the most centrally located node in .
985
-
986
- Args:
987
- nodes (list): List of node labels to include in the subnetwork.
988
-
989
- Returns:
990
- tuple: A tuple containing the domain's central node coordinates.
991
- """
992
- # Extract positions of all nodes in the domain
993
- node_positions = self.graph.node_coordinates[nodes, :]
994
- # Calculate the pairwise distance matrix between all nodes in the domain
995
- distances_matrix = np.linalg.norm(node_positions[:, np.newaxis] - node_positions, axis=2)
996
- # Sum the distances for each node to all other nodes in the domain
997
- sum_distances = np.sum(distances_matrix, axis=1)
998
- # Identify the node with the smallest total distance to others (the centroid)
999
- central_node_idx = np.argmin(sum_distances)
1000
- # Map the domain to the coordinates of its central node
1001
- domain_central_node = node_positions[central_node_idx]
1002
- return domain_central_node
1003
-
1004
- def get_annotated_node_colors(
1005
- self,
1006
- cmap: str = "gist_rainbow",
1007
- color: Union[str, None] = None,
1008
- min_scale: float = 0.8,
1009
- max_scale: float = 1.0,
1010
- scale_factor: float = 1.0,
1011
- alpha: float = 1.0,
1012
- nonenriched_color: Union[str, List, Tuple, np.ndarray] = "white",
1013
- nonenriched_alpha: float = 1.0,
1014
- random_seed: int = 888,
1015
- ) -> np.ndarray:
1016
- """Adjust the colors of nodes in the network graph based on enrichment.
1017
-
1018
- Args:
1019
- cmap (str, optional): Colormap to use for coloring the nodes. Defaults to "gist_rainbow".
1020
- color (str or None, optional): Color to use for the nodes. If None, the colormap will be used. Defaults to None.
1021
- min_scale (float, optional): Minimum scale for color intensity. Defaults to 0.8.
1022
- max_scale (float, optional): Maximum scale for color intensity. Defaults to 1.0.
1023
- scale_factor (float, optional): Factor for adjusting the color scaling intensity. Defaults to 1.0.
1024
- alpha (float, optional): Alpha value for enriched nodes. Defaults to 1.0.
1025
- nonenriched_color (str, list, tuple, or np.ndarray, optional): Color for non-enriched nodes. Defaults to "white".
1026
- nonenriched_alpha (float, optional): Alpha value for non-enriched nodes. Defaults to 1.0.
1027
- random_seed (int, optional): Seed for random number generation. Defaults to 888.
1028
-
1029
- Returns:
1030
- np.ndarray: Array of RGBA colors adjusted for enrichment status.
1031
- """
1032
- # Get the initial domain colors for each node, which are returned as RGBA
1033
- network_colors = self.graph.get_domain_colors(
1034
- cmap=cmap,
1035
- color=color,
1036
- min_scale=min_scale,
1037
- max_scale=max_scale,
1038
- scale_factor=scale_factor,
1039
- random_seed=random_seed,
1040
- )
1041
- # Apply the alpha value for enriched nodes
1042
- network_colors[:, 3] = alpha # Apply the alpha value to the enriched nodes' A channel
1043
- # Convert the non-enriched color to RGBA using the _to_rgba helper function
1044
- nonenriched_color = _to_rgba(nonenriched_color, nonenriched_alpha)
1045
- # Adjust node colors: replace any fully black nodes (RGB == 0) with the non-enriched color and its alpha
1046
- adjusted_network_colors = np.where(
1047
- np.all(network_colors[:, :3] == 0, axis=1, keepdims=True), # Check RGB values only
1048
- np.array([nonenriched_color]), # Apply the non-enriched color with alpha
1049
- network_colors, # Keep the original colors for enriched nodes
1050
- )
1051
- return adjusted_network_colors
1052
-
1053
- def get_annotated_node_sizes(
1054
- self, enriched_size: int = 50, nonenriched_size: int = 25
1055
- ) -> np.ndarray:
1056
- """Adjust the sizes of nodes in the network graph based on whether they are enriched or not.
1057
-
1058
- Args:
1059
- enriched_size (int): Size for enriched nodes. Defaults to 50.
1060
- nonenriched_size (int): Size for non-enriched nodes. Defaults to 25.
1061
-
1062
- Returns:
1063
- np.ndarray: Array of node sizes, with enriched nodes larger than non-enriched ones.
1064
- """
1065
- # Merge all enriched nodes from the domain_id_to_node_ids_map dictionary
1066
- enriched_nodes = set()
1067
- for _, node_ids in self.graph.domain_id_to_node_ids_map.items():
1068
- enriched_nodes.update(node_ids)
1069
-
1070
- # Initialize all node sizes to the non-enriched size
1071
- node_sizes = np.full(len(self.graph.network.nodes), nonenriched_size)
1072
- # Set the size for enriched nodes
1073
- for node in enriched_nodes:
1074
- if node in self.graph.network.nodes:
1075
- node_sizes[node] = enriched_size
1076
-
1077
- return node_sizes
1078
-
1079
- def get_annotated_contour_colors(
1080
- self,
1081
- cmap: str = "gist_rainbow",
1082
- color: Union[str, None] = None,
1083
- min_scale: float = 0.8,
1084
- max_scale: float = 1.0,
1085
- scale_factor: float = 1.0,
1086
- random_seed: int = 888,
1087
- ) -> np.ndarray:
1088
- """Get colors for the contours based on node annotations or a specified colormap.
1089
-
1090
- Args:
1091
- cmap (str, optional): Name of the colormap to use for generating contour colors. Defaults to "gist_rainbow".
1092
- color (str or None, optional): Color to use for the contours. If None, the colormap will be used. Defaults to None.
1093
- min_scale (float, optional): Minimum intensity scale for the colors generated by the colormap.
1094
- Controls the dimmest colors. Defaults to 0.8.
1095
- max_scale (float, optional): Maximum intensity scale for the colors generated by the colormap.
1096
- Controls the brightest colors. Defaults to 1.0.
1097
- scale_factor (float, optional): Exponent for adjusting color scaling based on enrichment scores.
1098
- A higher value increases contrast by dimming lower scores more. Defaults to 1.0.
1099
- random_seed (int, optional): Seed for random number generation to ensure reproducibility. Defaults to 888.
1100
-
1101
- Returns:
1102
- np.ndarray: Array of RGBA colors for contour annotations.
1103
- """
1104
- return self._get_annotated_domain_colors(
1105
- cmap=cmap,
1106
- color=color,
1107
- min_scale=min_scale,
1108
- max_scale=max_scale,
1109
- scale_factor=scale_factor,
1110
- random_seed=random_seed,
1111
- )
1112
-
1113
- def get_annotated_label_colors(
1114
- self,
1115
- cmap: str = "gist_rainbow",
1116
- color: Union[str, None] = None,
1117
- min_scale: float = 0.8,
1118
- max_scale: float = 1.0,
1119
- scale_factor: float = 1.0,
1120
- random_seed: int = 888,
1121
- ) -> np.ndarray:
1122
- """Get colors for the labels based on node annotations or a specified colormap.
1123
-
1124
- Args:
1125
- cmap (str, optional): Name of the colormap to use for generating label colors. Defaults to "gist_rainbow".
1126
- color (str or None, optional): Color to use for the labels. If None, the colormap will be used. Defaults to None.
1127
- min_scale (float, optional): Minimum intensity scale for the colors generated by the colormap.
1128
- Controls the dimmest colors. Defaults to 0.8.
1129
- max_scale (float, optional): Maximum intensity scale for the colors generated by the colormap.
1130
- Controls the brightest colors. Defaults to 1.0.
1131
- scale_factor (float, optional): Exponent for adjusting color scaling based on enrichment scores.
1132
- A higher value increases contrast by dimming lower scores more. Defaults to 1.0.
1133
- random_seed (int, optional): Seed for random number generation to ensure reproducibility. Defaults to 888.
1134
-
1135
- Returns:
1136
- np.ndarray: Array of RGBA colors for label annotations.
1137
- """
1138
- return self._get_annotated_domain_colors(
1139
- cmap=cmap,
1140
- color=color,
1141
- min_scale=min_scale,
1142
- max_scale=max_scale,
1143
- scale_factor=scale_factor,
1144
- random_seed=random_seed,
1145
- )
1146
-
1147
- def _get_annotated_domain_colors(
1148
- self,
1149
- cmap: str = "gist_rainbow",
1150
- color: Union[str, None] = None,
1151
- min_scale: float = 0.8,
1152
- max_scale: float = 1.0,
1153
- scale_factor: float = 1.0,
1154
- random_seed: int = 888,
1155
- ) -> np.ndarray:
1156
- """Get colors for the domains based on node annotations, or use a specified color.
1157
-
1158
- Args:
1159
- cmap (str, optional): Colormap to use for generating domain colors. Defaults to "gist_rainbow".
1160
- color (str or None, optional): Color to use for the domains. If None, the colormap will be used. Defaults to None.
1161
- min_scale (float, optional): Minimum scale for color intensity when generating domain colors.
1162
- Defaults to 0.8.
1163
- max_scale (float, optional): Maximum scale for color intensity when generating domain colors.
1164
- Defaults to 1.0.
1165
- scale_factor (float, optional): Factor for adjusting the contrast in the colors generated based on
1166
- enrichment. Higher values increase the contrast. Defaults to 1.0.
1167
- random_seed (int, optional): Seed for random number generation to ensure reproducibility. Defaults to 888.
1168
-
1169
- Returns:
1170
- np.ndarray: Array of RGBA colors for each domain.
1171
- """
1172
- # Generate domain colors based on the enrichment data
1173
- node_colors = self.graph.get_domain_colors(
1174
- cmap=cmap,
1175
- color=color,
1176
- min_scale=min_scale,
1177
- max_scale=max_scale,
1178
- scale_factor=scale_factor,
1179
- random_seed=random_seed,
1180
- )
1181
- annotated_colors = []
1182
- for _, node_ids in self.graph.domain_id_to_node_ids_map.items():
1183
- if len(node_ids) > 1:
1184
- # For multi-node domains, choose the brightest color based on RGB sum
1185
- domain_colors = np.array([node_colors[node] for node in node_ids])
1186
- brightest_color = domain_colors[
1187
- np.argmax(domain_colors[:, :3].sum(axis=1)) # Sum the RGB values
1188
- ]
1189
- annotated_colors.append(brightest_color)
1190
- else:
1191
- # Single-node domains default to white (RGBA)
1192
- default_color = np.array([1.0, 1.0, 1.0, 1.0])
1193
- annotated_colors.append(default_color)
1194
-
1195
- return np.array(annotated_colors)
1196
-
1197
- @staticmethod
1198
- def savefig(*args, pad_inches: float = 0.5, dpi: int = 100, **kwargs) -> None:
1199
- """Save the current plot to a file with additional export options.
1200
-
1201
- Args:
1202
- *args: Positional arguments passed to `plt.savefig`.
1203
- pad_inches (float, optional): Padding around the figure when saving. Defaults to 0.5.
1204
- dpi (int, optional): Dots per inch (DPI) for the exported image. Defaults to 300.
1205
- **kwargs: Keyword arguments passed to `plt.savefig`, such as filename and format.
1206
- """
1207
- plt.savefig(*args, bbox_inches="tight", pad_inches=pad_inches, dpi=dpi, **kwargs)
1208
-
1209
- @staticmethod
1210
- def show(*args, **kwargs) -> None:
1211
- """Display the current plot.
1212
-
1213
- Args:
1214
- *args: Positional arguments passed to `plt.show`.
1215
- **kwargs: Keyword arguments passed to `plt.show`.
1216
- """
1217
- plt.show(*args, **kwargs)
1218
-
1219
-
1220
- def _to_rgba(
1221
- color: Union[str, List, Tuple, np.ndarray],
1222
- alpha: float = 1.0,
1223
- num_repeats: Union[int, None] = None,
1224
- ) -> np.ndarray:
1225
- """Convert a color or array of colors to RGBA format, applying alpha only if the color is RGB.
1226
-
1227
- Args:
1228
- color (Union[str, list, tuple, np.ndarray]): The color(s) to convert. Can be a string, list, tuple, or np.ndarray.
1229
- alpha (float, optional): Alpha value (transparency) to apply if the color is in RGB format. Defaults to 1.0.
1230
- num_repeats (int or None, optional): If provided, the color will be repeated this many times. Defaults to None.
1231
-
1232
- Returns:
1233
- np.ndarray: The RGBA color or array of RGBA colors.
1234
- """
1235
- # Handle single color case (string, RGB, or RGBA)
1236
- if isinstance(color, str) or (
1237
- isinstance(color, (list, tuple, np.ndarray))
1238
- and len(color) in [3, 4]
1239
- and not any(isinstance(c, (list, tuple, np.ndarray)) for c in color)
1240
- ):
1241
- rgba_color = np.array(mcolors.to_rgba(color))
1242
- # Only set alpha if the input is an RGB color or a string (not RGBA)
1243
- if len(rgba_color) == 4 and (
1244
- len(color) == 3 or isinstance(color, str)
1245
- ): # If it's RGB or a string, set the alpha
1246
- rgba_color[3] = alpha
1247
-
1248
- # Repeat the color if num_repeats argument is provided
1249
- if num_repeats is not None:
1250
- return np.array([rgba_color] * num_repeats)
1251
-
1252
- return rgba_color
1253
-
1254
- # Handle array of colors case (including strings, RGB, and RGBA)
1255
- elif isinstance(color, (list, tuple, np.ndarray)):
1256
- rgba_colors = []
1257
- for c in color:
1258
- # Ensure each element is either a valid string or a list/tuple of length 3 (RGB) or 4 (RGBA)
1259
- if isinstance(c, str) or (
1260
- isinstance(c, (list, tuple, np.ndarray)) and len(c) in [3, 4]
1261
- ):
1262
- rgba_c = np.array(mcolors.to_rgba(c))
1263
- # Apply alpha only to RGB colors (not RGBA) and strings
1264
- if len(rgba_c) == 4 and (len(c) == 3 or isinstance(c, str)):
1265
- rgba_c[3] = alpha
1266
-
1267
- rgba_colors.append(rgba_c)
1268
- else:
1269
- raise ValueError(f"Invalid color: {c}. Must be a valid RGB/RGBA or string color.")
1270
-
1271
- # Repeat the colors if num_repeats argument is provided
1272
- if num_repeats is not None and len(rgba_colors) == 1:
1273
- return np.array([rgba_colors[0]] * num_repeats)
1274
-
1275
- return np.array(rgba_colors)
1276
-
1277
- else:
1278
- raise ValueError("Color must be a valid RGB/RGBA or array of RGB/RGBA colors.")
1279
-
1280
-
1281
- def _is_connected(z: np.ndarray) -> bool:
1282
- """Determine if a thresholded grid represents a single, connected component.
1283
-
1284
- Args:
1285
- z (np.ndarray): A binary grid where the component connectivity is evaluated.
1286
-
1287
- Returns:
1288
- bool: True if the grid represents a single connected component, False otherwise.
1289
- """
1290
- _, num_features = label(z)
1291
- return num_features == 1 # Return True if only one connected component is found
1292
-
1293
-
1294
- def _calculate_bounding_box(
1295
- node_coordinates: np.ndarray, radius_margin: float = 1.05
1296
- ) -> Tuple[np.ndarray, float]:
1297
- """Calculate the bounding box of the network based on node coordinates.
1298
-
1299
- Args:
1300
- node_coordinates (np.ndarray): Array of node coordinates (x, y).
1301
- radius_margin (float, optional): Margin factor to apply to the bounding box radius. Defaults to 1.05.
1302
-
1303
- Returns:
1304
- tuple: Center of the bounding box and the radius (adjusted by the radius margin).
1305
- """
1306
- # Find minimum and maximum x, y coordinates
1307
- x_min, y_min = np.min(node_coordinates, axis=0)
1308
- x_max, y_max = np.max(node_coordinates, axis=0)
1309
- # Calculate the center of the bounding box
1310
- center = np.array([(x_min + x_max) / 2, (y_min + y_max) / 2])
1311
- # Calculate the radius of the bounding box, adjusted by the margin
1312
- radius = max(x_max - x_min, y_max - y_min) / 2 * radius_margin
1313
- return center, radius
1314
-
1315
-
1316
- def _calculate_best_label_positions(
1317
- filtered_domain_centroids: Dict[str, Any], center: np.ndarray, radius: float, offset: float
1318
- ) -> Dict[str, Any]:
1319
- """Calculate and optimize label positions for clarity.
1320
-
1321
- Args:
1322
- filtered_domain_centroids (dict): Centroids of the filtered domains.
1323
- center (np.ndarray): The center coordinates for label positioning.
1324
- radius (float): The radius for positioning labels around the center.
1325
- offset (float): The offset distance from the radius for positioning labels.
1326
-
1327
- Returns:
1328
- dict: Optimized positions for labels.
1329
- """
1330
- num_domains = len(filtered_domain_centroids)
1331
- # Calculate equidistant positions around the center for initial label placement
1332
- equidistant_positions = _calculate_equidistant_positions_around_center(
1333
- center, radius, offset, num_domains
1334
- )
1335
- # Create a mapping of domains to their initial label positions
1336
- label_positions = {
1337
- domain: position
1338
- for domain, position in zip(filtered_domain_centroids.keys(), equidistant_positions)
1339
- }
1340
- # Optimize the label positions to minimize distance to domain centroids
1341
- return _optimize_label_positions(label_positions, filtered_domain_centroids)
1342
-
1343
-
1344
- def _calculate_equidistant_positions_around_center(
1345
- center: np.ndarray, radius: float, label_offset: float, num_domains: int
1346
- ) -> List[np.ndarray]:
1347
- """Calculate positions around a center at equidistant angles.
1348
-
1349
- Args:
1350
- center (np.ndarray): The central point around which positions are calculated.
1351
- radius (float): The radius at which positions are calculated.
1352
- label_offset (float): The offset added to the radius for label positioning.
1353
- num_domains (int): The number of positions (or domains) to calculate.
1354
-
1355
- Returns:
1356
- list[np.ndarray]: List of positions (as 2D numpy arrays) around the center.
1357
- """
1358
- # Calculate equidistant angles in radians around the center
1359
- angles = np.linspace(0, 2 * np.pi, num_domains, endpoint=False)
1360
- # Compute the positions around the center using the angles
1361
- return [
1362
- center + (radius + label_offset) * np.array([np.cos(angle), np.sin(angle)])
1363
- for angle in angles
1364
- ]
1365
-
1366
-
1367
- def _optimize_label_positions(
1368
- best_label_positions: Dict[str, Any], domain_centroids: Dict[str, Any]
1369
- ) -> Dict[str, Any]:
1370
- """Optimize label positions around the perimeter to minimize total distance to centroids.
1371
-
1372
- Args:
1373
- best_label_positions (dict): Initial positions of labels around the perimeter.
1374
- domain_centroids (dict): Centroid positions of the domains.
1375
-
1376
- Returns:
1377
- dict: Optimized label positions.
1378
- """
1379
- while True:
1380
- improvement = False # Start each iteration assuming no improvement
1381
- # Iterate through each pair of labels to check for potential improvements
1382
- for i in range(len(domain_centroids)):
1383
- for j in range(i + 1, len(domain_centroids)):
1384
- # Calculate the current total distance
1385
- current_distance = _calculate_total_distance(best_label_positions, domain_centroids)
1386
- # Evaluate the total distance after swapping two labels
1387
- swapped_distance = _swap_and_evaluate(best_label_positions, i, j, domain_centroids)
1388
- # If the swap improves the total distance, perform the swap
1389
- if swapped_distance < current_distance:
1390
- labels = list(best_label_positions.keys())
1391
- best_label_positions[labels[i]], best_label_positions[labels[j]] = (
1392
- best_label_positions[labels[j]],
1393
- best_label_positions[labels[i]],
1394
- )
1395
- improvement = True # Found an improvement, so continue optimizing
1396
-
1397
- if not improvement:
1398
- break # Exit the loop if no improvement was found in this iteration
1399
-
1400
- return best_label_positions
1401
-
1402
-
1403
- def _calculate_total_distance(
1404
- label_positions: Dict[str, Any], domain_centroids: Dict[str, Any]
1405
- ) -> float:
1406
- """Calculate the total distance from label positions to their domain centroids.
1407
-
1408
- Args:
1409
- label_positions (dict): Positions of labels around the perimeter.
1410
- domain_centroids (dict): Centroid positions of the domains.
1411
-
1412
- Returns:
1413
- float: The total distance from labels to centroids.
1414
- """
1415
- total_distance = 0
1416
- # Iterate through each domain and calculate the distance to its centroid
1417
- for domain, pos in label_positions.items():
1418
- centroid = domain_centroids[domain]
1419
- total_distance += np.linalg.norm(centroid - pos)
1420
-
1421
- return total_distance
1422
-
1423
-
1424
- def _swap_and_evaluate(
1425
- label_positions: Dict[str, Any],
1426
- i: int,
1427
- j: int,
1428
- domain_centroids: Dict[str, Any],
1429
- ) -> float:
1430
- """Swap two labels and evaluate the total distance after the swap.
1431
-
1432
- Args:
1433
- label_positions (dict): Positions of labels around the perimeter.
1434
- i (int): Index of the first label to swap.
1435
- j (int): Index of the second label to swap.
1436
- domain_centroids (dict): Centroid positions of the domains.
1437
-
1438
- Returns:
1439
- float: The total distance after swapping the two labels.
1440
- """
1441
- # Get the list of labels from the dictionary keys
1442
- labels = list(label_positions.keys())
1443
- swapped_positions = label_positions.copy()
1444
- # Swap the positions of the two specified labels
1445
- swapped_positions[labels[i]], swapped_positions[labels[j]] = (
1446
- swapped_positions[labels[j]],
1447
- swapped_positions[labels[i]],
1448
- )
1449
- # Calculate and return the total distance after the swap
1450
- return _calculate_total_distance(swapped_positions, domain_centroids)