def render(self, data, label=None, filename="Graph", directory="graphs", view=True):
"""Graphviz rendering."""
# create the Graphviz graph
graph_attr = self.graph_attr.copy()
if label is not None:
graph_attr['label'] = self._escape_label(label)
graph = gv.Digraph(graph_attr=graph_attr, node_attr=self.node_attr, edge_attr=self.edge_attr)
# draw nodes and edges of the Graphviz graph
self._graph = graph
self._rendered = set()
self._render(data)
self._graph = None
self._rendered = None
# display the Graphviz graph
graph.format = "pdf"
graph.render(f"{filename}.gv", directory, view, cleanup=True)
python类Digraph()的实例源码
def draw_cfg(cfg, output_filename = 'output'):
"""Draw CFG and output as pdf."""
graph = Digraph(format='pdf')
for node in cfg.nodes:
stripped_label = node.label.replace(IGNORED_LABEL_NAME_CHARACHTERS, '')
if 'Exit' in stripped_label:
graph.node(stripped_label, 'Exit', shape='none')
elif 'Entry' in stripped_label:
graph.node(stripped_label, 'Entry', shape='none')
else:
graph.node(stripped_label, stripped_label)
for ingoing_node in node.ingoing:
graph.edge(ingoing_node.label.replace(IGNORED_LABEL_NAME_CHARACHTERS, ''), stripped_label)
graph = apply_styles(graph, cfg_styles)
graph.render(filename = output_filename)
def dag(self, file_name='dag', file_format='svg'):
'''Create a dag of this node and its children'''
try:
import graphviz as gv
except ImportError:
# todo: add a warning to a log file here
# silently return if graphviz bindings are not installed
return
try:
graph = gv.Digraph(format=file_format)
except ValueError:
raise GenerationError(
"unsupported graphviz file format '{0}' provided".
format(file_format))
self.dag_gen(graph)
graph.render(filename=file_name)
def tf_digraph(name=None, name_scope=None, style=True):
"""
Return graphviz.dot.Digraph with TensorBoard-like style.
@param name
@param name_scope
@param style
@return graphviz.dot.Digraph object
"""
digraph = gv.Digraph(name=name)
if name_scope:
digraph.graph_attr['label'] = name_scope
if style is False: return digraph
if name_scope:
digraph.graph_attr.update(name_scope_graph_pref)
else:
digraph.graph_attr.update(non_name_scope_graph_pref)
digraph.graph_attr.update(graph_pref)
digraph.node_attr.update(node_pref)
digraph.edge_attr.update(edge_pref)
return digraph
def add_edges(digraph, node_inpt_table, node_inpt_shape_table):
"""
Add TensorFlow graph's edges to graphviz.dot.Digraph.
@param dirgraph
@param node_inpt_table
@param node_inpt_shape_table
@return graphviz.dot.Digraph
"""
for node, node_inputs in node_inpt_table.items():
if re.match(r"\^", node): continue
for ni in node_inputs:
if ni == node: continue
if re.match(r"\^", ni): continue
if not ni in node_inpt_shape_table:
digraph.edge(ni, node)
else:
shape = node_inpt_shape_table[ni]
digraph.edge(ni, node, label=edge_label(shape))
return digraph
def draw_cfg(cfg, output_filename = 'output'):
"""Draw CFG and output as pdf."""
graph = Digraph(format='pdf')
for node in cfg.nodes:
stripped_label = node.label.replace(IGNORED_LABEL_NAME_CHARACHTERS, '')
if 'Exit' in stripped_label:
graph.node(stripped_label, 'Exit', shape='none')
elif 'Entry' in stripped_label:
graph.node(stripped_label, 'Entry', shape='none')
else:
graph.node(stripped_label, stripped_label)
for ingoing_node in node.ingoing:
graph.edge(ingoing_node.label.replace(IGNORED_LABEL_NAME_CHARACHTERS, ''), stripped_label)
graph = apply_styles(graph, cfg_styles)
graph.render(filename = output_filename)
def __init__(self, **kwargs):
super(ExVizPass, self).__init__()
self.show_axes = kwargs.pop('show_axes', True)
self.show_all_metadata = kwargs.pop('show_all_metadata', True)
self.subgraph_attr = kwargs.pop('subgraph_attr', None)
self.exops_with_nodes = set()
self.exops_without_nodes = set()
self.filename = kwargs.pop('filename', 'Digraph')
self.view = kwargs.pop('view', True)
self.cleanup = kwargs.pop('cleanup', True)
self.show_tensors = kwargs.pop('show_tensors', False)
output_directory = kwargs.pop('output_directory', '.')
if self.view:
if output_directory is None:
output_directory = tempfile.mkdtemp()
self.output_directory = output_directory
def begin_pass(self, filename=None, **kwargs):
super(ExVizPass, self).begin_pass(**kwargs)
try:
import graphviz
except ImportError:
raise ImportError("You tried to use the ShowGraph transformer pass but did "
"not have the python graphviz library installed")
if filename is None:
filename = self.filename
self.exops_with_nodes = set()
self.exops_without_nodes = set()
self.tensors_with_nodes = set()
self.tensors_without_nodes = set()
# Get all ops from this set
self.graph = graphviz.Digraph(name=filename,
# node_attr={'shape': 'box', 'style': 'rounded'},
graph_attr={'nodesep': '.5',
'ranksep': '.5'})
def save(fname, creator):
dot = Digraph(comment='LRP',
node_attr={'style': 'filled', 'shape': 'box'})
#, 'fillcolor': 'lightblue'})
seen = set()
def add_nodes(var):
if var not in seen:
if isinstance(var, Variable):
dot.node(str(id(var)), str(var.size()), fillcolor='lightblue')
else:
dot.node(str(id(var)), type(var).__name__)
seen.add(var)
if hasattr(var, 'previous_functions'):
for u in var.previous_functions:
dot.edge(str(id(u[0])), str(id(var)))
add_nodes(u[0])
add_nodes(creator)
dot.save(fname)
def save(fname, creator):
dot = Digraph(comment='LRP',
node_attr={'style': 'filled', 'shape': 'box'})
#, 'fillcolor': 'lightblue'})
seen = set()
def add_nodes(var):
if var not in seen:
if isinstance(var, Variable):
dot.node(str(id(var)), str(var.size()), fillcolor='lightblue')
else:
dot.node(str(id(var)), type(var).__name__)
seen.add(var)
if hasattr(var, 'previous_functions'):
for u in var.previous_functions:
dot.edge(str(id(u[0])), str(id(var)))
add_nodes(u[0])
add_nodes(creator)
dot.save(fname)
def create_transition_graph(d, role, format_):
graph = gv.Digraph(format=format_)
for node in d:
node_name = to_node_name(node)
graph.node(node_name, label=node_name)
self_transitions = defaultdict(lambda: [])
for source, transitions in d.items():
source_name = to_node_name(source)
for received, dest in transitions.items():
dest_name = to_node_name(dest)
received_name = to_node_name(received)
if source_name == dest_name:
self_transitions[source_name].append(received_name)
continue
graph.edge(source_name, dest_name,
label=received_name)
for node_name, received_list in self_transitions.items():
graph.edge(node_name, node_name, label=' / '.join(received_list))
return graph
def __init__(self, crc_cards, format='png', graph_data=None):
self.format = format
self.crc_cards = crc_cards
self.graph_data = {'shape': 'record'}
self._edges = [] # keep track of the edges
if graph_data is not None:
self.graph_data.update(graph_data)
self.graph = Digraph(
comment='CRC Diagram',
node_attr=self.graph_data,
format=self.format
)
self._init()
def dependency_parsing():
dom = xml.dom.minidom.parse("nlp.txt.xml")
dpnds = dom.getElementsByTagName('dependencies')
dot = Digraph(format='png')
idgov, iddep, lblgov, lbldep = '', '', '', ''
for dpnd in dpnds:
if dpnd.getAttribute('type') == "collapsed-dependencies":
deps = dpnd.getElementsByTagName('dep')
for dep in deps:
governors = dep.getElementsByTagName('governor')
dependents = dep.getElementsByTagName('dependent')
for governor, dependent in zip(governors, dependents):
idgov = governor.getAttribute('idx')
lblgov = governor.firstChild.data
iddep = dependent.getAttribute('idx')
lbldep = dependent.firstChild.data
dot.node(str(iddep), lbldep)
dot.node(str(idgov), lblgov)
dot.edge(str(idgov), str(iddep))
dot.render('png-knock57', cleanup=True)
exit()
def dependency_parsing():
dom = xml.dom.minidom.parse("nlp.txt.xml")
dpnds = dom.getElementsByTagName('dependencies')
dot = Digraph(format='png')
idgov, iddep, lblgov, lbldep = '', '', '', ''
for dpnd in dpnds:
if dpnd.getAttribute('type') == "collapsed-dependencies":
deps = dpnd.getElementsByTagName('dep')
for dep in deps:
governors = dep.getElementsByTagName('governor')
dependents = dep.getElementsByTagName('dependent')
for governor, dependent in zip(governors, dependents):
idgov = governor.getAttribute('idx')
lblgov = governor.firstChild.data
iddep = dependent.getAttribute('idx')
lbldep = dependent.firstChild.data
dot.node(str(iddep), lbldep)
dot.node(str(idgov), lblgov)
dot.edge(str(iddep), str(idgov))
dot.render('png-knock57', cleanup=True)
exit()
def generate_graph(related_subs, subscribers, nsfw_subs, censored, full, min_subscribers, outfile):
""" Make a graphviz graph by adding edges for each sub and related subs """
g = Digraph('G', filename=outfile)
edges_added = 0
for key in related_subs:
for sub in related_subs[key]:
if not sub or not sub in subscribers:
continue
# In nsfw_subs and censored is mutually exclusive
if ((sub in nsfw_subs) != (censored)) or full:
subscriber_cnt = subscribers[sub]
# Filter: only include edge if sub has # subscribers
if subscriber_cnt >= min_subscribers:
g.edge(key, sub, weight=calculate_edge_weight(subscriber_cnt))
print("Edge count: " + str(edges_added))
edges_added += 1
g.save()
def generate_mapping_subgraph(table):
subgraph = Digraph(table.name, node_attr={
'width:': '20',
'fixed_size': 'shape'
})
subgraph.node(table.name, shape='box')
for osm_key, osm_values in table.mapping:
node_name = 'key_' + normalize_graphviz_labels(osm_key)
subgraph.node(node_name, label=osm_key, shape='box')
subgraph.edge(node_name, table.name,
label=values_label(osm_values))
return subgraph
def sentence_to_graph_recursive(self, token, parent_id, e):
"""Recursive function on each node as to generates the sentence dependency tree image.
Args:
token: The string token raw text.
parent_id: The id of the parent node this token is a child of in the dependency tree.
e: The graphical object (graphviz.Digraph).
"""
if len(list(token.children)) == 0:
return
current_global_id = {}
for child in token.children:
self.current_token_id += 1
current_global_id[str(self.current_token_id)] = child
for child_id, child in current_global_id.items():
self.sentence_to_graph_add_node(e, child_id, child.orth_)
e.edge(str(parent_id), child_id, label=child.dep_)
for child_id, child in current_global_id.items():
self.sentence_to_graph_recursive(child, child_id, e)
def gen_group_image(self, token, depth=1):
"""Generates the images based on the node that represents this group.
Args:
token: The Treenode node.
depth: integer 1 by default, as we are only interested in the first level.
Returns:
A string with the image path.
"""
e = Digraph(self.argv.tetre_word, format=GroupImageNameGenerator.file_extension)
e.attr('node', shape='box')
current_id = self.current_token_id
e.node(str(current_id), token.pos_)
self.group_to_graph_recursive_with_depth(token, current_id, e, depth)
name_generator = GroupImageNameGenerator(self.base_image_name, self.argv.tetre_word, str(self.current_group_id))
e.render(name_generator.get_render_path())
self.current_group_id += 1
return name_generator.get_base_path_with_extension()
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 to_dot(self, return_graph=False):
"""
Creates a DOT format representation of this chain, where states
are represented as labelled nodes and transitions as directed arcs
labelled by their probabilities. If return_graph is set to True,
the graphviz.Digraph object that contains the representation is
returned instead.
:param return_graph: a boolean indicating if the underlying Digraph
object should be returned instead of the string representation
:returns: a representation of the chain in DOT format
"""
graph = gv.Digraph(format='svg')
for st in self.states.values():
st.populate_graph(graph)
return graph if return_graph else graph.source
def _make_dot(var):
node_attr = dict(style='filled',
shape='box',
align='left',
fontsize='12',
ranksep='0.1',
height='0.2')
dot = Digraph(node_attr=node_attr, graph_attr=dict(size="12,12"))
seen = set()
def add_nodes(var):
if var not in seen:
if isinstance(var, Variable):
value = '(' + (', ').join(['%d' % v for v in var.size()]) + ')'
dot.node(str(id(var)), str(value), fillcolor='lightblue')
else:
dot.node(str(id(var)), str(type(var).__name__))
seen.add(var)
if hasattr(var, 'previous_functions'):
for u in var.previous_functions:
dot.edge(str(id(u[0])), str(id(var)))
add_nodes(u[0])
add_nodes(var.creator)
return dot
def create_graph(semantic_graph):
splines = 'spline'
if semantic_graph.loop_edges or semantic_graph.and_loop_edges:
splines = 'ortho'
g = graphviz.Digraph(
graph_attr={'rankdir':'BT', 'splines':splines},
node_attr={
'shape':'rectangle', 'style':'rounded,filled', 'fillcolor':'#FFFFCC'
}
)
for identifier, label, cls in semantic_graph.nodes:
g.node(identifier, label=label, **attrs[cls])
g.edges(semantic_graph.edges)
for e in semantic_graph.and_edges:
g.edge(*e, dir="none")
for e in semantic_graph.loop_edges:
g.edge(*e, constraint="false")
for e in semantic_graph.and_loop_edges:
g.edge(*e, dir="none", constraint="false")
for a, b in semantic_graph.conflicts:
subgraph = graphviz.Digraph('cluster', graph_attr={'rank':'same', 'color':'none'})
subgraph.edge(a, b, style="tapered", dir="both", arrowhead="none",
arrowtail="none", constraint="false", color="red", penwidth="7")
g.subgraph(subgraph)
return g
def save(fname, creator):
dot = Digraph(comment='LRP',
node_attr={'style': 'filled', 'shape': 'box'})
#, 'fillcolor': 'lightblue'})
seen = set()
def add_nodes(var):
if var not in seen:
if isinstance(var, Variable):
dot.node(str(id(var)), str(var.size()), fillcolor='lightblue')
else:
dot.node(str(id(var)), type(var).__name__)
seen.add(var)
if hasattr(var, 'previous_functions'):
for u in var.previous_functions:
dot.edge(str(id(u[0])), str(id(var)))
add_nodes(u[0])
add_nodes(creator)
dot.save(fname)
def __init__(self,output,cache_data):
# TODO: Store this relations in a redis-like cache
self.cache = Cache(cache_data)
self.cache.create_cache(self.DEST_RELS)
self.cache.create_cache(self.DOM_RELS)
self.cache.create_cache(self.SRC_RELS)
self.cache.create_cache(self.SRCDST_RELS)
self.cache.create_cache(self.SRCLOGIN_RELS)
self.cache.create_cache(self.SESSIONS_RELS)
self.cache.create_cache(self.FROM_SESSIONS)
self.cache.create_cache(self.USER_LIST)
self.cache.create_cache(self.DOM_LIST)
self.cache.create_cache(self.SRV_LIST)
self.cache.create_cache(self.SRVDOM_RELS)
self.output = output
self.graph = gv.Digraph()
def save_dependency(self, to_file):
try:
import graphviz
except ImportError:
LOG.error('"graphviz" is required for save dependency')
raise
dot = graphviz.Digraph(comment='Docker Images Dependency')
dot.body.extend(['rankdir=LR'])
for image in self.images:
if image.status not in [STATUS_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 _as_graph(self, finals: Optional[List[str]]) -> Digraph: # pragma: no cover
if Digraph is None:
raise ImportError('The graphviz package is required to draw the graph.')
graph = Digraph()
if finals is None:
patterns = [
'{}: {} with {}'.format(
self._colored_pattern(i), html.escape(str(p.expression)), self._format_constraint_set(c)
) for i, (p, l, c) in enumerate(self.patterns)
]
graph.node('patterns', '<<b>Patterns:</b><br/>\n{}>'.format('<br/>\n'.join(patterns)), {'shape': 'box'})
self._make_graph_nodes(graph, finals)
if finals is None:
constraints = [
'{}: {} for {}'.format(self._colored_constraint(i), html.escape(str(c)), self._format_pattern_set(p))
for i, (c, p) in enumerate(self.constraints)
]
graph.node(
'constraints', '<<b>Constraints:</b><br/>\n{}>'.format('<br/>\n'.join(constraints)), {'shape': 'box'}
)
self._make_graph_edges(graph)
return graph
def _make_graph_edges(self, graph: Digraph) -> None: # pragma: no cover
for state in self.states:
for _, transitions in state.transitions.items():
for transition in transitions:
t_label = '<'
if transition.variable_name:
t_label += '{}: '.format(self._colored_variable(transition.variable_name))
t_label += 'ε' if transition.label is _EPS else html.escape(str(transition.label))
if is_operation(transition.label):
t_label += '('
t_label += '<br/>{}'.format(self._format_pattern_set(transition.patterns))
if transition.check_constraints is not None:
t_label += '<br/>{}'.format(self._format_constraint_set(transition.check_constraints))
if transition.subst is not None:
t_label += '<br/>{}'.format(html.escape(str(transition.subst)))
t_label += '>'
start = 'n{!s}'.format(state.number)
if state.matcher and len(state.matcher.automaton.states) > 1:
start += '-end'
end = 'n{!s}'.format(transition.target.number)
graph.edge(start, end, t_label)
def build_petrinet(tl, yl, ti, to, output_file):
pn = gv.Digraph(format='png')
pn.attr(rankdir='LR') # left to righ layout - default is top down
pn.node('start')
pn.node('end')
for elem in yl:
for i in elem[0]:
pn.edge(i, str(elem))
pn.node(i, shape='box')
pn.node(str(elem), shape='circle')
for i in elem[1]:
pn.edge(str(elem), i)
pn.node(i, shape='box')
for i in ti:
pn.edge('start', i)
for o in to:
pn.edge(o, 'end')
pn.render(output_file)
def save(fname, creator):
dot = Digraph(comment='LRP', node_attr={'style': 'filled', 'shape': 'box'})
seen = set()
def add_nodes(var):
if var not in seen:
if isinstance(var, Variable):
dot.node(str(id(var)), str(var.size()), fillcolor='lightblue')
else:
dot.node(str(id(var)), type(var).__name__)
seen.add(var)
if hasattr(var, 'previous_functions'):
for u in var.previous_functions:
dot.edge(str(id(u[0])), str(id(var)))
add_nodes(u[0])
add_nodes(creator)
dot.save(fname)
def to_dot(self):
"""Produces a ball and stick graph of this state machine.
Returns
-------
`graphviz.Digraph`
A ball and stick visualization of this state machine.
"""
from graphviz import Digraph
dot = Digraph(format='png')
for state in self.states:
if isinstance(state, TransientState):
dot.node(state.name(), style='dashed')
else:
dot.node(state.name())
for transition in state.transition_set:
dot.edge(state.name(), transition.output.name(), transition.label())
return dot