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