-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuild_graph.py
85 lines (69 loc) · 2.14 KB
/
build_graph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @author : Manuel Castro Avila <[email protected]>
# @file : build_graph.py
# @created : 28-Jul-2022
# @company : Home
#
"""
Build Graph with connections across items.
"""
import networkx as nx
from networkx.drawing.nx_agraph import write_dot, graphviz_layout
import importlib
import functions
importlib.reload(functions)
from functions import *
dg = nx.DiGraph()
for item in list_items:
for single_component in item.components.keys():
dg.add_edge(
single_component.name,
item.name,
n_components=item.components[single_component],
)
def get_ancestor_nodes_and_position(final_node):
'''
Build sub-graph with ancestors of `final_node`.
Parameters:
final_node: str, item's name.
'''
sub_graph = nx.DiGraph()
ancestors = nx.ancestors(dg, final_node)
ancestors.add(final_node)
for node in ancestors:
for edge in dg.in_edges(node):
sub_graph.add_edge(edge[0], edge[1])
# Position layout
position = graphviz_layout(sub_graph, prog='dot')
return sub_graph, position
def get_descendant_nodes_and_position(initial_node):
'''
Build sub-graph with descendants of `initial_node`.
Parameters:
initial_node: str, item's name.
'''
sub_graph = nx.DiGraph()
descendants = nx.descendants(dg, initial_node)
descendants.add(initial_node)
for node in descendants:
for edge in dg.out_edges(node):
sub_graph.add_edge(edge[0], edge[1])
# Position layout
position = graphviz_layout(sub_graph, prog='dot')
return sub_graph, position
def get_quantity(source, target):
'''
Return quantity needed of `source` to create `target.
Parameters:
source: str, item's name.
target: str, item's name.
'''
item_target = get_object(target)
if item_target.n_components > 0:
for item in item_target.components.keys():
if item.name == source:
quantity = item_target.components[item]
return quantity
else:
return None