1
|
|
|
"""Utilities with networkx.""" |
2
|
|
|
from typing import Any, Callable, Iterable, List, Tuple |
3
|
|
|
|
4
|
|
|
from networkx import Graph, all_simple_paths |
5
|
|
|
from networkx.utils import pairwise |
6
|
|
|
|
7
|
|
|
__all__ = [ |
8
|
|
|
"get_first_item", |
9
|
|
|
"get_second_item", |
10
|
|
|
"get_two_first_items", |
11
|
|
|
"filter_by_degree", |
12
|
|
|
"get_attributs", |
13
|
|
|
'search_root_nodes', |
14
|
|
|
'search_leaf_nodes', |
15
|
|
|
'search_simple_path', |
16
|
|
|
] |
17
|
|
|
|
18
|
|
|
|
19
|
|
|
def get_first_item(t: Tuple) -> Any: |
20
|
|
|
"""Returns first item of tuple.""" |
21
|
|
|
return t[0] |
22
|
|
|
|
23
|
|
|
|
24
|
|
|
def get_second_item(t: Tuple) -> Any: # pragma: no cover |
25
|
|
|
"""Returns second item of tuple.""" |
26
|
|
|
return t[1] |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
def get_two_first_items(t: Tuple) -> Tuple: |
30
|
|
|
"""Return (first, second) item of tuple as tuple.""" |
31
|
|
|
return (t[0], t[1]) |
32
|
|
|
|
33
|
|
|
|
34
|
|
|
def filter_by_degree(degree: int) -> Callable[[Any], bool]: # pragma: no cover |
35
|
|
|
"""Generate a filter for specified degree.""" |
36
|
|
|
|
37
|
|
|
def _filter(node: Any) -> bool: |
38
|
|
|
(id, d) = node |
39
|
|
|
return d == degree |
40
|
|
|
|
41
|
|
|
return _filter |
42
|
|
|
|
43
|
|
|
|
44
|
|
|
def get_attributs(*names: str) -> Callable[[Tuple], List]: # pragma: no cover |
45
|
|
|
"""Returns attributs list for specified node or edge.""" |
46
|
|
|
|
47
|
|
|
def _map(t: Tuple) -> List: |
48
|
|
|
(v, d) = t |
49
|
|
|
return [d[name] for name in names] |
50
|
|
|
|
51
|
|
|
return _map |
52
|
|
|
|
53
|
|
|
|
54
|
|
|
def search_root_nodes(graph: Graph) -> Iterable[Any]: # pragma: no cover |
55
|
|
|
"""Search nodes with no 'in' edges. |
56
|
|
|
|
57
|
|
|
Arguments: |
58
|
|
|
graph (Graph): networkx graph instance |
59
|
|
|
|
60
|
|
|
Returns: |
61
|
|
|
(Iterable[Any]): results as an iterable of node identifier. |
62
|
|
|
|
63
|
|
|
""" |
64
|
|
|
return map(get_first_item, filter(filter_by_degree(0), graph.in_degree())) |
65
|
|
|
|
66
|
|
|
|
67
|
|
|
def search_leaf_nodes(graph: Graph) -> Iterable[Any]: # pragma: no cover |
68
|
|
|
"""Search nodes with no 'out' edges. |
69
|
|
|
|
70
|
|
|
Arguments: |
71
|
|
|
graph (Graph): networkx graph instance |
72
|
|
|
|
73
|
|
|
Returns: |
74
|
|
|
(Iterable[Any]): results as an iterable of node identifier. |
75
|
|
|
|
76
|
|
|
""" |
77
|
|
|
return map(get_first_item, filter(filter_by_degree(0), graph.out_degree())) |
78
|
|
|
|
79
|
|
|
|
80
|
|
|
def search_simple_path(graph: Graph, source: Any, target: Any, cutoff=None): # pragma: no cover |
81
|
|
|
"""Returns a list of edges.""" |
82
|
|
|
return map(pairwise, all_simple_paths(graph, source=target, target=target, cutoff=cutoff)) |
83
|
|
|
|