def node_graph(node):
"""Create a graph representing a node."""
graph = graphviz.Graph()
counter = itertools.count(1)
graph.node('0', label=str(node.f.__name__))
frontier = [('0', child) for child in node.children]
while frontier:
parent, node = frontier.pop()
node_num = str(next(counter))
graph.node(node_num, label=str(node.f.__name__))
graph.edge(parent, node_num)
frontier.extend((node_num, child) for child in node.children)
return graph
python类Graph()的实例源码
def main(engine, undirected, format, name, dot, file, edges, no_vertex_labels):
if undirected:
graph = graphviz.Graph(engine=engine, format=format)
else:
graph = graphviz.Digraph(engine=engine, format=format)
if name:
graph.body.append(r'label = "{0}"'.format(name))
edges = seq(edges).map(split_edge)
if no_vertex_labels:
edges.map(lambda e: (e.left, e.right)).flatten().distinct()\
.filter_not(lambda n: n is None).for_each(lambda n: graph.node(n, label=''))
else:
edges.map(lambda e: (e.left, e.right)).flatten().distinct() \
.filter_not(lambda n: n is None).for_each(lambda n: graph.node(n))
edges.filter(lambda e: e.right is not None) \
.for_each(lambda e: graph.edge(e.left, e.right, label=e.label))
filepath, filename = path.split(file)
filepath = filepath if filepath != '' else None
graph.render(filename=filename, directory=filepath, cleanup=not dot)
def export_to_dot(host_groups, data_center_prefix='dc-'):
dc_colors = _colors('white', '#238b45')
host_colors = _colors('black', '#66c2a4')
role_colors = _colors('black', '#b2e2e2')
graph = graphviz.Graph()
graph.attr('graph', overlap='false', layout='neato', comment=ANSIBLE_INVENTORY_TAG)
for fqdn, labels in host_groups.items():
host = fqdn.split('.')[0]
graph.node(host, **host_colors)
for label in labels:
if label.startswith(data_center_prefix):
graph.node(label, **dc_colors)
graph.edge(label, host, **dc_colors)
else:
graph.node(label, **role_colors)
graph.edge(host, label, **role_colors)
return graph
def bipartite_as_graph(self) -> Graph: # pragma: no cover
"""Returns a :class:`graphviz.Graph` representation of this bipartite graph."""
if Graph is None:
raise ImportError('The graphviz package is required to draw the graph.')
graph = Graph()
nodes_left = {} # type: Dict[TLeft, str]
nodes_right = {} # type: Dict[TRight, str]
node_id = 0
for (left, right), value in self.bipartite._edges.items():
if left not in nodes_left:
name = 'node{:d}'.format(node_id)
nodes_left[left] = name
label = str(self.subjects_by_id[left])
graph.node(name, label=label)
node_id += 1
if right not in nodes_right:
name = 'node{:d}'.format(node_id)
nodes_right[right] = name
label = str(self.automaton.patterns[right][0])
graph.node(name, label=label)
node_id += 1
edge_label = value is not True and str(value) or ''
graph.edge(nodes_left[left], nodes_right[right], edge_label)
return graph
def as_graph(self) -> Graph: # pragma: no cover
"""Returns a :class:`graphviz.Graph` representation of this bipartite graph."""
if Graph is None:
raise ImportError('The graphviz package is required to draw the graph.')
graph = Graph()
nodes_left = {} # type: Dict[TLeft, str]
nodes_right = {} # type: Dict[TRight, str]
node_id = 0
for (left, right), value in self._edges.items():
if left not in nodes_left:
name = 'node{:d}'.format(node_id)
nodes_left[left] = name
graph.node(name, label=str(left))
node_id += 1
if right not in nodes_right:
name = 'node{:d}'.format(node_id)
nodes_right[right] = name
graph.node(name, label=str(right))
node_id += 1
edge_label = value is not True and str(value) or ''
graph.edge(nodes_left[left], nodes_right[right], edge_label)
return graph
def draw_SCION_topology(topology_dict, n_labels, e_labels):
"""
Draws the Scion topology from a topology dictionary
returned by parse_gen_folder.
:param dictionary topology_dict: dictionary returned by parse_gen_folder,
boolean ip_addresses: indicates if node labels are drawn,
boolean edge_labels: indicates if edge labels are drawn
:return Dot graph: graph of the SCION topology
"""
isd_graphs = {}
dot = Graph(name='topology',filename='topology.gv',comment='SCION-net')
ISDs = topology_dict["ISD"]
# draw each ISD graph
for ISD in ISDs:
isd_graphs[ISD] = draw_isd_graph(ISD, ISDs[ISD]["AS"], e_labels, n_labels)
# put all isd graphs into the same graph
for ISD in isd_graphs:
dot.subgraph(isd_graphs[ISD])
# add edges between ISDs
dot = draw_inter_ISD_edges(dot, ISDs, e_labels)
return dot
def to_graphviz(self):
graph = Graph()
assigns = ['<%s> %s' % (str(assign.uid), str(assign)) for assign in self.assigns]
graph.node(str(self.uid), '{%s | %s}' % (self.name, '|'.join(assigns)), shape='record')
return graph
def to_graphviz(self, filename):
graph = Graph()
graph.format = 'svg'
for inst in self.insts:
graph.subgraph(inst.to_graphviz())
for net in self.nets:
graph.node(str(net.uid), str(net))
for assign in self.assigns:
_from = '%s:%s' % (str(assign.terminal.inst.uid), str(assign.uid))
graph.edge(_from, str(assign.to.uid))
graph.render(filename)
def concrete_bipartite_as_graph(self, subjects, patterns) -> Graph: # pragma: no cover
"""Returns a :class:`graphviz.Graph` representation of this bipartite graph."""
if Graph is None:
raise ImportError('The graphviz package is required to draw the graph.')
bipartite = self._build_bipartite(subjects, patterns)
graph = Graph()
nodes_left = {} # type: Dict[TLeft, str]
nodes_right = {} # type: Dict[TRight, str]
node_id = 0
for (left, right), value in bipartite._edges.items():
if left not in nodes_left:
subject_id, i = left
name = 'node{:d}'.format(node_id)
nodes_left[left] = name
label = '{}, {}'.format(i, self.subjects_by_id[subject_id])
graph.node(name, label=label)
node_id += 1
if right not in nodes_right:
pattern, i = right
name = 'node{:d}'.format(node_id)
nodes_right[right] = name
label = '{}, {}'.format(i, self.automaton.patterns[pattern][0])
graph.node(name, label=label)
node_id += 1
edge_label = value is not True and str(value) or ''
graph.edge(nodes_left[left], nodes_right[right], edge_label)
return graph
def draw_topology(topology_dict, output_filename='img/topology'):
'''
topology_dict - ??????? ? ????????? ?????????
???? ???????
{('R4', 'Fa0/1'): ('R5', 'Fa0/1'),
('R4', 'Fa0/2'): ('R6', 'Fa0/0')}
????????????? ?????????:
[ R5 ]-Fa0/1 --- Fa0/1-[ R4 ]-Fa0/2---Fa0/0-[ R6 ]
??????? ?????????? ?????????, ? ??????? svg.
? ?????????? ???? topology.svg ? ??????? img.
'''
nodes = set([item[0]
for item in list(topology_dict.keys())
+ list(topology_dict.values())])
g1 = gv.Graph(format='svg')
for node in nodes:
g1.node(node)
for key, value in topology_dict.items():
head, t_label = key
tail, h_label = value
g1.edge(head, tail, headlabel=h_label, taillabel=t_label, label=" "*12)
g1 = apply_styles(g1, styles)
filename = g1.render(filename=output_filename)
print( "Graph saved in", filename )
def draw_topology(topology_dict, out_filename='img/topology', style_dict=styles):
'''
topology_dict - ??????? ? ????????? ?????????
?????? ??????? topology_dict:
{('R4', 'Eth0/1'): ('R5', 'Eth0/1'),
('R4', 'Eth0/2'): ('R6', 'Eth0/0')}
????????????? ?????????:
[ R5 ]-Eth0/1 --- Eth0/1-[ R4 ]-Eth0/2---Eth0/0-[ R6 ]
??????? ?????????? ?????????, ? ??????? svg.
? ?????????? ???? topology.svg ? ??????? img.
'''
nodes = set([item[0]
for item in list(topology_dict.keys())
+ list(topology_dict.values())])
graph = gv.Graph(format='svg')
for node in nodes:
graph.node(node)
for key, value in topology_dict.items():
head, t_label = key
tail, h_label = value
graph.edge(head, tail, headlabel=h_label, taillabel=t_label, label=" "*12)
graph = apply_styles(graph, style_dict)
filename = graph.render(filename=out_filename)
print( "Topology saved in", filename )
def graphUpdate(self):
if self.aType == "tw":
self.graph = Digraph()
elif self.aType == "fb":
self.graph = Graph()
else:
exit("Invalid Analyze Type")
for key in self.nameIndex.keys():
self.graph.node(self.nameIndex[key], key)
for key in self.network.keys():
for friend in self.network[key]:
if friend != "":
self.graph.edge(self.nameIndex[key],self.nameIndex[friend])
def get_graph(self):
"""
:return: Isd graphviz graph with correct formatting
"""
graph_name = 'cluster_' + "ISD " + self.ISD
label = "ISD " + self.ISD
isd_graph = Graph(name=graph_name,
graph_attr={'color': 'blue', 'label': label, 'style': 'rounded'})
return isd_graph
def get_core_graph(self):
"""
:return: Isd graphviz core graph with correct formatting
"""
return Graph(name='cluster_core',
graph_attr={'color': 'red', 'label': '', 'style': 'rounded'})
def add_nodes(self, to_draw_list, graph, core, ip_addresses):
"""
Adds nodes of ASes to a graph
:param: self, array to_draw_list: an array of ASes,
graphviz graph: Graph to which we add the nodes,
bool core: indicates if we add core nodes
bool ip_addresses: indicates if we have edge labels
"""
for AS in to_draw_list:
if ip_addresses:
self.draw_node_with_attributes(AS, core, graph)
else:
self.draw_node_without_attributes(AS, core, graph)