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