def __init__(self, graphviz=False):
self.graphviz = graphviz
self.graphviz_digraph = gv.Digraph(format='svg', comment='Generation Instances') if graphviz else None
python类Digraph()的实例源码
def draw_lattice(node, output_filename = 'output.dot'):
"""Draw CFG and output as pdf."""
graph = Digraph(format='pdf')
l = list()
draw_node(l, graph, node)
graph = apply_styles(graph, styles)
graph.render(filename = output_filename)
def draw_lattice(cfg, output_filename='output'):
"""Draw CFG and output as pdf."""
graph = Digraph(format='pdf')
ll = [s.label for s in cfg.nodes if isinstance(s, AssignmentNode)]
root = make_lattice(ll,len(ll)-1)
l = list()
draw_node(l, graph, root)
graph = apply_styles(graph, lattice_styles)
graph.render(filename = output_filename+'.dot')
add_anchor(output_filename)
run_dot(output_filename)
def draw_lattice_from_labels(labels, output_filename):
graph = Digraph(format='pdf')
root = make_lattice(labels, len(labels)-1)
l = list()
draw_node(l, graph, root)
graph = apply_styles(graph, lattice_styles)
graph.render(filename = output_filename+'.dot')
add_anchor(output_filename)
run_dot(output_filename)
def save_dependency(self, to_file):
dot = graphviz.Digraph(comment='Docker Images Dependency')
dot.body.extend(['rankdir=LR'])
for image in self.images:
if image['status'] not in ['matched']:
continue
dot.node(image['name'])
if image['parent'] is not None:
dot.edge(image['parent']['name'], image['name'])
with open(to_file, 'w') as f:
f.write(dot.source)
def save_dependency(self, to_file):
dot = graphviz.Digraph(comment='Docker Images Dependency')
dot.body.extend(['rankdir=LR'])
for image in self.images:
if image['status'] not in ['matched']:
continue
dot.node(image['name'])
if image['parent'] is not None:
dot.edge(image['parent']['name'], image['name'])
with open(to_file, 'w') as f:
f.write(dot.source)
def add_nodes(node_table, name=None, name_scope=None, style=True):
"""
Add TensorFlow graph's nodes to graphviz.dot.Digraph.
@param node_table
@param name
@param name_scope
@param style
@return graphviz.dot.Digraph object
"""
global CLUSTER_INDEX
if name:
digraph = tf_digraph(name=name, name_scope=name_scope, style=style)
else:
digraph = tf_digraph(name=str(uuid.uuid4().get_hex().upper()[0:6]), name_scope=name_scope, style=style)
graphs = []
for key, value in node_table.items():
if len(value) > 0:
sg = add_nodes(value, name='cluster_%i' % CLUSTER_INDEX, name_scope=key.split('/')[-1], style=style)
sg.node(key, key.split('/')[-1])
CLUSTER_INDEX += 1
graphs.append(sg)
else:
digraph.node(key, key.split('/')[-1])
for tg in graphs:
digraph.subgraph(tg)
return digraph
def board(tfgraph, depth=1, name='G', style=True):
"""
Return graphviz.dot.Digraph object with TensorFlow's Graphs.
@param depth
@param name
@param style
@return graphviz.dot.Digraph
"""
global CLUSTER_INDEX
CLUSTER_INDEX = 0
_node_table = node_table(tfgraph, depth=depth)
_node_inpt_table, _node_inpt_shape_table = node_input_table(tfgraph, depth=depth)
digraph = add_nodes(_node_table, name=name, style=style)
digraph = add_edges(digraph, _node_inpt_table, _node_inpt_shape_table)
return digraph
def save_visualization(name, format='jpg'):
g = graphviz.Digraph(format=format)
def sizestr(var):
size = [int(i) for i in list(var.size())]
return str(size)
# add variable nodes
for vid, var in vars.items():
if isinstance(var, nn.Parameter):
g.node(str(vid), label=sizestr(var), shape='ellipse', style='filled', fillcolor='red')
elif isinstance(var, Variable):
g.node(str(vid), label=sizestr(var), shape='ellipse', style='filled', fillcolor='lightblue')
else:
assert False, var.__class__
# add creator nodes
for cid in func_trace:
creator = funcs[cid]
g.node(str(cid), label=str(creator.__class__.__name__), shape='rectangle', style='filled', fillcolor='orange')
# add edges between creator and inputs
for cid in func_trace:
for iid in func_trace[cid]:
g.edge(str(iid), str(cid))
# add edges between outputs and creators
for oid in var_trace:
for cid in var_trace[oid]:
g.edge(str(cid), str(oid))
g.render(name)
def output_graph(self, outdir, outfile, numInSpecies=None):
self.init_network()
g1 = gv.Digraph(format='png')
g1.attr('node', shape='doublecircle')
for in_node in self.inputs:
g1.attr('node', color='green')
g1.node(self.get_node_name(in_node))
for out_node in self.outputs:
g1.attr('node', color='blue')
g1.node(self.get_node_name(out_node))
g1.attr('node', shape='circle', color='black')
for node_id in self.nodes:
if node_id in self.inputs or node_id in self.outputs:
continue
g1.node(self.get_node_name(node_id))
for conn in (self.connections[x] for x in self.connections):
if not conn.is_enabled:
g1.attr('edge', style='dashed', arrowhead='empty')
if conn.is_recurrent:
if not self.allow_recurrent:
continue
g1.attr('edge', color='red')
g1.edge(self.get_node_name(conn.from_node),
self.get_node_name(conn.to_node),
label='{:.4f}'.format(conn.weight))
g1.attr('edge', color='black', arrowhead='normal', style='solid')
if numInSpecies:
label = ('label = "Fitness = {:.2f}, '
'Species Size = {}"').format(self.fitness,
numInSpecies)
else:
label = 'label = "Fitness = {:.2f}"'.format(self.fitness)
g1.body.append(label)
g1.render(filename=outfile,
directory=outdir,
cleanup=True)
def draw_lattice(cfg, output_filename='output'):
"""Draw CFG and output as pdf."""
graph = Digraph(format='pdf')
ll = [s.label for s in cfg.nodes if isinstance(s, AssignmentNode)]
root = make_lattice(ll,len(ll)-1)
l = list()
draw_node(l, graph, root)
graph = apply_styles(graph, lattice_styles)
graph.render(filename = output_filename+'.dot')
add_anchor(output_filename)
run_dot(output_filename)
def draw_lattice_from_labels(labels, output_filename):
graph = Digraph(format='pdf')
root = make_lattice(labels, len(labels)-1)
l = list()
draw_node(l, graph, root)
graph = apply_styles(graph, lattice_styles)
graph.render(filename = output_filename+'.dot')
add_anchor(output_filename)
run_dot(output_filename)
def dot_graph(self, parent_graph=None):
from graphviz import Digraph
#graph_attr = {'label': self._name}
graph_attr = {}
if parent_graph is None:
g = Digraph('cluster_' + self._name, graph_attr=graph_attr)
else:
g = parent_graph.subgraph('cluster_' + self._name,
label=self._name)
for child in self._children:
if isinstance(child, Block):
block = child
label = block.name.split('/', 1)[1]
block_colors = defaultdict(lambda: 'white')
block_colors['CopyBlock'] = 'lightsteelblue'
block_type = block.__class__.__name__
fillcolor = block_colors[block_type]
g.node(block.name,
#label='%s: %s' % (block.type,block.name),
label=label,
shape='box',
style='filled',
fillcolor=fillcolor)
for oring in block.orings:
space_colors = {
'system': 'orange',
'cuda': 'limegreen',
'cuda_host': 'deepskyblue'
}
g.node(oring.name,
shape='ellipse',
style='filled',
fillcolor=space_colors[oring.space])
g.edge(block.name, oring.name)
for iring in block.irings:
g.edge(iring.name, block.name)
else:
#child.dot_graph(g)
g.subgraph(child.dot_graph())
return g
def tf_to_dot(g):
dot = Digraph()
for n in g.node:
dot.node(n.name, label=n.name)
for i in n.input:
dot.edge(i, n.name)
return dot
def draw_graph(nodes_list):
"""Draws the graph image using Graphviz library"""
graph = graphviz.Digraph(name='ProcessGraph', format='svg')
graph.body.extend(['rankdir=LR'])
graph.attr('node', style='bold')
for node in nodes_list:
graph.node(name=node.name, color=X11_colors[node.type])
for successor in node.successor_list:
graph.edge(node.name, successor.name, label=str(successor.time_value))
try:
graph.render(directory=render_dir)
except RuntimeError:
logger.warning("Can't render graphs. Check if Graphviz path is valid")
def sent2graph(sentence):
dot = Digraph(format='png')
for chunk in sentence:
if chunk.dst != -1:
dot.node(str(chunk.id), chunk.join_surface())
dot.node(str(chunk.dst), sentence[chunk.dst].join_surface())
dot.edge(str(chunk.id), str(chunk.dst))
dot.render('knock44')
def sent2graph(sentence):
dot = Digraph(format='png')
for chunk in sentence:
if chunk.dst != -1:
dot.node(str(chunk.id), chunk.join_surface())
dot.node(str(chunk.dst), sentence[chunk.dst].join_surface())
dot.edge(str(chunk.id), str(chunk.dst))
dot.render('knock44')
def sent2graph(sentence):
dot = Digraph(format='png')
for chunk in sentence:
if chunk.dst != -1:
dot.node(str(chunk.id), chunk.join_surface())
dot.node(str(chunk.dst), sentence[chunk.dst].join_surface())
dot.edge(str(chunk.id), str(chunk.dst))
dot.render('knock44', cleanup=True)
def endElement(self, name):
self.pop_tag()
if name == 'dependencies':
self.is_representative = False
fname = '{}/{}'.format(dirname, self.sent_id)
self.graph.render(fname, cleanup=True)
self.graph = Digraph(format='svg')
def sent2graph(sentence):
dot = Digraph(format='png')
for chunk in sentence:
if chunk.dst != -1:
dot.node(str(chunk.id), chunk.join_surface())
dot.node(str(chunk.dst), sentence[chunk.dst].join_surface())
dot.edge(str(chunk.id), str(chunk.dst))
dot.render('knock44', cleanup=True)