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
risk/network/io.py DELETED
@@ -1,550 +0,0 @@
1
- """
2
- risk/network/io
3
- ~~~~~~~~~~~~~~~
4
- """
5
-
6
- import copy
7
- import json
8
- import os
9
- import pickle
10
- import shutil
11
- import zipfile
12
- from xml.dom import minidom
13
-
14
- import networkx as nx
15
- import numpy as np
16
- import pandas as pd
17
-
18
- from risk.network.geometry import assign_edge_lengths
19
- from risk.log import params, logger, log_header
20
-
21
-
22
- class NetworkIO:
23
- """A class for loading, processing, and managing network data.
24
-
25
- The NetworkIO class provides methods to load network data from various formats (e.g., GPickle, NetworkX)
26
- and process the network by adjusting node coordinates, calculating edge lengths, and validating graph structure.
27
- """
28
-
29
- def __init__(
30
- self,
31
- compute_sphere: bool = True,
32
- surface_depth: float = 0.0,
33
- min_edges_per_node: int = 0,
34
- ):
35
- """Initialize the NetworkIO class.
36
-
37
- Args:
38
- compute_sphere (bool, optional): Whether to map nodes to a sphere. Defaults to True.
39
- surface_depth (float, optional): Surface depth for the sphere. Defaults to 0.0.
40
- min_edges_per_node (int, optional): Minimum number of edges per node. Defaults to 0.
41
- """
42
- self.compute_sphere = compute_sphere
43
- self.surface_depth = surface_depth
44
- self.min_edges_per_node = min_edges_per_node
45
- # Log the initialization of the NetworkIO class
46
- params.log_network(
47
- compute_sphere=compute_sphere,
48
- surface_depth=surface_depth,
49
- min_edges_per_node=min_edges_per_node,
50
- )
51
-
52
- @staticmethod
53
- def load_gpickle_network(
54
- filepath: str,
55
- compute_sphere: bool = True,
56
- surface_depth: float = 0.0,
57
- min_edges_per_node: int = 0,
58
- ) -> nx.Graph:
59
- """Load a network from a GPickle file.
60
-
61
- Args:
62
- filepath (str): Path to the GPickle file.
63
- compute_sphere (bool, optional): Whether to map nodes to a sphere. Defaults to True.
64
- surface_depth (float, optional): Surface depth for the sphere. Defaults to 0.0.
65
- min_edges_per_node (int, optional): Minimum number of edges per node. Defaults to 0.
66
-
67
- Returns:
68
- nx.Graph: Loaded and processed network.
69
- """
70
- networkio = NetworkIO(
71
- compute_sphere=compute_sphere,
72
- surface_depth=surface_depth,
73
- min_edges_per_node=min_edges_per_node,
74
- )
75
- return networkio._load_gpickle_network(filepath=filepath)
76
-
77
- def _load_gpickle_network(self, filepath: str) -> nx.Graph:
78
- """Private method to load a network from a GPickle file.
79
-
80
- Args:
81
- filepath (str): Path to the GPickle file.
82
-
83
- Returns:
84
- nx.Graph: Loaded and processed network.
85
- """
86
- filetype = "GPickle"
87
- # Log the loading of the GPickle file
88
- params.log_network(filetype=filetype, filepath=filepath)
89
- self._log_loading(filetype, filepath=filepath)
90
-
91
- with open(filepath, "rb") as f:
92
- G = pickle.load(f)
93
-
94
- # Initialize the graph
95
- return self._initialize_graph(G)
96
-
97
- @staticmethod
98
- def load_networkx_network(
99
- network: nx.Graph,
100
- compute_sphere: bool = True,
101
- surface_depth: float = 0.0,
102
- min_edges_per_node: int = 0,
103
- ) -> nx.Graph:
104
- """Load a NetworkX graph.
105
-
106
- Args:
107
- network (nx.Graph): A NetworkX graph object.
108
- compute_sphere (bool, optional): Whether to map nodes to a sphere. Defaults to True.
109
- surface_depth (float, optional): Surface depth for the sphere. Defaults to 0.0.
110
- min_edges_per_node (int, optional): Minimum number of edges per node. Defaults to 0.
111
-
112
- Returns:
113
- nx.Graph: Loaded and processed network.
114
- """
115
- networkio = NetworkIO(
116
- compute_sphere=compute_sphere,
117
- surface_depth=surface_depth,
118
- min_edges_per_node=min_edges_per_node,
119
- )
120
- return networkio._load_networkx_network(network=network)
121
-
122
- def _load_networkx_network(self, network: nx.Graph) -> nx.Graph:
123
- """Private method to load a NetworkX graph.
124
-
125
- Args:
126
- network (nx.Graph): A NetworkX graph object.
127
-
128
- Returns:
129
- nx.Graph: Processed network.
130
- """
131
- filetype = "NetworkX"
132
- # Log the loading of the NetworkX graph
133
- params.log_network(filetype=filetype)
134
- self._log_loading(filetype)
135
-
136
- # Important: Make a copy of the network to avoid modifying the original
137
- network_copy = copy.deepcopy(network)
138
- # Initialize the graph
139
- return self._initialize_graph(network_copy)
140
-
141
- @staticmethod
142
- def load_cytoscape_network(
143
- filepath: str,
144
- source_label: str = "source",
145
- target_label: str = "target",
146
- view_name: str = "",
147
- compute_sphere: bool = True,
148
- surface_depth: float = 0.0,
149
- min_edges_per_node: int = 0,
150
- ) -> nx.Graph:
151
- """Load a network from a Cytoscape file.
152
-
153
- Args:
154
- filepath (str): Path to the Cytoscape file.
155
- source_label (str, optional): Source node label. Defaults to "source".
156
- target_label (str, optional): Target node label. Defaults to "target".
157
- view_name (str, optional): Specific view name to load. Defaults to "".
158
- compute_sphere (bool, optional): Whether to map nodes to a sphere. Defaults to True.
159
- surface_depth (float, optional): Surface depth for the sphere. Defaults to 0.0.
160
- min_edges_per_node (int, optional): Minimum number of edges per node. Defaults to 0.
161
-
162
- Returns:
163
- nx.Graph: Loaded and processed network.
164
- """
165
- networkio = NetworkIO(
166
- compute_sphere=compute_sphere,
167
- surface_depth=surface_depth,
168
- min_edges_per_node=min_edges_per_node,
169
- )
170
- return networkio._load_cytoscape_network(
171
- filepath=filepath,
172
- source_label=source_label,
173
- target_label=target_label,
174
- view_name=view_name,
175
- )
176
-
177
- def _load_cytoscape_network(
178
- self,
179
- filepath: str,
180
- source_label: str = "source",
181
- target_label: str = "target",
182
- view_name: str = "",
183
- ) -> nx.Graph:
184
- """Private method to load a network from a Cytoscape file.
185
-
186
- Args:
187
- filepath (str): Path to the Cytoscape file.
188
- source_label (str, optional): Source node label. Defaults to "source".
189
- target_label (str, optional): Target node label. Defaults to "target".
190
- view_name (str, optional): Specific view name to load. Defaults to "".
191
-
192
- Returns:
193
- nx.Graph: Loaded and processed network.
194
-
195
- Raises:
196
- ValueError: If no matching attribute metadata file is found.
197
- """
198
- filetype = "Cytoscape"
199
- # Log the loading of the Cytoscape file
200
- params.log_network(filetype=filetype, filepath=str(filepath))
201
- self._log_loading(filetype, filepath=filepath)
202
-
203
- cys_files = []
204
- tmp_dir = ".tmp_cytoscape"
205
- # Try / finally to remove unzipped files
206
- try:
207
- # Create the temporary directory if it doesn't exist
208
- if not os.path.exists(tmp_dir):
209
- os.makedirs(tmp_dir)
210
-
211
- # Unzip CYS file into the temporary directory
212
- with zipfile.ZipFile(filepath, "r") as zip_ref:
213
- cys_files = zip_ref.namelist()
214
- zip_ref.extractall(tmp_dir)
215
-
216
- # Get first view and network instances
217
- cys_view_files = [os.path.join(tmp_dir, cf) for cf in cys_files if "/views/" in cf]
218
- cys_view_file = (
219
- cys_view_files[0]
220
- if not view_name
221
- else [cvf for cvf in cys_view_files if cvf.endswith(view_name + ".xgmml")][0]
222
- )
223
- # Parse nodes
224
- cys_view_dom = minidom.parse(cys_view_file)
225
- cys_nodes = cys_view_dom.getElementsByTagName("node")
226
- node_x_positions = {}
227
- node_y_positions = {}
228
- for node in cys_nodes:
229
- # Node ID is found in 'label'
230
- node_id = str(node.attributes["label"].value)
231
- for child in node.childNodes:
232
- if child.nodeType == 1 and child.tagName == "graphics":
233
- node_x_positions[node_id] = float(child.attributes["x"].value)
234
- node_y_positions[node_id] = float(child.attributes["y"].value)
235
-
236
- # Read the node attributes (from /tables/)
237
- attribute_metadata_keywords = ["/tables/", "SHARED_ATTRS", "edge.cytable"]
238
- # Use a generator to find the first matching file
239
- attribute_metadata = next(
240
- (
241
- os.path.join(tmp_dir, cf)
242
- for cf in cys_files
243
- if all(keyword in cf for keyword in attribute_metadata_keywords)
244
- ),
245
- None, # Default if no file matches
246
- )
247
- if attribute_metadata:
248
- # Optimize `read_csv` by leveraging proper options
249
- attribute_table = pd.read_csv(
250
- attribute_metadata,
251
- sep=",",
252
- header=None,
253
- skiprows=1,
254
- dtype=str, # Use specific dtypes to reduce memory usage
255
- engine="c", # Use the C engine for parsing if compatible
256
- low_memory=False, # Optimize memory handling for large files
257
- )
258
- else:
259
- raise ValueError("No matching attribute metadata file found.")
260
-
261
- # Set columns
262
- attribute_table.columns = attribute_table.iloc[0]
263
- # Skip first four rows, select source and target columns, and reset index
264
- attribute_table = attribute_table.iloc[4:, :]
265
- try:
266
- # Attempt to filter the attribute_table with the given labels
267
- attribute_table = attribute_table[[source_label, target_label]]
268
- except KeyError as e:
269
- # Find which key(s) caused the issue
270
- missing_keys = [
271
- key
272
- for key in [source_label, target_label]
273
- if key not in attribute_table.columns
274
- ]
275
- # Raise the KeyError with details about the issue and available options
276
- available_columns = ", ".join(attribute_table.columns)
277
- raise KeyError(
278
- f"The column(s) '{', '.join(missing_keys)}' do not exist in the table. "
279
- f"Available columns are: {available_columns}."
280
- ) from e
281
-
282
- attribute_table = attribute_table.dropna().reset_index(drop=True)
283
-
284
- # Create a graph
285
- G = nx.Graph()
286
- # Add edges and nodes
287
- for _, row in attribute_table.iterrows():
288
- source = row[source_label]
289
- target = row[target_label]
290
- G.add_edge(source, target)
291
- if source not in G:
292
- G.add_node(source) # Optionally add x, y coordinates here if available
293
- if target not in G:
294
- G.add_node(target) # Optionally add x, y coordinates here if available
295
-
296
- # Add node attributes
297
- for node in G.nodes():
298
- G.nodes[node]["label"] = node
299
- G.nodes[node]["x"] = node_x_positions[node]
300
- G.nodes[node]["y"] = node_y_positions[node]
301
-
302
- # Initialize the graph
303
- return self._initialize_graph(G)
304
-
305
- finally:
306
- # Remove the temporary directory and its contents
307
- if os.path.exists(tmp_dir):
308
- shutil.rmtree(tmp_dir)
309
-
310
- @staticmethod
311
- def load_cytoscape_json_network(
312
- filepath: str,
313
- source_label: str = "source",
314
- target_label: str = "target",
315
- compute_sphere: bool = True,
316
- surface_depth: float = 0.0,
317
- min_edges_per_node: int = 0,
318
- ) -> nx.Graph:
319
- """Load a network from a Cytoscape JSON (.cyjs) file.
320
-
321
- Args:
322
- filepath (str): Path to the Cytoscape JSON file.
323
- source_label (str, optional): Source node label. Default is "source".
324
- target_label (str, optional): Target node label. Default is "target".
325
- compute_sphere (bool, optional): Whether to map nodes to a sphere. Defaults to True.
326
- surface_depth (float, optional): Surface depth for the sphere. Defaults to 0.0.
327
- min_edges_per_node (int, optional): Minimum number of edges per node. Defaults to 0.
328
-
329
- Returns:
330
- NetworkX graph: Loaded and processed network.
331
- """
332
- networkio = NetworkIO(
333
- compute_sphere=compute_sphere,
334
- surface_depth=surface_depth,
335
- min_edges_per_node=min_edges_per_node,
336
- )
337
- return networkio._load_cytoscape_json_network(
338
- filepath=filepath,
339
- source_label=source_label,
340
- target_label=target_label,
341
- )
342
-
343
- def _load_cytoscape_json_network(self, filepath, source_label="source", target_label="target"):
344
- """Private method to load a network from a Cytoscape JSON (.cyjs) file.
345
-
346
- Args:
347
- filepath (str): Path to the Cytoscape JSON file.
348
- source_label (str, optional): Source node label. Default is "source".
349
- target_label (str, optional): Target node label. Default is "target".
350
-
351
- Returns:
352
- NetworkX graph: Loaded and processed network.
353
- """
354
- filetype = "Cytoscape JSON"
355
- # Log the loading of the Cytoscape JSON file
356
- params.log_network(filetype=filetype, filepath=str(filepath))
357
- self._log_loading(filetype, filepath=filepath)
358
-
359
- # Load the Cytoscape JSON file
360
- with open(filepath, "r") as f:
361
- cyjs_data = json.load(f)
362
-
363
- # Create a graph
364
- G = nx.Graph()
365
- # Store node positions for later use
366
- node_x_positions = {}
367
- node_y_positions = {}
368
- for node in cyjs_data["elements"]["nodes"]:
369
- node_data = node["data"]
370
- # Use the original node ID if available, otherwise use the default ID
371
- node_id = node_data.get("id_original", node_data.get("id"))
372
- node_x_positions[node_id] = node["position"]["x"]
373
- node_y_positions[node_id] = node["position"]["y"]
374
-
375
- # Process edges and add them to the graph
376
- for edge in cyjs_data["elements"]["edges"]:
377
- edge_data = edge["data"]
378
- # Use the original source and target labels if available, otherwise fall back to default labels
379
- source = edge_data.get(f"{source_label}_original", edge_data.get(source_label))
380
- target = edge_data.get(f"{target_label}_original", edge_data.get(target_label))
381
- G.add_edge(source, target)
382
-
383
- # Ensure nodes exist in the graph and add them if not present
384
- if source not in G:
385
- G.add_node(source)
386
- if target not in G:
387
- G.add_node(target)
388
-
389
- # Add node attributes (like label, x, y positions)
390
- for node in G.nodes():
391
- G.nodes[node]["label"] = node
392
- G.nodes[node]["x"] = node_x_positions.get(node, 0) # Use stored positions
393
- G.nodes[node]["y"] = node_y_positions.get(node, 0) # Use stored positions
394
-
395
- # Initialize the graph
396
- return self._initialize_graph(G)
397
-
398
- def _initialize_graph(self, G: nx.Graph) -> nx.Graph:
399
- """Initialize the graph by processing and validating its nodes and edges.
400
-
401
- Args:
402
- G (nx.Graph): The input NetworkX graph.
403
-
404
- Returns:
405
- nx.Graph: The processed and validated graph.
406
- """
407
- self._validate_nodes(G)
408
- self._assign_edge_weights(G)
409
- self._assign_edge_lengths(G)
410
- self._remove_invalid_graph_properties(G)
411
- # IMPORTANT: This is where the graph node labels are converted to integers
412
- # Make sure to perform this step after all other processing
413
- G = nx.convert_node_labels_to_integers(G)
414
- return G
415
-
416
- def _remove_invalid_graph_properties(self, G: nx.Graph) -> None:
417
- """Remove invalid properties from the graph, including self-loops, nodes with fewer edges than
418
- the threshold, and isolated nodes.
419
-
420
- Args:
421
- G (nx.Graph): A NetworkX graph object.
422
- """
423
- # Count the number of nodes and edges before cleaning
424
- num_initial_nodes = G.number_of_nodes()
425
- num_initial_edges = G.number_of_edges()
426
- # Remove self-loops to ensure correct edge count
427
- G.remove_edges_from(nx.selfloop_edges(G))
428
- # Iteratively remove nodes with fewer edges than the threshold
429
- while True:
430
- nodes_to_remove = [
431
- node
432
- for node, degree in dict(G.degree()).items()
433
- if degree < self.min_edges_per_node
434
- ]
435
- if not nodes_to_remove:
436
- break # Exit loop if no nodes meet the condition
437
- G.remove_nodes_from(nodes_to_remove)
438
-
439
- # Remove isolated nodes
440
- G.remove_nodes_from(nx.isolates(G))
441
-
442
- # Log the number of nodes and edges before and after cleaning
443
- num_final_nodes = G.number_of_nodes()
444
- num_final_edges = G.number_of_edges()
445
- logger.debug(f"Initial node count: {num_initial_nodes}")
446
- logger.debug(f"Final node count: {num_final_nodes}")
447
- logger.debug(f"Initial edge count: {num_initial_edges}")
448
- logger.debug(f"Final edge count: {num_final_edges}")
449
-
450
- def _assign_edge_weights(self, G: nx.Graph) -> None:
451
- """Assign default edge weights to the graph.
452
-
453
- Args:
454
- G (nx.Graph): A NetworkX graph object.
455
- """
456
- # Set default weight for all edges in bulk
457
- default_weight = 1
458
- nx.set_edge_attributes(G, default_weight, "weight")
459
-
460
- def _validate_nodes(self, G: nx.Graph) -> None:
461
- """Validate the graph structure and attributes with attribute fallback for positions and labels.
462
-
463
- Args:
464
- G (nx.Graph): A NetworkX graph object.
465
-
466
- Raises:
467
- ValueError: If a node is missing 'x', 'y', and a valid 'pos' attribute.
468
- """
469
- # Retrieve all relevant attributes in bulk
470
- pos_attrs = nx.get_node_attributes(G, "pos")
471
- name_attrs = nx.get_node_attributes(G, "name")
472
- id_attrs = nx.get_node_attributes(G, "id")
473
- # Dictionaries to hold missing or fallback attributes
474
- x_attrs = {}
475
- y_attrs = {}
476
- label_attrs = {}
477
- nodes_with_missing_labels = []
478
-
479
- # Iterate through nodes to validate and assign missing attributes
480
- for node in G.nodes:
481
- attrs = G.nodes[node]
482
- # Validate and assign 'x' and 'y' attributes
483
- if "x" not in attrs or "y" not in attrs:
484
- if (
485
- node in pos_attrs
486
- and isinstance(pos_attrs[node], (list, tuple, np.ndarray))
487
- and len(pos_attrs[node]) >= 2
488
- ):
489
- x_attrs[node], y_attrs[node] = pos_attrs[node][:2]
490
- else:
491
- raise ValueError(
492
- f"Node {node} is missing 'x', 'y', and a valid 'pos' attribute."
493
- )
494
-
495
- # Validate and assign 'label' attribute
496
- if "label" not in attrs:
497
- if node in name_attrs:
498
- label_attrs[node] = name_attrs[node]
499
- elif node in id_attrs:
500
- label_attrs[node] = id_attrs[node]
501
- else:
502
- # Assign node ID as label and log the missing label
503
- label_attrs[node] = str(node)
504
- nodes_with_missing_labels.append(node)
505
-
506
- # Batch update attributes in the graph
507
- nx.set_node_attributes(G, x_attrs, "x")
508
- nx.set_node_attributes(G, y_attrs, "y")
509
- nx.set_node_attributes(G, label_attrs, "label")
510
-
511
- # Log a warning if any labels were missing
512
- if nodes_with_missing_labels:
513
- total_nodes = G.number_of_nodes()
514
- fraction_missing_labels = len(nodes_with_missing_labels) / total_nodes
515
- logger.warning(
516
- f"{len(nodes_with_missing_labels)} out of {total_nodes} nodes "
517
- f"({fraction_missing_labels:.2%}) were missing 'label' attributes and were assigned node IDs."
518
- )
519
-
520
- def _assign_edge_lengths(self, G: nx.Graph) -> None:
521
- """Prepare the network by adjusting surface depth and calculating edge lengths.
522
-
523
- Args:
524
- G (nx.Graph): The input network graph.
525
- """
526
- assign_edge_lengths(
527
- G,
528
- compute_sphere=self.compute_sphere,
529
- surface_depth=self.surface_depth,
530
- )
531
-
532
- def _log_loading(
533
- self,
534
- filetype: str,
535
- filepath: str = "",
536
- ) -> None:
537
- """Log the initialization details of the RISK class.
538
-
539
- Args:
540
- filetype (str): The type of the file being loaded (e.g., 'CSV', 'JSON').
541
- filepath (str, optional): The path to the file being loaded. Defaults to "".
542
- """
543
- log_header("Loading network")
544
- logger.debug(f"Filetype: {filetype}")
545
- if filepath:
546
- logger.debug(f"Filepath: {filepath}")
547
- logger.debug(f"Minimum edges per node: {self.min_edges_per_node}")
548
- logger.debug(f"Projection: {'Sphere' if self.compute_sphere else 'Plane'}")
549
- if self.compute_sphere:
550
- logger.debug(f"Surface depth: {self.surface_depth}")
@@ -1,6 +0,0 @@
1
- """
2
- risk/network/plotter
3
- ~~~~~~~~~~~~~~~~~~~~
4
- """
5
-
6
- from risk.network.plotter.api import PlotterAPI
@@ -1,54 +0,0 @@
1
- """
2
- risk/network/plotter/api
3
- ~~~~~~~~~~~~~~~~~~~~~~~~
4
- """
5
-
6
- from typing import List, Tuple, Union
7
-
8
- import numpy as np
9
-
10
- from risk.log import log_header
11
- from risk.network.graph.graph import Graph
12
- from risk.network.plotter.plotter import Plotter
13
-
14
-
15
- class PlotterAPI:
16
- """Handles the loading of network plotter objects.
17
-
18
- The PlotterAPI class provides methods to load and configure Plotter objects for plotting network graphs.
19
- """
20
-
21
- def __init__() -> None:
22
- pass
23
-
24
- def load_plotter(
25
- self,
26
- graph: Graph,
27
- figsize: Union[List, Tuple, np.ndarray] = (10, 10),
28
- background_color: str = "white",
29
- background_alpha: Union[float, None] = 1.0,
30
- pad: float = 0.3,
31
- ) -> Plotter:
32
- """Get a Plotter object for plotting.
33
-
34
- Args:
35
- graph (Graph): The graph to plot.
36
- figsize (List, Tuple, or np.ndarray, optional): Size of the plot. Defaults to (10, 10)., optional): Size of the figure. Defaults to (10, 10).
37
- background_color (str, optional): Background color of the plot. Defaults to "white".
38
- background_alpha (float, None, optional): Transparency level of the background color. If provided, it overrides
39
- any existing alpha values found in background_color. Defaults to 1.0.
40
- pad (float, optional): Padding value to adjust the axis limits. Defaults to 0.3.
41
-
42
- Returns:
43
- Plotter: A Plotter object configured with the given parameters.
44
- """
45
- log_header("Loading plotter")
46
-
47
- # Initialize and return a Plotter object
48
- return Plotter(
49
- graph,
50
- figsize=figsize,
51
- background_color=background_color,
52
- background_alpha=background_alpha,
53
- pad=pad,
54
- )