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.
@@ -0,0 +1,929 @@
1
+ """
2
+ risk/network/plot/labels
3
+ ~~~~~~~~~~~~~~~~~~~~~~~~
4
+ """
5
+
6
+ import copy
7
+ from typing import Any, Dict, List, Tuple, Union
8
+
9
+ import matplotlib.pyplot as plt
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ from risk.log import params
14
+ from risk.network.graph import NetworkGraph
15
+ from risk.network.plot.utils.color import get_annotated_domain_colors, to_rgba
16
+ from risk.network.plot.utils.layout import calculate_bounding_box
17
+
18
+ TERM_DELIMITER = "::::" # String used to separate multiple domain terms when constructing composite domain labels
19
+
20
+
21
+ class Labels:
22
+ """Class to handle the annotation of network graphs with labels for different domains."""
23
+
24
+ def __init__(self, graph: NetworkGraph, ax: plt.Axes):
25
+ """Initialize the Labeler object with a network graph and matplotlib axes.
26
+
27
+ Args:
28
+ graph (NetworkGraph): NetworkGraph object containing the network data.
29
+ ax (plt.Axes): Matplotlib axes object to plot the labels on.
30
+ """
31
+ self.graph = graph
32
+ self.ax = ax
33
+
34
+ def plot_labels(
35
+ self,
36
+ scale: float = 1.05,
37
+ offset: float = 0.10,
38
+ font: str = "Arial",
39
+ fontcase: Union[str, Dict[str, str], None] = None,
40
+ fontsize: int = 10,
41
+ fontcolor: Union[str, List, Tuple, np.ndarray] = "black",
42
+ fontalpha: Union[float, None] = 1.0,
43
+ arrow_linewidth: float = 1,
44
+ arrow_style: str = "->",
45
+ arrow_color: Union[str, List, Tuple, np.ndarray] = "black",
46
+ arrow_alpha: Union[float, None] = 1.0,
47
+ arrow_base_shrink: float = 0.0,
48
+ arrow_tip_shrink: float = 0.0,
49
+ max_labels: Union[int, None] = None,
50
+ max_label_lines: Union[int, None] = None,
51
+ min_label_lines: int = 1,
52
+ max_chars_per_line: Union[int, None] = None,
53
+ min_chars_per_line: int = 1,
54
+ words_to_omit: Union[List, None] = None,
55
+ overlay_ids: bool = False,
56
+ ids_to_keep: Union[List, Tuple, np.ndarray, None] = None,
57
+ ids_to_replace: Union[Dict, None] = None,
58
+ ) -> None:
59
+ """Annotate the network graph with labels for different domains, positioned around the network for clarity.
60
+
61
+ Args:
62
+ scale (float, optional): Scale factor for positioning labels around the perimeter. Defaults to 1.05.
63
+ offset (float, optional): Offset distance for labels from the perimeter. Defaults to 0.10.
64
+ font (str, optional): Font name for the labels. Defaults to "Arial".
65
+ fontcase (Union[str, Dict[str, str], None]): Defines how to transform the case of words.
66
+ - If a string (e.g., 'upper', 'lower', 'title'), applies the transformation to all words.
67
+ - If a dictionary, maps specific cases ('lower', 'upper', 'title') to transformations (e.g., 'lower'='upper').
68
+ - If None, no transformation is applied.
69
+ fontsize (int, optional): Font size for the labels. Defaults to 10.
70
+ fontcolor (str, List, Tuple, or np.ndarray, optional): Color of the label text. Can be a string or RGBA array.
71
+ Defaults to "black".
72
+ fontalpha (float, None, optional): Transparency level for the font color. If provided, it overrides any existing alpha
73
+ values found in fontcolor. Defaults to 1.0.
74
+ arrow_linewidth (float, optional): Line width of the arrows pointing to centroids. Defaults to 1.
75
+ arrow_style (str, optional): Style of the arrows pointing to centroids. Defaults to "->".
76
+ arrow_color (str, List, Tuple, or np.ndarray, optional): Color of the arrows. Defaults to "black".
77
+ arrow_alpha (float, None, optional): Transparency level for the arrow color. If provided, it overrides any existing alpha
78
+ values found in arrow_color. Defaults to 1.0.
79
+ arrow_base_shrink (float, optional): Distance between the text and the base of the arrow. Defaults to 0.0.
80
+ arrow_tip_shrink (float, optional): Distance between the arrow tip and the centroid. Defaults to 0.0.
81
+ max_labels (int, optional): Maximum number of labels to plot. Defaults to None (no limit).
82
+ min_label_lines (int, optional): Minimum number of lines in a label. Defaults to 1.
83
+ max_label_lines (int, optional): Maximum number of lines in a label. Defaults to None (no limit).
84
+ min_chars_per_line (int, optional): Minimum number of characters in a line to display. Defaults to 1.
85
+ max_chars_per_line (int, optional): Maximum number of characters in a line to display. Defaults to None (no limit).
86
+ words_to_omit (List, optional): List of words to omit from the labels. Defaults to None.
87
+ overlay_ids (bool, optional): Whether to overlay domain IDs in the center of the centroids. Defaults to False.
88
+ ids_to_keep (List, Tuple, np.ndarray, or None, optional): IDs of domains that must be labeled. To discover domain IDs,
89
+ you can set `overlay_ids=True`. Defaults to None.
90
+ ids_to_replace (Dict, optional): A dictionary mapping domain IDs to custom labels (strings). The labels should be
91
+ space-separated words. If provided, the custom labels will replace the default domain terms. To discover domain IDs, you
92
+ can set `overlay_ids=True`. Defaults to None.
93
+
94
+ Raises:
95
+ ValueError: If the number of provided `ids_to_keep` exceeds `max_labels`.
96
+ """
97
+ # Log the plotting parameters
98
+ params.log_plotter(
99
+ label_perimeter_scale=scale,
100
+ label_offset=offset,
101
+ label_font=font,
102
+ label_fontcase=fontcase,
103
+ label_fontsize=fontsize,
104
+ label_fontcolor=(
105
+ "custom" if isinstance(fontcolor, np.ndarray) else fontcolor
106
+ ), # np.ndarray usually indicates custom colors
107
+ label_fontalpha=fontalpha,
108
+ label_arrow_linewidth=arrow_linewidth,
109
+ label_arrow_style=arrow_style,
110
+ label_arrow_color="custom" if isinstance(arrow_color, np.ndarray) else arrow_color,
111
+ label_arrow_alpha=arrow_alpha,
112
+ label_arrow_base_shrink=arrow_base_shrink,
113
+ label_arrow_tip_shrink=arrow_tip_shrink,
114
+ label_max_labels=max_labels,
115
+ label_min_label_lines=min_label_lines,
116
+ label_max_label_lines=max_label_lines,
117
+ label_max_chars_per_line=max_chars_per_line,
118
+ label_min_chars_per_line=min_chars_per_line,
119
+ label_words_to_omit=words_to_omit,
120
+ label_overlay_ids=overlay_ids,
121
+ label_ids_to_keep=ids_to_keep,
122
+ label_ids_to_replace=ids_to_replace,
123
+ )
124
+
125
+ # Convert ids_to_keep to a tuple if it is not None
126
+ ids_to_keep = tuple(ids_to_keep) if ids_to_keep else tuple()
127
+ # Set max_labels to the total number of domains if not provided (None)
128
+ if max_labels is None:
129
+ max_labels = len(self.graph.domain_id_to_node_ids_map)
130
+ # Set max_label_lines and max_chars_per_line to large numbers if not provided (None)
131
+ if max_label_lines is None:
132
+ max_label_lines = int(1e6)
133
+ if max_chars_per_line is None:
134
+ max_chars_per_line = int(1e6)
135
+ # Normalize words_to_omit to lowercase
136
+ if words_to_omit:
137
+ words_to_omit = set(word.lower() for word in words_to_omit)
138
+
139
+ # Calculate the center and radius of domains to position labels around the network
140
+ domain_id_to_centroid_map = {}
141
+ for domain_id, node_ids in self.graph.domain_id_to_node_ids_map.items():
142
+ if node_ids: # Skip if the domain has no nodes
143
+ domain_id_to_centroid_map[domain_id] = self._calculate_domain_centroid(node_ids)
144
+
145
+ # Initialize dictionaries and lists for valid indices
146
+ valid_indices = [] # List of valid indices to plot colors and arrows
147
+ filtered_domain_centroids = {} # Filtered domain centroids to plot
148
+ filtered_domain_terms = {} # Filtered domain terms to plot
149
+ # Handle the ids_to_keep logic
150
+ if ids_to_keep:
151
+ # Process the ids_to_keep first INPLACE
152
+ self._process_ids_to_keep(
153
+ domain_id_to_centroid_map=domain_id_to_centroid_map,
154
+ ids_to_keep=ids_to_keep,
155
+ ids_to_replace=ids_to_replace,
156
+ words_to_omit=words_to_omit,
157
+ max_labels=max_labels,
158
+ min_label_lines=min_label_lines,
159
+ max_label_lines=max_label_lines,
160
+ min_chars_per_line=min_chars_per_line,
161
+ max_chars_per_line=max_chars_per_line,
162
+ filtered_domain_centroids=filtered_domain_centroids,
163
+ filtered_domain_terms=filtered_domain_terms,
164
+ valid_indices=valid_indices,
165
+ )
166
+
167
+ # Calculate remaining labels to plot after processing ids_to_keep
168
+ remaining_labels = (
169
+ max_labels - len(valid_indices) if valid_indices and max_labels else max_labels
170
+ )
171
+ # Process remaining domains INPLACE to fill in additional labels, if there are slots left
172
+ if remaining_labels and remaining_labels > 0:
173
+ self._process_remaining_domains(
174
+ domain_id_to_centroid_map=domain_id_to_centroid_map,
175
+ ids_to_keep=ids_to_keep,
176
+ ids_to_replace=ids_to_replace,
177
+ words_to_omit=words_to_omit,
178
+ remaining_labels=remaining_labels,
179
+ min_chars_per_line=min_chars_per_line,
180
+ max_chars_per_line=max_chars_per_line,
181
+ max_label_lines=max_label_lines,
182
+ min_label_lines=min_label_lines,
183
+ filtered_domain_centroids=filtered_domain_centroids,
184
+ filtered_domain_terms=filtered_domain_terms,
185
+ valid_indices=valid_indices,
186
+ )
187
+
188
+ # Calculate the bounding box around the network
189
+ center, radius = calculate_bounding_box(self.graph.node_coordinates, radius_margin=scale)
190
+ # Calculate the best positions for labels
191
+ best_label_positions = _calculate_best_label_positions(
192
+ filtered_domain_centroids, center, radius, offset
193
+ )
194
+ # Convert all domain colors to RGBA using the to_rgba helper function
195
+ fontcolor_rgba = to_rgba(
196
+ color=fontcolor, alpha=fontalpha, num_repeats=len(self.graph.domain_id_to_node_ids_map)
197
+ )
198
+ arrow_color_rgba = to_rgba(
199
+ color=arrow_color,
200
+ alpha=arrow_alpha,
201
+ num_repeats=len(self.graph.domain_id_to_node_ids_map),
202
+ )
203
+
204
+ # Annotate the network with labels
205
+ for idx, (domain, pos) in zip(valid_indices, best_label_positions.items()):
206
+ centroid = filtered_domain_centroids[domain]
207
+ # Split by special key TERM_DELIMITER to split annotation into multiple lines
208
+ annotations = filtered_domain_terms[domain].split(TERM_DELIMITER)
209
+ if fontcase is not None:
210
+ annotations = _apply_str_transformation(words=annotations, transformation=fontcase)
211
+ self.ax.annotate(
212
+ "\n".join(annotations),
213
+ xy=centroid,
214
+ xytext=pos,
215
+ textcoords="data",
216
+ ha="center",
217
+ va="center",
218
+ fontsize=fontsize,
219
+ fontname=font,
220
+ color=fontcolor_rgba[idx],
221
+ arrowprops=dict(
222
+ arrowstyle=arrow_style,
223
+ color=arrow_color_rgba[idx],
224
+ linewidth=arrow_linewidth,
225
+ shrinkA=arrow_base_shrink,
226
+ shrinkB=arrow_tip_shrink,
227
+ ),
228
+ )
229
+
230
+ # Overlay domain ID at the centroid regardless of max_labels if requested
231
+ if overlay_ids:
232
+ for idx, domain in enumerate(self.graph.domain_id_to_node_ids_map):
233
+ centroid = domain_id_to_centroid_map[domain]
234
+ self.ax.text(
235
+ centroid[0],
236
+ centroid[1],
237
+ domain,
238
+ ha="center",
239
+ va="center",
240
+ fontsize=fontsize,
241
+ fontname=font,
242
+ color=fontcolor_rgba[idx],
243
+ )
244
+
245
+ def plot_sublabel(
246
+ self,
247
+ nodes: Union[List, Tuple, np.ndarray],
248
+ label: str,
249
+ radial_position: float = 0.0,
250
+ scale: float = 1.05,
251
+ offset: float = 0.10,
252
+ font: str = "Arial",
253
+ fontsize: int = 10,
254
+ fontcolor: Union[str, List, Tuple, np.ndarray] = "black",
255
+ fontalpha: Union[float, None] = 1.0,
256
+ arrow_linewidth: float = 1,
257
+ arrow_style: str = "->",
258
+ arrow_color: Union[str, List, Tuple, np.ndarray] = "black",
259
+ arrow_alpha: Union[float, None] = 1.0,
260
+ arrow_base_shrink: float = 0.0,
261
+ arrow_tip_shrink: float = 0.0,
262
+ ) -> None:
263
+ """Annotate the network graph with a label for the given nodes, with one arrow pointing to each centroid of sublists of nodes.
264
+
265
+ Args:
266
+ nodes (List, Tuple, or np.ndarray): List of node labels or list of lists of node labels.
267
+ label (str): The label to be annotated on the network.
268
+ radial_position (float, optional): Radial angle for positioning the label, in degrees (0-360). Defaults to 0.0.
269
+ scale (float, optional): Scale factor for positioning the label around the perimeter. Defaults to 1.05.
270
+ offset (float, optional): Offset distance for the label from the perimeter. Defaults to 0.10.
271
+ font (str, optional): Font name for the label. Defaults to "Arial".
272
+ fontsize (int, optional): Font size for the label. Defaults to 10.
273
+ fontcolor (str, List, Tuple, or np.ndarray, optional): Color of the label text. Defaults to "black".
274
+ fontalpha (float, None, optional): Transparency level for the font color. If provided, it overrides any existing alpha values found
275
+ in fontalpha. Defaults to 1.0.
276
+ arrow_linewidth (float, optional): Line width of the arrow pointing to the centroid. Defaults to 1.
277
+ arrow_style (str, optional): Style of the arrows pointing to the centroid. Defaults to "->".
278
+ arrow_color (str, List, Tuple, or np.ndarray, optional): Color of the arrow. Defaults to "black".
279
+ arrow_alpha (float, None, optional): Transparency level for the arrow color. If provided, it overrides any existing alpha values
280
+ found in arrow_alpha. Defaults to 1.0.
281
+ arrow_base_shrink (float, optional): Distance between the text and the base of the arrow. Defaults to 0.0.
282
+ arrow_tip_shrink (float, optional): Distance between the arrow tip and the centroid. Defaults to 0.0.
283
+ """
284
+ # Check if nodes is a list of lists or a flat list
285
+ if any(isinstance(item, (list, tuple, np.ndarray)) for item in nodes):
286
+ # If it's a list of lists, iterate over sublists
287
+ node_groups = nodes
288
+ # Convert fontcolor and arrow_color to RGBA arrays to match the number of groups
289
+ fontcolor_rgba = to_rgba(color=fontcolor, alpha=fontalpha, num_repeats=len(node_groups))
290
+ arrow_color_rgba = to_rgba(
291
+ color=arrow_color, alpha=arrow_alpha, num_repeats=len(node_groups)
292
+ )
293
+ else:
294
+ # If it's a flat list of nodes, treat it as a single group
295
+ node_groups = [nodes]
296
+ # Wrap the RGBA fontcolor and arrow_color in an array to index the first element
297
+ fontcolor_rgba = np.array(to_rgba(color=fontcolor, alpha=fontalpha, num_repeats=1))
298
+ arrow_color_rgba = np.array(
299
+ to_rgba(color=arrow_color, alpha=arrow_alpha, num_repeats=1)
300
+ )
301
+
302
+ # Calculate the bounding box around the network
303
+ center, radius = calculate_bounding_box(self.graph.node_coordinates, radius_margin=scale)
304
+ # Convert radial position to radians, adjusting for a 90-degree rotation
305
+ radial_radians = np.deg2rad(radial_position - 90)
306
+ label_position = (
307
+ center[0] + (radius + offset) * np.cos(radial_radians),
308
+ center[1] + (radius + offset) * np.sin(radial_radians),
309
+ )
310
+
311
+ # Iterate over each group of nodes (either sublists or flat list)
312
+ for idx, sublist in enumerate(node_groups):
313
+ # Map node labels to IDs
314
+ node_ids = [
315
+ self.graph.node_label_to_node_id_map.get(node)
316
+ for node in sublist
317
+ if node in self.graph.node_label_to_node_id_map
318
+ ]
319
+ if not node_ids or len(node_ids) == 1:
320
+ raise ValueError(
321
+ "No nodes found in the network graph or insufficient nodes to plot."
322
+ )
323
+
324
+ # Calculate the centroid of the provided nodes in this sublist
325
+ centroid = self._calculate_domain_centroid(node_ids)
326
+ # Annotate the network with the label and an arrow pointing to each centroid
327
+ self.ax.annotate(
328
+ label,
329
+ xy=centroid,
330
+ xytext=label_position,
331
+ textcoords="data",
332
+ ha="center",
333
+ va="center",
334
+ fontsize=fontsize,
335
+ fontname=font,
336
+ color=fontcolor_rgba[idx],
337
+ arrowprops=dict(
338
+ arrowstyle=arrow_style,
339
+ color=arrow_color_rgba[idx],
340
+ linewidth=arrow_linewidth,
341
+ shrinkA=arrow_base_shrink,
342
+ shrinkB=arrow_tip_shrink,
343
+ ),
344
+ )
345
+
346
+ def _calculate_domain_centroid(self, nodes: List) -> tuple:
347
+ """Calculate the most centrally located node in .
348
+
349
+ Args:
350
+ nodes (List): List of node labels to include in the subnetwork.
351
+
352
+ Returns:
353
+ tuple: A tuple containing the domain's central node coordinates.
354
+ """
355
+ # Extract positions of all nodes in the domain
356
+ node_positions = self.graph.node_coordinates[nodes, :]
357
+ # Calculate the pairwise distance matrix between all nodes in the domain
358
+ distances_matrix = np.linalg.norm(node_positions[:, np.newaxis] - node_positions, axis=2)
359
+ # Sum the distances for each node to all other nodes in the domain
360
+ sum_distances = np.sum(distances_matrix, axis=1)
361
+ # Identify the node with the smallest total distance to others (the centroid)
362
+ central_node_idx = np.argmin(sum_distances)
363
+ # Map the domain to the coordinates of its central node
364
+ domain_central_node = node_positions[central_node_idx]
365
+ return domain_central_node
366
+
367
+ def _process_ids_to_keep(
368
+ self,
369
+ domain_id_to_centroid_map: Dict[str, np.ndarray],
370
+ ids_to_keep: Union[List[str], Tuple[str], np.ndarray],
371
+ ids_to_replace: Union[Dict[str, str], None],
372
+ words_to_omit: Union[List[str], None],
373
+ max_labels: Union[int, None],
374
+ min_label_lines: int,
375
+ max_label_lines: int,
376
+ min_chars_per_line: int,
377
+ max_chars_per_line: int,
378
+ filtered_domain_centroids: Dict[str, np.ndarray],
379
+ filtered_domain_terms: Dict[str, str],
380
+ valid_indices: List[int],
381
+ ) -> None:
382
+ """Process the ids_to_keep, apply filtering, and store valid domain centroids and terms.
383
+
384
+ Args:
385
+ domain_id_to_centroid_map (Dict[str, np.ndarray]): Mapping of domain IDs to their centroids.
386
+ ids_to_keep (List, Tuple, or np.ndarray, optional): IDs of domains that must be labeled.
387
+ ids_to_replace (Dict[str, str], optional): A dictionary mapping domain IDs to custom labels. Defaults to None.
388
+ words_to_omit (List, optional): List of words to omit from the labels. Defaults to None.
389
+ max_labels (int, optional): Maximum number of labels allowed.
390
+ min_label_lines (int): Minimum number of lines in a label.
391
+ max_label_lines (int): Maximum number of lines in a label.
392
+ min_chars_per_line (int): Minimum number of characters in a line to display.
393
+ max_chars_per_line (int): Maximum number of characters in a line to display.
394
+ filtered_domain_centroids (Dict[str, np.ndarray]): Dictionary to store filtered domain centroids (output).
395
+ filtered_domain_terms (Dict[str, str]): Dictionary to store filtered domain terms (output).
396
+ valid_indices (List): List to store valid indices (output).
397
+
398
+ Note:
399
+ The `filtered_domain_centroids`, `filtered_domain_terms`, and `valid_indices` are modified in-place.
400
+
401
+ Raises:
402
+ ValueError: If the number of provided `ids_to_keep` exceeds `max_labels`.
403
+ """
404
+ # Check if the number of provided ids_to_keep exceeds max_labels
405
+ if max_labels is not None and len(ids_to_keep) > max_labels:
406
+ raise ValueError(
407
+ f"Number of provided IDs ({len(ids_to_keep)}) exceeds max_labels ({max_labels})."
408
+ )
409
+
410
+ # Process each domain in ids_to_keep
411
+ for domain in ids_to_keep:
412
+ if (
413
+ domain in self.graph.domain_id_to_domain_terms_map
414
+ and domain in domain_id_to_centroid_map
415
+ ):
416
+ domain_centroid = domain_id_to_centroid_map[domain]
417
+ # No need to filter the domain terms if it is in ids_to_keep
418
+ _ = self._validate_and_update_domain(
419
+ domain=domain,
420
+ domain_centroid=domain_centroid,
421
+ domain_id_to_centroid_map=domain_id_to_centroid_map,
422
+ ids_to_replace=ids_to_replace,
423
+ words_to_omit=words_to_omit,
424
+ min_label_lines=min_label_lines,
425
+ max_label_lines=max_label_lines,
426
+ min_chars_per_line=min_chars_per_line,
427
+ max_chars_per_line=max_chars_per_line,
428
+ filtered_domain_centroids=filtered_domain_centroids,
429
+ filtered_domain_terms=filtered_domain_terms,
430
+ valid_indices=valid_indices,
431
+ )
432
+
433
+ def _process_remaining_domains(
434
+ self,
435
+ domain_id_to_centroid_map: Dict[str, np.ndarray],
436
+ ids_to_keep: Union[List[str], Tuple[str], np.ndarray],
437
+ ids_to_replace: Union[Dict[str, str], None],
438
+ words_to_omit: Union[List[str], None],
439
+ remaining_labels: int,
440
+ min_label_lines: int,
441
+ max_label_lines: int,
442
+ min_chars_per_line: int,
443
+ max_chars_per_line: int,
444
+ filtered_domain_centroids: Dict[str, np.ndarray],
445
+ filtered_domain_terms: Dict[str, str],
446
+ valid_indices: List[int],
447
+ ) -> None:
448
+ """Process remaining domains to fill in additional labels, respecting the remaining_labels limit.
449
+
450
+ Args:
451
+ domain_id_to_centroid_map (Dict[str, np.ndarray]): Mapping of domain IDs to their centroids.
452
+ ids_to_keep (List, Tuple, or np.ndarray, optional): IDs of domains that must be labeled.
453
+ ids_to_replace (Dict[str, str], optional): A dictionary mapping domain IDs to custom labels. Defaults to None.
454
+ words_to_omit (List, optional): List of words to omit from the labels. Defaults to None.
455
+ remaining_labels (int): The remaining number of labels that can be generated.
456
+ min_label_lines (int): Minimum number of lines in a label.
457
+ max_label_lines (int): Maximum number of lines in a label.
458
+ min_chars_per_line (int): Minimum number of characters in a line to display.
459
+ max_chars_per_line (int): Maximum number of characters in a line to display.
460
+ filtered_domain_centroids (Dict[str, np.ndarray]): Dictionary to store filtered domain centroids (output).
461
+ filtered_domain_terms (Dict[str, str]): Dictionary to store filtered domain terms (output).
462
+ valid_indices (List): List to store valid indices (output).
463
+
464
+ Note:
465
+ The `filtered_domain_centroids`, `filtered_domain_terms`, and `valid_indices` are modified in-place.
466
+ """
467
+ # Counter to track how many labels have been created
468
+ label_count = 0
469
+ # Collect domains not in ids_to_keep
470
+ remaining_domains = {
471
+ domain: centroid
472
+ for domain, centroid in domain_id_to_centroid_map.items()
473
+ if domain not in ids_to_keep and not pd.isna(domain)
474
+ }
475
+
476
+ # Function to calculate distance between two centroids
477
+ def calculate_distance(centroid1, centroid2):
478
+ return np.linalg.norm(centroid1 - centroid2)
479
+
480
+ # Domains to plot on network
481
+ selected_domains = []
482
+ # Find the farthest apart domains using centroids
483
+ if remaining_domains and remaining_labels:
484
+ first_domain = next(iter(remaining_domains)) # Pick the first domain to start
485
+ selected_domains.append(first_domain)
486
+
487
+ while len(selected_domains) < remaining_labels:
488
+ farthest_domain = None
489
+ max_distance = -1
490
+ # Find the domain farthest from any already selected domain
491
+ for candidate_domain, candidate_centroid in remaining_domains.items():
492
+ if candidate_domain in selected_domains:
493
+ continue
494
+
495
+ # Calculate the minimum distance to any selected domain
496
+ min_distance = min(
497
+ calculate_distance(candidate_centroid, remaining_domains[dom])
498
+ for dom in selected_domains
499
+ )
500
+ # Update the farthest domain if the minimum distance is greater
501
+ if min_distance > max_distance:
502
+ max_distance = min_distance
503
+ farthest_domain = candidate_domain
504
+
505
+ # Add the farthest domain to the selected domains
506
+ if farthest_domain:
507
+ selected_domains.append(farthest_domain)
508
+ else:
509
+ break # No more domains to select
510
+
511
+ # Process the selected domains and add to filtered lists
512
+ for domain in selected_domains:
513
+ domain_centroid = remaining_domains[domain]
514
+ is_domain_valid = self._validate_and_update_domain(
515
+ domain=domain,
516
+ domain_centroid=domain_centroid,
517
+ domain_id_to_centroid_map=domain_id_to_centroid_map,
518
+ ids_to_replace=ids_to_replace,
519
+ words_to_omit=words_to_omit,
520
+ min_label_lines=min_label_lines,
521
+ max_label_lines=max_label_lines,
522
+ min_chars_per_line=min_chars_per_line,
523
+ max_chars_per_line=max_chars_per_line,
524
+ filtered_domain_centroids=filtered_domain_centroids,
525
+ filtered_domain_terms=filtered_domain_terms,
526
+ valid_indices=valid_indices,
527
+ )
528
+ # Increment the label count if the domain is valid
529
+ if is_domain_valid:
530
+ label_count += 1
531
+ if label_count >= remaining_labels:
532
+ break
533
+
534
+ def _validate_and_update_domain(
535
+ self,
536
+ domain: str,
537
+ domain_centroid: np.ndarray,
538
+ domain_id_to_centroid_map: Dict[str, np.ndarray],
539
+ ids_to_replace: Union[Dict[str, str], None],
540
+ words_to_omit: Union[List[str], None],
541
+ min_label_lines: int,
542
+ max_label_lines: int,
543
+ min_chars_per_line: int,
544
+ max_chars_per_line: int,
545
+ filtered_domain_centroids: Dict[str, np.ndarray],
546
+ filtered_domain_terms: Dict[str, str],
547
+ valid_indices: List[int],
548
+ ) -> bool:
549
+ """Validate and process the domain terms, updating relevant dictionaries if valid.
550
+
551
+ Args:
552
+ domain (str): Domain ID to process.
553
+ domain_centroid (np.ndarray): Centroid position of the domain.
554
+ domain_id_to_centroid_map (Dict[str, np.ndarray]): Mapping of domain IDs to their centroids.
555
+ ids_to_replace (Dict[str, str], None, optional): A dictionary mapping domain IDs to custom labels. Defaults to None.
556
+ words_to_omit (List[str], None, optional): List of words to omit from the labels. Defaults to None.
557
+ min_label_lines (int): Minimum number of lines required in a label.
558
+ max_label_lines (int): Maximum number of lines allowed in a label.
559
+ min_chars_per_line (int): Minimum number of characters allowed per line.
560
+ max_chars_per_line (int): Maximum number of characters allowed per line.
561
+ filtered_domain_centroids (Dict[str, np.ndarray]): Dictionary to store valid domain centroids.
562
+ filtered_domain_terms (Dict[str, str]): Dictionary to store valid domain terms.
563
+ valid_indices (List[int]): List of valid domain indices.
564
+
565
+ Returns:
566
+ bool: True if the domain is valid and added to the filtered dictionaries, False otherwise.
567
+
568
+ Note:
569
+ The `filtered_domain_centroids`, `filtered_domain_terms`, and `valid_indices` are modified in-place.
570
+ """
571
+ # Process the domain terms
572
+ domain_terms = self._process_terms(
573
+ domain=domain,
574
+ ids_to_replace=ids_to_replace,
575
+ words_to_omit=words_to_omit,
576
+ max_label_lines=max_label_lines,
577
+ min_chars_per_line=min_chars_per_line,
578
+ max_chars_per_line=max_chars_per_line,
579
+ )
580
+ # If domain_terms is empty, skip further processing
581
+ if not domain_terms:
582
+ return False
583
+
584
+ # Split the terms by TERM_DELIMITER and count the number of lines
585
+ num_domain_lines = len(domain_terms.split(TERM_DELIMITER))
586
+ # Check if the number of lines is greater than or equal to the minimum
587
+ if num_domain_lines >= min_label_lines:
588
+ filtered_domain_centroids[domain] = domain_centroid
589
+ filtered_domain_terms[domain] = domain_terms
590
+ # Add the index of the domain to the valid indices list
591
+ valid_indices.append(list(domain_id_to_centroid_map.keys()).index(domain))
592
+ return True
593
+
594
+ return False
595
+
596
+ def _process_terms(
597
+ self,
598
+ domain: str,
599
+ ids_to_replace: Union[Dict[str, str], None],
600
+ words_to_omit: Union[List[str], None],
601
+ max_label_lines: int,
602
+ min_chars_per_line: int,
603
+ max_chars_per_line: int,
604
+ ) -> List[str]:
605
+ """Process terms for a domain, applying word length constraints and combining words where appropriate.
606
+
607
+ Args:
608
+ domain (str): The domain being processed.
609
+ ids_to_replace (Dict[str, str], optional): Dictionary mapping domain IDs to custom labels.
610
+ words_to_omit (List, optional): List of words to omit from the labels.
611
+ max_label_lines (int): Maximum number of lines in a label.
612
+ min_chars_per_line (int): Minimum number of characters in a line to display.
613
+ max_chars_per_line (int): Maximum number of characters in a line to display.
614
+
615
+ Returns:
616
+ str: Processed terms separated by TERM_DELIMITER, with words combined if necessary to fit within constraints.
617
+ """
618
+ # Return custom labels if domain is in ids_to_replace
619
+ if ids_to_replace and domain in ids_to_replace:
620
+ terms = ids_to_replace[domain].replace(" ", TERM_DELIMITER)
621
+ return terms
622
+
623
+ else:
624
+ terms = self.graph.domain_id_to_domain_terms_map[domain].split(" ")
625
+
626
+ # Apply words_to_omit and word length constraints
627
+ if words_to_omit:
628
+ terms = [
629
+ term
630
+ for term in terms
631
+ if term.lower() not in words_to_omit and len(term) >= min_chars_per_line
632
+ ]
633
+
634
+ # Use the combine_words function directly to handle word combinations and length constraints
635
+ compressed_terms = _combine_words(tuple(terms), max_chars_per_line, max_label_lines)
636
+
637
+ return compressed_terms
638
+
639
+ def get_annotated_label_colors(
640
+ self,
641
+ cmap: str = "gist_rainbow",
642
+ color: Union[str, List, Tuple, np.ndarray, None] = None,
643
+ blend_colors: bool = False,
644
+ blend_gamma: float = 2.2,
645
+ min_scale: float = 0.8,
646
+ max_scale: float = 1.0,
647
+ scale_factor: float = 1.0,
648
+ random_seed: int = 888,
649
+ ) -> np.ndarray:
650
+ """Get colors for the labels based on node annotations or a specified colormap.
651
+
652
+ Args:
653
+ cmap (str, optional): Name of the colormap to use for generating label colors. Defaults to "gist_rainbow".
654
+ color (str, List, Tuple, np.ndarray, or None, optional): Color to use for the labels. Can be a single color or an array
655
+ of colors. If None, the colormap will be used. Defaults to None.
656
+ blend_colors (bool, optional): Whether to blend colors for nodes with multiple domains. Defaults to False.
657
+ blend_gamma (float, optional): Gamma correction factor for perceptual color blending. Defaults to 2.2.
658
+ min_scale (float, optional): Minimum intensity scale for the colors generated by the colormap.
659
+ Controls the dimmest colors. Defaults to 0.8.
660
+ max_scale (float, optional): Maximum intensity scale for the colors generated by the colormap.
661
+ Controls the brightest colors. Defaults to 1.0.
662
+ scale_factor (float, optional): Exponent for adjusting color scaling based on enrichment scores.
663
+ A higher value increases contrast by dimming lower scores more. Defaults to 1.0.
664
+ random_seed (int, optional): Seed for random number generation to ensure reproducibility. Defaults to 888.
665
+
666
+ Returns:
667
+ np.ndarray: Array of RGBA colors for label annotations.
668
+ """
669
+ return get_annotated_domain_colors(
670
+ graph=self.graph,
671
+ cmap=cmap,
672
+ color=color,
673
+ blend_colors=blend_colors,
674
+ blend_gamma=blend_gamma,
675
+ min_scale=min_scale,
676
+ max_scale=max_scale,
677
+ scale_factor=scale_factor,
678
+ random_seed=random_seed,
679
+ )
680
+
681
+
682
+ def _combine_words(words: List[str], max_chars_per_line: int, max_label_lines: int) -> str:
683
+ """Combine words to fit within the max_chars_per_line and max_label_lines constraints,
684
+ and separate the final output by TERM_DELIMITER for plotting.
685
+
686
+ Args:
687
+ words (List[str]): List of words to combine.
688
+ max_chars_per_line (int): Maximum number of characters in a line to display.
689
+ max_label_lines (int): Maximum number of lines in a label.
690
+
691
+ Returns:
692
+ str: String of combined words separated by ':' for line breaks.
693
+ """
694
+
695
+ def try_combinations(words_batch: List[str]) -> List[str]:
696
+ """Try to combine words within a batch and return them with combined words separated by ':'."""
697
+ combined_lines = []
698
+ i = 0
699
+ while i < len(words_batch):
700
+ current_word = words_batch[i]
701
+ combined_word = current_word # Start with the current word
702
+ # Try to combine more words if possible, and ensure the combination fits within max_length
703
+ for j in range(i + 1, len(words_batch)):
704
+ next_word = words_batch[j]
705
+ # Ensure that the combined word fits within the max_chars_per_line limit
706
+ if len(combined_word) + len(next_word) + 1 <= max_chars_per_line: # +1 for space
707
+ combined_word = f"{combined_word} {next_word}"
708
+ i += 1 # Move past the combined word
709
+ else:
710
+ break # Stop combining if the length is exceeded
711
+
712
+ # Add the combined word only if it fits within the max_chars_per_line limit
713
+ if len(combined_word) <= max_chars_per_line:
714
+ combined_lines.append(combined_word) # Add the combined word
715
+ # Move to the next word
716
+ i += 1
717
+
718
+ # Stop if we've reached the max_label_lines limit
719
+ if len(combined_lines) >= max_label_lines:
720
+ break
721
+
722
+ return combined_lines
723
+
724
+ # Main logic: start with max_label_lines number of words
725
+ combined_lines = try_combinations(words[:max_label_lines])
726
+ remaining_words = words[max_label_lines:] # Remaining words after the initial batch
727
+ # Track words that have already been added
728
+ existing_words = set(" ".join(combined_lines).split())
729
+
730
+ # Continue pulling more words until we fill the lines
731
+ while remaining_words and len(combined_lines) < max_label_lines:
732
+ available_slots = max_label_lines - len(combined_lines)
733
+ words_to_add = [
734
+ word for word in remaining_words[:available_slots] if word not in existing_words
735
+ ]
736
+ remaining_words = remaining_words[available_slots:]
737
+ # Update the existing words set
738
+ existing_words.update(words_to_add)
739
+ # Add to combined_lines only unique words
740
+ combined_lines += try_combinations(words_to_add)
741
+
742
+ # Join the final combined lines with TERM_DELIMITER, a special separator for line breaks
743
+ return TERM_DELIMITER.join(combined_lines[:max_label_lines])
744
+
745
+
746
+ def _calculate_best_label_positions(
747
+ filtered_domain_centroids: Dict[str, Any], center: np.ndarray, radius: float, offset: float
748
+ ) -> Dict[str, Any]:
749
+ """Calculate and optimize label positions for clarity.
750
+
751
+ Args:
752
+ filtered_domain_centroids (Dict[str, Any]): Centroids of the filtered domains.
753
+ center (np.ndarray): The center coordinates for label positioning.
754
+ radius (float): The radius for positioning labels around the center.
755
+ offset (float): The offset distance from the radius for positioning labels.
756
+
757
+ Returns:
758
+ Dict[str, Any]: Optimized positions for labels.
759
+ """
760
+ num_domains = len(filtered_domain_centroids)
761
+ # Calculate equidistant positions around the center for initial label placement
762
+ equidistant_positions = _calculate_equidistant_positions_around_center(
763
+ center, radius, offset, num_domains
764
+ )
765
+ # Create a mapping of domains to their initial label positions
766
+ label_positions = {
767
+ domain: position
768
+ for domain, position in zip(filtered_domain_centroids.keys(), equidistant_positions)
769
+ }
770
+ # Optimize the label positions to minimize distance to domain centroids
771
+ return _optimize_label_positions(label_positions, filtered_domain_centroids)
772
+
773
+
774
+ def _calculate_equidistant_positions_around_center(
775
+ center: np.ndarray, radius: float, label_offset: float, num_domains: int
776
+ ) -> List[np.ndarray]:
777
+ """Calculate positions around a center at equidistant angles.
778
+
779
+ Args:
780
+ center (np.ndarray): The central point around which positions are calculated.
781
+ radius (float): The radius at which positions are calculated.
782
+ label_offset (float): The offset added to the radius for label positioning.
783
+ num_domains (int): The number of positions (or domains) to calculate.
784
+
785
+ Returns:
786
+ List[np.ndarray]: List of positions (as 2D numpy arrays) around the center.
787
+ """
788
+ # Calculate equidistant angles in radians around the center
789
+ angles = np.linspace(0, 2 * np.pi, num_domains, endpoint=False)
790
+ # Compute the positions around the center using the angles
791
+ return [
792
+ center + (radius + label_offset) * np.array([np.cos(angle), np.sin(angle)])
793
+ for angle in angles
794
+ ]
795
+
796
+
797
+ def _optimize_label_positions(
798
+ best_label_positions: Dict[str, Any], domain_centroids: Dict[str, Any]
799
+ ) -> Dict[str, Any]:
800
+ """Optimize label positions around the perimeter to minimize total distance to centroids.
801
+
802
+ Args:
803
+ best_label_positions (Dict[str, Any]): Initial positions of labels around the perimeter.
804
+ domain_centroids (Dict[str, Any]): Centroid positions of the domains.
805
+
806
+ Returns:
807
+ Dict[str, Any]: Optimized label positions.
808
+ """
809
+ while True:
810
+ improvement = False # Start each iteration assuming no improvement
811
+ # Iterate through each pair of labels to check for potential improvements
812
+ for i in range(len(domain_centroids)):
813
+ for j in range(i + 1, len(domain_centroids)):
814
+ # Calculate the current total distance
815
+ current_distance = _calculate_total_distance(best_label_positions, domain_centroids)
816
+ # Evaluate the total distance after swapping two labels
817
+ swapped_distance = _swap_and_evaluate(best_label_positions, i, j, domain_centroids)
818
+ # If the swap improves the total distance, perform the swap
819
+ if swapped_distance < current_distance:
820
+ labels = list(best_label_positions.keys())
821
+ best_label_positions[labels[i]], best_label_positions[labels[j]] = (
822
+ best_label_positions[labels[j]],
823
+ best_label_positions[labels[i]],
824
+ )
825
+ improvement = True # Found an improvement, so continue optimizing
826
+
827
+ if not improvement:
828
+ break # Exit the loop if no improvement was found in this iteration
829
+
830
+ return best_label_positions
831
+
832
+
833
+ def _calculate_total_distance(
834
+ label_positions: Dict[str, Any], domain_centroids: Dict[str, Any]
835
+ ) -> float:
836
+ """Calculate the total distance from label positions to their domain centroids.
837
+
838
+ Args:
839
+ label_positions (Dict[str, Any]): Positions of labels around the perimeter.
840
+ domain_centroids (Dict[str, Any]): Centroid positions of the domains.
841
+
842
+ Returns:
843
+ float: The total distance from labels to centroids.
844
+ """
845
+ total_distance = 0
846
+ # Iterate through each domain and calculate the distance to its centroid
847
+ for domain, pos in label_positions.items():
848
+ centroid = domain_centroids[domain]
849
+ total_distance += np.linalg.norm(centroid - pos)
850
+
851
+ return total_distance
852
+
853
+
854
+ def _swap_and_evaluate(
855
+ label_positions: Dict[str, Any],
856
+ i: int,
857
+ j: int,
858
+ domain_centroids: Dict[str, Any],
859
+ ) -> float:
860
+ """Swap two labels and evaluate the total distance after the swap.
861
+
862
+ Args:
863
+ label_positions (Dict[str, Any]): Positions of labels around the perimeter.
864
+ i (int): Index of the first label to swap.
865
+ j (int): Index of the second label to swap.
866
+ domain_centroids (Dict[str, Any]): Centroid positions of the domains.
867
+
868
+ Returns:
869
+ float: The total distance after swapping the two labels.
870
+ """
871
+ # Get the list of labels from the dictionary keys
872
+ labels = list(label_positions.keys())
873
+ swapped_positions = copy.deepcopy(label_positions)
874
+ # Swap the positions of the two specified labels
875
+ swapped_positions[labels[i]], swapped_positions[labels[j]] = (
876
+ swapped_positions[labels[j]],
877
+ swapped_positions[labels[i]],
878
+ )
879
+ # Calculate and return the total distance after the swap
880
+ return _calculate_total_distance(swapped_positions, domain_centroids)
881
+
882
+
883
+ def _apply_str_transformation(
884
+ words: List[str], transformation: Union[str, Dict[str, str]]
885
+ ) -> List[str]:
886
+ """Apply a user-specified case transformation to each word in the list without appending duplicates.
887
+
888
+ Args:
889
+ words (List[str]): A list of words to transform.
890
+ transformation (Union[str, Dict[str, str]]): A single transformation (e.g., 'lower', 'upper', 'title', 'capitalize')
891
+ or a dictionary mapping cases ('lower', 'upper', 'title') to transformations (e.g., 'lower'='upper').
892
+
893
+ Returns:
894
+ List[str]: A list of transformed words with no duplicates.
895
+ """
896
+ # Initialize a list to store transformed words
897
+ transformed_words = []
898
+ for word in words:
899
+ # Split word into subwords by space
900
+ subwords = word.split(" ")
901
+ transformed_subwords = []
902
+ # Apply transformation to each subword
903
+ for subword in subwords:
904
+ transformed_subword = subword # Start with the original subword
905
+ # If transformation is a string, apply it to all subwords
906
+ if isinstance(transformation, str):
907
+ if hasattr(subword, transformation):
908
+ transformed_subword = getattr(subword, transformation)()
909
+
910
+ # If transformation is a dictionary, apply case-specific transformations
911
+ elif isinstance(transformation, dict):
912
+ for case_type, transform in transformation.items():
913
+ if case_type == "lower" and subword.islower() and transform:
914
+ transformed_subword = getattr(subword, transform)()
915
+ elif case_type == "upper" and subword.isupper() and transform:
916
+ transformed_subword = getattr(subword, transform)()
917
+ elif case_type == "title" and subword.istitle() and transform:
918
+ transformed_subword = getattr(subword, transform)()
919
+
920
+ # Append the transformed subword to the list
921
+ transformed_subwords.append(transformed_subword)
922
+
923
+ # Rejoin the transformed subwords into a single string to preserve structure
924
+ transformed_word = " ".join(transformed_subwords)
925
+ # Only append if the transformed word is not already in the list
926
+ if transformed_word not in transformed_words:
927
+ transformed_words.append(transformed_word)
928
+
929
+ return transformed_words