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