本文整理汇总了Python中pygraphviz.AGraph.layout方法的典型用法代码示例。如果您正苦于以下问题:Python AGraph.layout方法的具体用法?Python AGraph.layout怎么用?Python AGraph.layout使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygraphviz.AGraph
的用法示例。
在下文中一共展示了AGraph.layout方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def render(self, filename):
g = AGraph(strict=False, directed=True)
# create nodes
for frame_id, node in self.callers.items():
label = "{ %s }" % node
g.add_node(frame_id, shape='Mrecord', label=label,
fontsize=13, labelfontsize=13)
# create edges
for frame_id, node in self.callers.items():
child_nodes = []
for child_id in node.child_methods:
child_nodes.append(child_id)
g.add_edge(frame_id, child_id)
# order edges l to r
if len(child_nodes) > 1:
sg = g.add_subgraph(child_nodes, rank='same')
sg.graph_attr['rank'] = 'same'
prev_node = None
for child_node in child_nodes:
if prev_node:
sg.add_edge(prev_node, child_node, color="#ffffff")
prev_node = child_node
g.layout()
g.draw(path=filename, prog='dot')
print("callviz: rendered to %s" % filename)
self.clear()
示例2: plot
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def plot(table_names=None):
"""
Plot relationships between columns and tables using Graphviz.
Parameters
----------
table_names : iterable of str, optional
Names of UrbanSim registered tables to plot.
Defaults to all registered tables.
Returns
-------
graph : pygraphviz.AGraph
PyGraphviz graph object.
"""
if not table_names:
# Default to all registered tables.
table_names = simulation.list_tables()
graph = AGraph(directed=True)
graph.graph_attr['fontname'] = 'Sans'
graph.graph_attr['fontsize'] = 28
graph.node_attr['shape'] = 'box'
graph.node_attr['fontname'] = 'Sans'
graph.node_attr['fontcolor'] = 'blue'
graph.edge_attr['weight'] = 2
# Add each registered table as a subgraph with columns as nodes.
for table_name in table_names:
subgraph = graph.add_subgraph(name='cluster_' + table_name,
label=table_name, fontcolor='red')
table = simulation.get_table(table_name)
for column_name in table.columns:
full_name = table_name + '.' + column_name
subgraph.add_node(full_name, label=column_name)
# Iterate over computed columns to build nodes.
for key, wrapped_col in simulation._COLUMNS.items():
table_name = key[0]
column_name = key[1]
# Combine inputs from argument names and argument default values.
args = list(wrapped_col._argspec.args)
if wrapped_col._argspec.defaults:
default_args = list(wrapped_col._argspec.defaults)
else:
default_args = []
inputs = args[:len(args) - len(default_args)] + default_args
# Create edge from each input column to the computed column.
for input_name in inputs:
full_name = table_name + '.' + column_name
graph.add_edge(input_name, full_name)
graph.layout(prog='dot')
return graph
示例3: draw_workflow
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def draw_workflow(filename, workflow):
dot = AGraph(directed=True, strict=False) # (comment="Computing scheme")
for i, n in workflow.nodes.items():
dot.add_node(i, label="{0} \n {1}".format(n.foo.__name__, _format_arg_list(n.bound_args.args, None)))
for i in workflow.links:
for j in workflow.links[i]:
dot.add_edge(i, j[0], j[1].name) # , headlabel=j[1].name, labeldistance=1.8)
dot.layout(prog="dot")
dot.draw(filename)
示例4: startGraph
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def startGraph():
# We maintain this globally to make it accessible, pylint: disable=global-statement
global graph
if Options.shallCreateGraph():
try:
from pygraphviz import AGraph # pylint: disable=I0021,import-error
graph = AGraph(name="Optimization", directed=True)
graph.layout()
except ImportError:
warning("Cannot import pygraphviz module, no graphing capability.")
示例5: __call__
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def __call__(self):
self.request.response.setHeader('Content-Type', 'image/svg+xml')
self.request.response.setHeader('Content-Disposition',
'inline; filename=%s.svg' % \
self.context.getId())
tfile = tempfile.NamedTemporaryFile(suffix='.svg')
gv = generate_gv(self.context)
ag = AGraph(string=gv)
ag.layout()
ag.draw(path=tfile, format='svg', prog='dot')
tfile.seek(0)
return tfile.read()
示例6: render_local
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def render_local(self, filename):
"""Renders the OBST image locally using pygraphviz."""
# Get the graph information
node_list, edge_list = self.__generate_image()
# Generate the graph
from pygraphviz import AGraph
G=AGraph(strict=True,directed=True) # Create a graph
for node in node_list:
G.add_node(node)
for edge in edge_list:
G.add_edge(edge[0], edge[1])
G.layout('dot') # Set hierarchical layout
G.draw(filename) # Save the image.
示例7: to_dot
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def to_dot(self, filename, edges):
from pygraphviz import AGraph
dot = AGraph(directed=True)
for n in edges.keys():
dot.add_node(str(n))
if lib.qcgc_arena_get_blocktype(ffi.cast("cell_t *", n)) not in [
lib.BLOCK_BLACK, lib.BLOCK_WHITE]:
node = dot.get_node(str(n))
node.attr['color'] = 'red'
for n in edges.keys():
if edges[n] is not None:
dot.add_edge(str(n), str(edges[n]))
dot.layout(prog='dot')
dot.draw(filename)
示例8: run
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def run(self):
options = self.options
filename = self.arguments[0]
if self.content:
content = u'\n'.join(self.content)
ofilename = filename + '.' + self.outputformat
else:
content = open(filename).read().decode(options.get('encoding','utf-8'))
ofilename = os.path.splitext(filename)[0] + '.' + self.outputformat
g = AGraph(string=content)
g.layout(prog='dot')
opath = os.path.join(OUTPUT_DIR, ofilename)
g.draw(opath, 'png')
self.arguments[0] = opath
return super(GraphvizBlock, self).run()
示例9: render_image
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def render_image(self, filename):
"""Renders the graph image locally using pygraphviz."""
# Create a graph
G=AGraph(directed=False)
# Add nodes
for node in self.nodes:
G.add_node(node)
# Add edges
for edge in self.edges:
G.add_edge(edge[0], edge[1], color='blue')
# Give layout and draw.
G.layout('circo')
G.draw(filename) # Save the image.
# Display the output image.
os.system("gwenview %s&" % filename)
示例10: render_image
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def render_image(node_list, edge_list):
# Generate the graph
from pygraphviz import AGraph
G=AGraph(strict=False,directed=True) # Create a graph
for node in node_list:
G.add_node(node)
for edge in edge_list:
G.add_edge(edge[0], edge[1])
G.layout('dot') # Set hierarchical layout
filename = str(time())
postfix = 0
while exists(filename+str(postfix)+".png"):
postfix+=1
filename += str(postfix) + ".png"
G.draw(filename) # Save the image.
with open(filename, "rb") as handle:
return xmlrpclib.Binary(handle.read())
示例11: write_graph
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def write_graph(probs, path):
graph = AGraph(directed=True)
next_label = 0
labels = {}
for from_state, to_states in probs.iteritems():
if from_state not in labels:
labels[from_state] = next_label
next_label += 1
for to_state in to_states:
if to_state not in labels:
labels[to_state] = next_label
next_label += 1
for label in xrange(next_label):
graph.add_node(label, fillcolor="blue", label="", style="filled")
for from_state, to_states in probs.iteritems():
for to_state, prob in to_states.iteritems():
graph.add_edge(labels[from_state], labels[to_state], label="%.2g" % prob)
# prog: neato (default), dot, twopi, circo, fdp or nop.
graph.layout()
graph.draw(path)
示例12: _drawmap
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def _drawmap(fs, rulename=None):
"""Draw a map of the firewalls and their connections based on their interfaces.
If nulename is specified, draw also the sources and dests for a that rule. #TODO: implement this
"""
A = AGraph()
A.graph_attr['bgcolor'] = 'transparent'
# A.graph_attr['size'] = '8,5'
# Draw hosts
for h in fs.hosts:
A.add_node(h.hostname)
if h.network_fw in (1, True, '1'): # network firewall
f = Node(A, h.hostname)
f.attr['color'] = 'red'
# Draw nets
for net in fs.networks:
A.add_node(net.name)
poly = Node(A, net.name)
poly.attr['shape'] = 'polygon'
poly.attr['sides'] = '8'
# Connect hosts to nets
for host in fs.hosts:
on_Internet = True
for net in fs.networks:
if host in net:
on_Internet = False
A.add_edge(host.hostname, net.name)
e = Edge(A, host.hostname, net.name)
e.attr['label'] = host.iface
e.attr['fontsize'] = '6'
# If a host is not in any configured net, it's on the Internet
if on_Internet:
A.add_edge(host.hostname, 'Internet')
e = Edge(A, host.hostname, 'Internet')
e.attr['label'] = host.iface
e.attr['fontsize'] = '6'
A.layout(prog='circo')
return A
示例13: dot_layout
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
def dot_layout(cy_elements, edge_labels=False, subgraph_boxes=False, node_gt=None):
"""
Get a CyElements object and augment it (in-place) with positions,
widths, heights, and spline data from a dot based layout.
edge_labels is true if labels should appear on edges
subgraph_boxes is true if boxes should be drawn around subgraphs
Returns the object.
"""
elements = cy_elements.elements
# g = AGraph(directed=True, strict=False)
g = AGraph(directed=True, strict=False, forcelabels=True)
# make transitive relations appear top to bottom
elements = list(elements)
nodes_by_id = dict((e["data"]["id"], e) for e in elements if e["group"] == "nodes")
order = [
(nodes_by_id[e["data"]["source"]], nodes_by_id[e["data"]["target"]])
for e in elements
if e["group"] == "edges" and "transitive" in e["data"] and e["data"]["transitive"]
]
elements = topological_sort(elements, order, lambda e: e["data"]["id"])
# get the node id's and stable sort them by cluster
# the idea here is to convert the graph into a dag by sorting
# the nodes, then reversing the back edges. In particular, we try to make
# all the edges between two clusters go in the same direction so clustering
# doesn't result in horizontal edges, which dot renders badly.
sorted_nodes = [e["data"]["id"] for e in elements if e["group"] == "nodes"]
sorted_nodes = sorted(enumerate(sorted_nodes), key=lambda x: (nodes_by_id[x[1]]["data"]["cluster"], x[0]))
sorted_nodes = [y for idx, y in sorted_nodes]
node_key = dict((id, idx) for idx, id in enumerate(sorted_nodes))
if node_gt is None:
node_gt = lambda X, y: False
else:
node_gt = lambda x, y: node_key[x] > node_key[y]
# add nodes to the graph
for e in elements:
if e["group"] == "nodes" and e["classes"] != "non_existing":
g.add_node(e["data"]["id"], label=e["data"]["label"].replace("\n", "\\n"))
# TODO: remove this, it's specific to leader_demo
weight = {"reach": 10, "le": 10, "id": 1}
constraint = {"pending": False}
# add edges to the graph
for e in elements:
if e["group"] == "edges":
# kwargs = {'weight': weight.get(e["data"]["obj"], 0)},
kwargs = {"label": e["data"]["label"]} if edge_labels else {}
if node_gt(e["data"]["source"], e["data"]["target"]):
g.add_edge(
e["data"]["target"],
e["data"]["source"],
e["data"]["id"],
dir="back",
**kwargs
# constraint=constraint.get(e["data"]["obj"], True),
)
else:
g.add_edge(
e["data"]["source"],
e["data"]["target"],
e["data"]["id"],
**kwargs
# constraint=constraint.get(e["data"]["obj"], True),
)
# add clusters
clusters = defaultdict(list)
for e in elements:
if e["group"] == "nodes" and e["data"]["cluster"] is not None and e["classes"] != "non_existing":
clusters[e["data"]["cluster"]].append(e["data"]["id"])
for i, k in enumerate(sorted(clusters.keys())):
g.add_subgraph(name="cluster_{}".format(i), nbunch=clusters[k], rank="min")
# now get positions, heights, widths, and bsplines
g.layout(prog="dot")
# get the y origin. we want the top left of the graph to be a
# fixed coordinate (hopefully (0,0)) so the graph doesn't jump when
# its height changes. Unfortunately, pygraphviz has a bug a gives
# the wrong bbox, so we compute the max y coord.
# bbox = pygraphviz.graphviz.agget(g.handle,'bb')
global y_origin
y_origin = 0.0
for n in g.nodes():
top = float(n.attr["pos"].split(",")[1]) + float(n.attr["height"]) / 2
if top > y_origin:
y_origin = top
if subgraph_boxes:
for sg in g.subgraphs():
#.........这里部分代码省略.........
示例14: __init__
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
#.........这里部分代码省略.........
)
)
self.edges.append(
(
id(stream.c),
id(stream),
stream.c.get_bits(),
"sw"
)
)
def write_decoupler(self, stream):
self.nodes.append(
(
id(stream),
"Decoupler",
"ellipse"
)
)
self.edges.append(
(
id(stream.a),
id(stream),
stream.a.get_bits(),
"w"
)
)
def write_resizer(self, stream):
self.nodes.append((id(stream), "Resizer", "ellipse"))
self.edges.append(
(
id(stream.a),
id(stream),
stream.a.get_bits(),
"w"
)
)
def write_printer(self, stream):
self.nodes.append((id(stream), "Printer", "ellipse"))
self.edges.append(
(
id(stream.a),
id(stream),
stream.a.get_bits(),
"w"
)
)
def write_output(self, stream):
self.outputs[id(stream)] = id(stream.process)
def write_process(self, p):
self.nodes.append((id(p), "Process", "ellipse"))
for i in p.inputs:
self.edges.append((id(i), id(p), i.get_bits(), "centre"))
def write_external_ip(self, ip):
for i in ip.output_streams:
self.ip_outputs[id(i)]=id(ip)
self.nodes.append((id(ip), ip.definition.name, "ellipse"))
for i in ip.input_streams:
self.edges.append((id(i), id(ip), i.get_bits(), "centre"))
def write_chip(self, *args):
pass
#System VHDL Generation and external tools
def draw(self, filename):
for ident, label, shape in self.nodes:
self.schematic.add_node(
str(ident),
shape=shape,
label=str(label)
)
for from_node, to_node, bits, headport in self.edges:
if from_node in self.outputs:
self.schematic.add_edge(
str(self.outputs[from_node]),
str(to_node),
label=str(bits),
headport=headport
)
elif from_node in self.ip_outputs:
self.schematic.add_edge(
str(self.ip_outputs[from_node]),
str(to_node),
label=str(bits),
headport=headport
)
else:
self.schematic.add_edge(
str(from_node),
str(to_node),
label=str(bits)
)
self.schematic.layout(prog='dot')
self.schematic.draw(filename)
示例15: __init__
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import layout [as 别名]
#.........这里部分代码省略.........
def add_functional_edge(self, src, dst, name):
self.connected_nodes.add(src)
self.connected_nodes.add(dst)
self.graph.add_edge(
graphviz_id(src),
graphviz_id(dst),
label=name,
arrowhead="open",
headlabel="1...1",
taillabel="0...*",
labeldistance=2.0,
labelfontcolor="black",
labelangle=-65.0,
)
def add_inversefunctional_edge(self, src, dst, name):
self.connected_nodes.add(src)
self.connected_nodes.add(dst)
self.graph.add_edge(
graphviz_id(src),
graphviz_id(dst),
label=name,
arrowhead="open",
headlabel="0...*",
taillabel="1...1",
labeldistance=2.0,
labelfontcolor="black",
labelangle=-65.0,
)
def add_equivalentclass_edge(self, src, dst):
self.connected_nodes.add(src)
self.connected_nodes.add(dst)
self.graph.add_edge(
graphviz_id(src), graphviz_id(dst), label="\<\<equivalentClass\>\>", arrowhead="none", style="dashed"
)
def add_unionof_edge(self, src, dst):
self.connected_nodes.add(src)
self.connected_nodes.add(dst)
self.graph.add_edge(
graphviz_id(src), graphviz_id(dst), label="\<\<unionOf\>\>", arrowhead="open", style="dashed"
)
def add_oneof_edge(self, src, dst):
self.connected_nodes.add(src)
self.connected_nodes.add(dst)
self.graph.add_edge(
graphviz_id(src), graphviz_id(dst), label="\<\<instanceOf\>\>", arrowhead="open", style="dashed", dir="back"
)
def add_subclass_edge(self, src, dst):
self.connected_nodes.add(src)
self.connected_nodes.add(dst)
self.graph.add_edge(graphviz_id(src), graphviz_id(dst), arrowhead="empty")
def set_label(self, label):
self.graph.graph_attr["label"] = label
def start_subgraph(self, graph_name):
self.subgraph = self.graph.add_subgraph(name="cluster_%s" % graphviz_id(graph_name))
self.subgraph.graph_attr["label"] = graph_name
def add_undescribed_nodes(self):
s = self.connected_nodes - self.described_nodes
for node in s:
self.graph.add_node(graphviz_id(node), label=node)
def write_to_file(self, filename_dot):
f = open(filename_dot, "w")
f.write(self.graph.string())
print("dot file created: " + filename_dot)
def visualize(self, filename, namespaceList=None):
self.graph.layout(prog="dot")
self.graph.draw(filename)
if filename.endswith(".svg"):
self._add_links_to_svg_file(filename, namespaceList)
print("graphic file created: " + filename)
def _add_links_to_svg_file(self, output, namespaceList=None):
# SVG Datei anpassen
svg_string = open(output).read()
# Titel der SVG Datei anpassen
svg_string = svg_string.replace("%3", output)
# Hyperlinks mit den Internetseiten hinzufügen
for ns in namespaceList:
namespace = str(ns[0]) # Präfix des Namespaces
url = str(ns[1]) # URL des Namespaces
regex_str = """%s:(\w+)""" % namespace
regex = re.compile(regex_str)
svg_string = regex.sub("""<a xlink:href='%s\\1'>%s:\\1</a>""" % (url, namespace), svg_string)
# Datei schreiben
svg_file = open(output, "w")
svg_file.write(svg_string)
svg_file.close()