本文整理汇总了Python中pygraphviz.AGraph.add_subgraph方法的典型用法代码示例。如果您正苦于以下问题:Python AGraph.add_subgraph方法的具体用法?Python AGraph.add_subgraph怎么用?Python AGraph.add_subgraph使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygraphviz.AGraph
的用法示例。
在下文中一共展示了AGraph.add_subgraph方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import add_subgraph [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: cm_json_to_graph
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import add_subgraph [as 别名]
def cm_json_to_graph(im_json):
"""Return pygraphviz Agraph from Kappy's contact map JSON.
Parameters
----------
im_json : dict
A JSON dict which contains a contact map generated by Kappy.
Returns
-------
graph : pygraphviz.Agraph
A graph representing the contact map.
"""
cmap_data = im_json['contact map']['map']
# Initialize the graph
graph = AGraph()
# In this loop we add sites as nodes and clusters around sites to the
# graph. We also collect edges to be added between sites later.
edges = []
for node_idx, node in enumerate(cmap_data):
sites_in_node = []
for site_idx, site in enumerate(node['node_sites']):
# We map the unique ID of the site to its name
site_key = (node_idx, site_idx)
sites_in_node.append(site_key)
graph.add_node(site_key, label=site['site_name'], style='filled',
shape='ellipse')
# Each port link is an edge from the current site to the
# specified site
if not site['site_type'] or not site['site_type'][0] == 'port':
continue
for port_link in site['site_type'][1]['port_links']:
edge = (site_key, tuple(port_link))
edges.append(edge)
graph.add_subgraph(sites_in_node,
name='cluster_%s' % node['node_type'],
label=node['node_type'])
# Finally we add the edges between the sites
for source, target in edges:
graph.add_edge(source, target)
return graph
示例3: plot
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import add_subgraph [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
示例4: get_dot
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import add_subgraph [as 别名]
def get_dot(self, labeller=None):
self.labeller = labeller
a_graph = AGraph(directed=True)
nx_graph = self.graph.nx_graph
# TODO: Add some default stuff?
# a_graph.graph_attr.update(N.graph.get('graph',{}))
# a_graph.node_attr.update(N.graph.get('node',{}))
# a_graph.edge_attr.update(N.graph.get('edge',{}))
structural_nodes = []
output_nodes = []
input_nodes = []
# First, add nodes
for node in nx_graph.nodes():
name, attrs = self.get_node_attributes(node)
if self.graph.is_input(node):
input_nodes.append(name)
elif self.graph.is_structural(node):
structural_nodes.append(name)
elif self.graph.is_output(node):
output_nodes.append(name)
# Keep a reference to the original node
a_graph.add_node(name, **attrs)
# We need to add subgraphs to cluster stuff on rank
sub = a_graph.add_subgraph(input_nodes, name='input')
sub.graph_attr['rank'] = 'source'
sub = a_graph.add_subgraph(structural_nodes, name='structural')
sub.graph_attr['rank'] = 'same'
sub = a_graph.add_subgraph(output_nodes, name='output')
sub.graph_attr['rank'] = 'sink'
# Now add edges
for u, v, edgedata in nx_graph.edges_iter(data=True):
attrs = {}
a_graph.add_edge(self.graph.node_to_name(u),
self.graph.node_to_name(v),
**attrs)
return a_graph
示例5: convert
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import add_subgraph [as 别名]
def convert(graph, desired_ns=[], exclude_ns=[]):
# graph.parse('rdf-schema.ttl', format='turtle')
# network.feedFactsToAdd(generateTokenSet(graph))
# for n in network.inferredFacts.triples((None, None, None)):
# graph.add(n)
agraph = AGraph(directed=True, clusterrank="global", rankdir="LR")
namespaces = {}
nsm = graph.namespace_manager
deferred_resources = set()
included_resources = set()
def prefix(ressource):
return nsm.qname(ressource).split(':')[0]
def add_ressource(ressource):
if ressource not in included_resources:
qname = nsm.qname(ressource)
prefix = qname.split(':')[0]
shape = 'rect' if (
ressource, RDF.type, OWL.Class) in graph else 'oval'
color = 'black' if prefix in desired_ns else 'grey'
if prefix in namespaces:
namespaces[prefix].add_node(qname, shape=shape, color=color)
else:
agraph.add_node(qname, shape=shape, color=color)
included_resources.add(ressource)
if ressource in deferred_resources:
deferred_resources.remove(ressource)
def add_edge(r1, r2, **kwargs):
pr1, pr2 = prefix(r1), prefix(r2)
if pr1 in exclude_ns or pr2 in exclude_ns:
return
if pr1 in desired_ns or pr2 in desired_ns:
add_ressource(r1)
add_ressource(r2)
agraph.add_edge(nsm.qname(r1), nsm.qname(r2), **kwargs)
for kprefix, namespace in graph.namespaces():
namespaces[kprefix] = agraph.add_subgraph(
name="cluster_"+kprefix, color="grey")
for k in graph.subjects(RDF.type, OWL.Class):
if isinstance(k, BNode):
continue
qname = nsm.qname(k)
kprefix = prefix(k)
if kprefix in exclude_ns:
continue
elif kprefix in desired_ns:
add_ressource(k)
else:
deferred_resources.add(k)
for (s, p, o) in chain(graph.triples((None, RDFS.subClassOf, None)),
graph.triples((None, OWL.subClassOf, None))):
if isinstance(s, BNode) or isinstance(o, BNode):
continue
add_edge(s, o, arrowhead='empty', color="blue")
prop_types = [OWL.Property, OWL.AnnotationProperty, OWL.DatatypeProperty,
OWL.AsymmetricProperty, OWL.ObjectProperty,
OWL.FunctionalProperty, OWL.InverseFunctionalProperty]
properties = set()
for prop in prop_types:
properties.update(graph.subjects(RDF.type, prop))
for k in properties:
if isinstance(k, BNode):
continue
qname = nsm.qname(k)
kprefix = prefix(k)
if kprefix in exclude_ns:
continue
elif kprefix in desired_ns:
add_ressource(k)
else:
deferred_resources.add(k)
for (s, p, o) in chain(graph.triples((None, RDFS.subPropertyOf, None)),
graph.triples((None, OWL.subPropertyOf, None))):
if isinstance(s, BNode) or isinstance(o, BNode):
continue
add_edge(s, o, arrowhead='empty', color="blue")
for (s, p, o) in graph.triples((None, OWL.equivalentClass, None)):
if isinstance(s, BNode) or isinstance(o, BNode):
continue
add_edge(s, o, arrowhead="odot", arrowtail="odot", color="blue")
for (s, p, o) in graph.triples((None, RDFS.domain, None)):
if isinstance(s, BNode):
continue
if isinstance(o, BNode):
for o2 in graph.objects(o, OWL.unionOf):
for o3 in list_content(o2, graph):
add_edge(o3, s, arrowhead="open")
for o2 in graph.objects(o, OWL.intersectionOf):
for o3 in list_content(o2, graph):
add_edge(o3, s, arrowhead="open")
continue
add_edge(o, s, arrowhead="open")
for (s, p, o) in graph.triples((None, RDFS.range, None)):
if isinstance(s, BNode):
continue
#.........这里部分代码省略.........
示例6: dot_layout
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import add_subgraph [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():
#.........这里部分代码省略.........
示例7: __init__
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import add_subgraph [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()
示例8: dot_layout
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import add_subgraph [as 别名]
def dot_layout(cy_elements):
"""
Get a CyElements object and augment it (in-place) with positions,
widths, heights, and spline data from a dot based layout.
Returns the object.
"""
elements = cy_elements.elements
g = AGraph(directed=True, strict=False)
# make transitive relations appear top to bottom
# TODO: make this not specific to leader example
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
e["data"]["obj"] in ('reach', 'le')
]
elements = topological_sort(elements, order, lambda e: e["data"]["id"])
# add nodes to the graph
for e in elements:
if e["group"] == "nodes":
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":
g.add_edge(
e["data"]["source"],
e["data"]["target"],
e["data"]["id"],
weight=weight.get(e["data"]["obj"], 0),
#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:
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],
)
# now get positions, heights, widths, and bsplines
g.layout(prog='dot')
for e in elements:
if e["group"] == "nodes":
attr = g.get_node(e["data"]["id"]).attr
e["position"] = _to_position(attr['pos'])
e["data"]["width"] = 72 * float(attr['width'])
e["data"]["height"] = 72 * float(attr['height'])
elif e["group"] == "edges":
attr = g.get_edge(e["data"]["source"], e["data"]["target"], e["data"]["id"]).attr
e["data"].update(_to_edge_position(attr['pos']))
g.draw('g.png')
return cy_elements