def output_clustered_graph(graph, name, clustering):
"""Will ommit edge labels
"""
# Create AGraph via networkx
G = nx.DiGraph()
G.add_nodes_from(graph.nodes())
G.add_edges_from(graph.edges())
A = to_agraph(G)
tableau20 = [ '#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78',
'#2ca02c', '#98df8a', '#d62728', '#ff9896',
'#9467bd', '#c5b0d5', '#8c564b', '#c49c94',
'#e377c2', '#f7b6d2', '#7f7f7f', '#c7c7c7',
'#bcbd22', '#dbdb8d', '#17becf', '#9edae5' ]
clist = [ tableau20[i*2] for i in range(0, len(tableau20)/2)]
i = 0
for c in clustering:
A.add_subgraph(c, name='cluster_%d' % i, color=clist[i % len(clist)])
i += 1
name = 'graphs/%s.png' % name
A.write(name + '.dot')
A.draw(name, prog="dot")
python类AGraph()的实例源码
def _profile_from_parser(
parser,
graph_filename=DEFAULT_GRAPH_FILENAME,
node_threshold=DEFAULT_NODE_THRESHOLD,
edge_threshold=DEFAULT_EDGE_THRESHOLD,
view=DEFAULT_VIEW,
colour_nodes_by_selftime=DEFAULT_COLOUR_NODES_BY_SELFTIME):
# Parse pstats and prune graph based on thresholds
profile = parser.parse()
profile.prune(
node_threshold,
edge_threshold,
colour_nodes_by_selftime=colour_nodes_by_selftime)
# Convert graph to dot format
dot_file = StringIO()
dot = gprof2dot.DotWriter(dot_file)
dot.graph(profile, theme=gprof2dot.themes['color'])
# Convert dot to image
graph = pygraphviz.AGraph(string=dot_file.getvalue())
graph.draw(graph_filename, prog='dot')
# Open image
if view:
_view_file(graph_filename)
def buildGraph(tn,entityname):
A=pgv.AGraph(directed=True,strict=True)
entities=tn.Entities;
entity= entities[entityname];
nodes={};
addNode(A,entity,nodes);
A.graph_attr['epsilon']='0.001'
print (A.string()) # print dot file to standard output
A.write('foo.dot')
A.layout('dot') # layout with dot
A.draw('foo.png') # write to file
def draw_binary_tree(Tree, correlation, c='none'):
A = pg.AGraph(directed=True, strict=True)
level = 0
queue = [Tree.tree]
while queue:
node = queue.pop(0)
#node_string = str(node.label) + '\n' + str(Tree.generate_bt_stats(node))
node_string = str(node.ground_truth) + '\n' + str(Tree.generate_bt_stats(node))
level += 1
if node.get_left() is not None:
queue.append(node.get_left())
child_string = str(node.get_left().ground_truth) + '\n' + str(Tree.generate_bt_stats(node.get_left()))
A.add_edge(node_string, child_string)
if node.get_right() is not None:
queue.append(node.get_right())
child_string = str(node.get_right().ground_truth) + '\n' + str(Tree.generate_bt_stats(node.get_right()))
A.add_edge(node_string, child_string)
if level >= cfg.max_tree_size:
break
dot_path = util.generate_meta_path(Tree.system_name, 'dot', c)
util.ensure_path_exists(dot_path)
A.write('{}{} BT.dot'.format(dot_path, Tree.system_name))
A.layout(prog='dot')
A.draw('{}{} BT Score={}.png'.format(dot_path, Tree.system_name, correlation))
print "[clustering] : Created n-ary tree at path {}.".format('{}{} BT Score={}.png'.format(dot_path,
Tree.system_name,
correlation))
def generate_dot(fab_dims, CLBs, CBr, CBb, SB, paths, filename):
G = pgv.AGraph(name=filename, directed=True)
#G.node_attr['fixedsize']='true'
G.node_attr['shape'] = 'box'
create_all_CLBs(fab_dims, CLBs, G)
for cb in CBr:
pos, name = parse_name(cb, (__bias_amount,0))
G.add_node(name)
n = G.get_node(name)
n.attr['pos'] = '{},{}!'.format(__scale_factor*pos[0], __scale_factor*pos[1])
for cb in CBb:
pos, name = parse_name(cb, (0,__bias_amount))
G.add_node(name)
n = G.get_node(name)
n.attr['pos'] = '{},{}!'.format(__scale_factor*pos[0], __scale_factor*pos[1])
for s in SB:
pos, name = parse_name(s, (__bias_amount,__bias_amount))
G.add_node(name)
n = G.get_node(name)
n.attr['pos'] = '{},{}!'.format(__scale_factor*pos[0], __scale_factor*pos[1])
#now make connections
for path in paths:
for i in range(0, len(path)-1):
if len(path[i]) > __cutoff:
n1 = path[i][0:__cutoff+1]
else:
n1 = path[i]
if len(path[i+1]) > __cutoff:
n2 = path[i+1][0:__cutoff+1]
else:
n2 = path[i+1]
G.add_edge(n1, n2)
#write to file
G.write(filename)
def from_file(file_name):
return from_graph(pg.AGraph(file_name))
def generate_dot(fab_dims, CLBs, CBr, CBb, SB, paths, filename):
G = pgv.AGraph(name=filename, directed=True)
#G.node_attr['fixedsize']='true'
G.node_attr['shape'] = 'box'
create_all_CLBs(fab_dims, CLBs, G)
for cb in CBr:
pos, name = parse_name(cb, (__bias_amount,0))
G.add_node(name)
n = G.get_node(name)
n.attr['pos'] = '{},{}!'.format(__scale_factor*pos[0], __scale_factor*pos[1])
for cb in CBb:
pos, name = parse_name(cb, (0,__bias_amount))
G.add_node(name)
n = G.get_node(name)
n.attr['pos'] = '{},{}!'.format(__scale_factor*pos[0], __scale_factor*pos[1])
for s in SB:
pos, name = parse_name(s, (__bias_amount,__bias_amount))
G.add_node(name)
n = G.get_node(name)
n.attr['pos'] = '{},{}!'.format(__scale_factor*pos[0], __scale_factor*pos[1])
#now make connections
for path in paths:
for i in range(0, len(path)-1):
if len(path[i]) > __cutoff:
n1 = path[i][0:__cutoff+1]
else:
n1 = path[i]
if len(path[i+1]) > __cutoff:
n2 = path[i+1][0:__cutoff+1]
else:
n2 = path[i+1]
G.add_edge(n1, n2)
#write to file
G.write(filename)
def from_file(file_name):
return from_graph(pg.AGraph(file_name))
def _render(self, costs=False, word_probs=False, highlight_best=False):
from pygraphviz import AGraph
graph = AGraph(directed=True)
for node_id, node_label in self.nodes.iteritems():
attributes = self._node_attr(node_id, costs=costs, word_probs=word_probs)
graph.add_node(node_id, **attributes)
for (parent_node_id, child_node_id) in self.edges:
graph.add_edge(parent_node_id, child_node_id)
self.graph = graph
if highlight_best:
self._highlight_best()
def graphviz(self, root_id=None):
g = pgv.AGraph(directed='True')
for o_node in self.ontology_term_nodes:
g.add_node(o_node.term_id, shape='polygon')
#g.add_edge(self.id_to_term[curr_id].name, self.id_to_term[sub_id].name)
return str(g)
def dict_to_dot(dict_G, name=''):
dict_G = dict(dict_G)
name = str(name)
nodes = dict_G.keys()
G = pgv.AGraph(name=name, label=name, strict=False, directed=True, rankdir="LR")
x_dim, y_dim = 0.1, 0.1
tail,adir,ahlen = 'dot','both',0.62
arc_descriptor_shape = 'plain'
node_shape = 'egg'
arc_shape = 'plain'
arc_arrow_head = 'normal'
arc_arrow_tail = 'dot'
arc_mid = 'none'
arc_dir = 'both'
for node in nodes:
G.add_node(node.uid,label=node_to_label(node))
arcs = dict_G[node]
for arc in arcs:
arc_id = arc_to_id(arc)
G.add_node(arc_id,shape=arc_descriptor_shape,label=arc_to_label(arc),width=x_dim,height=y_dim)
G.add_edge(node.uid,arc_id,len=ahlen,dir=arc_dir,arrowtail=arc_arrow_tail,arrowhead=arc_mid)
G.add_edge(arc_id,arc.toNode.uid,shape=arc_shape,arrowtail=arc_mid,arrowhead=arc_arrow_head)
return G
def dot_to_file(dot_G, name='out', env='./env'):
G = dot_G.copy()
env = os.path.abspath(env)
env_dot = os.path.join(env,'dot')
env_img = os.path.join(env,'img')
layout_prog = 'dot'
dot_suffix = 'dot'
img_suffix = 'png'
dot_G.graph_attr.update(name = name)
dot_G.graph_attr.update(label = name)
if (debug):
# print to screen
print(G.string())
if not os.path.exists(env_dot):
os.makedirs(env_dot)
if not os.path.exists(env_img):
os.makedirs(env_img)
G.layout(prog=layout_prog)
dot_fname = os.path.join(env_dot, name +'.' + str(dot_suffix))
img_fname = os.path.join(env_img, name + '.' + str(img_suffix))
G.write(dot_fname)
if (debug):
print("Wrote " + str(dot_fname))
# create a new graph from file
G = pgv.AGraph(dot_fname)
G.layout(prog=layout_prog)
G.draw(img_fname)
if(debug):
print("Wrote " + str(img_fname))
def build_with_parents(self, envos=None):
"""Given a list of ENVO terms, build a simple network with
all the keys and all the parents."""
# Testing mode #
if envos is None: envos = onotology.test_envos
# New graph #
g = pygraphviz.AGraph(directed=True)
# Main loop #
for e in envos:
g.add_node(e)
# Return #
return g
def print_tree(self, node = None):
if node is None:
#?????
import pygraphviz
self.printer = pygraphviz.AGraph(directed = True, strict = False)
#????
self.printer.node_attr['shape'] = 'circle'
self.printer.node_attr['color'] = 'red'
self.printer.node_attr['fontcolor'] = 'white'
self.printer.node_attr['style'] = 'filled'
#?????
node = self.tree
self.printer.add_node(node.data, color = node.colour)
if node.Lchild or node.Rchild:
if node.Lchild:
#?????????????????
self.printer.add_node(node.Lchild.data, color = node.Lchild.colour)
#?????
self.printer.add_edge(node.data, node.Lchild.data, label = str(node.Lchild.father))
#?????
self.print_tree(node.Lchild)
else:
#?????????????
self.printer.add_node('Lchild ' + str(node.data), style = 'invis')
self.printer.add_edge(node.data, 'Lchild ' + str(node.data), style = 'invis')
if node.Rchild:
#?????????????????
self.printer.add_node(node.Rchild.data, color = node.Rchild.colour)
#?????
self.printer.add_edge(node.data, node.Rchild.data, label = str(node.Rchild.father))
#?????
self.print_tree(node.Rchild)
else:
#?????????????
self.printer.add_node('Rchild ' + str(node.data), style = 'invis')
self.printer.add_edge(node.data, 'Rchild ' + str(node.data), style = 'invis')
def main():
with open(GATE_FILE, "rb") as f:
gates_per_config = pickle.load(f)
for config_number, config in enumerate(configs):
gates = gates_per_config[config_number]
g = pgv.AGraph(directed=True)
for gate in gates:
gate.put_to_graph(g)
g.layout(prog='dot')
g.draw("wires_autogen_{}.pdf".format(config_number))
def processLines(self):
if len(self.lines) == 0:
return
self.identifier = self.lines[0][2:]
s = '\n'.join(self.lines)
A = AGraph()
G = A.from_string(s)
self.processGraph(G)
def __init__(self):
super(GraphvizWalker, self).__init__()
self.top_graph = pgv.AGraph(directed=True,
rankdir='LR',
packMode='clust',
splines='true'
)
self.stack = [self.top_graph]
self.node_count = 0
def bg_graph_model():
graph = pgv.AGraph(layout='dot', directed=True, strict=False, rankdir='LR')
subgraphs = dict()
for tablename in db.tables:
if hasattr(db[tablename],'_meta_graphmodel'):
meta_graphmodel = db[tablename]._meta_graphmodel
else:
meta_graphmodel = dict(group=request.application, color='#ECECEC')
group = meta_graphmodel['group'].replace(' ', '')
if group not in subgraphs:
subgraphs[group] = dict(meta=meta_graphmodel, tables=[])
subgraphs[group]['tables'].append(tablename)
graph.add_node(tablename, name=tablename, shape='plaintext',
label=table_template(tablename))
for n, key in enumerate(subgraphs.iterkeys()):
graph.subgraph(nbunch=subgraphs[key]['tables'],
name='cluster%d' % n,
style='filled',
color=subgraphs[key]['meta']['color'],
label=subgraphs[key]['meta']['group'])
for tablename in db.tables:
for field in db[tablename]:
f_type = field.type
if isinstance(f_type,str) and (
f_type.startswith('reference') or
f_type.startswith('list:reference')):
referenced_table = f_type.split()[1].split('.')[0]
n1 = graph.get_node(tablename)
n2 = graph.get_node(referenced_table)
graph.add_edge(n1, n2, color="#4C4C4C", label='')
graph.layout()
if not request.args:
response.headers['Content-Type'] = 'image/png'
return graph.draw(format='png', prog='dot')
else:
response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0)
if request.args(0) == 'dot':
return graph.string()
else:
return graph.draw(format=request.args(0), prog='dot')
def bg_graph_model():
graph = pgv.AGraph(layout='dot', directed=True, strict=False, rankdir='LR')
subgraphs = dict()
for tablename in db.tables:
if hasattr(db[tablename],'_meta_graphmodel'):
meta_graphmodel = db[tablename]._meta_graphmodel
else:
meta_graphmodel = dict(group=request.application, color='#ECECEC')
group = meta_graphmodel['group'].replace(' ', '')
if group not in subgraphs:
subgraphs[group] = dict(meta=meta_graphmodel, tables=[])
subgraphs[group]['tables'].append(tablename)
graph.add_node(tablename, name=tablename, shape='plaintext',
label=table_template(tablename))
for n, key in enumerate(subgraphs.iterkeys()):
graph.subgraph(nbunch=subgraphs[key]['tables'],
name='cluster%d' % n,
style='filled',
color=subgraphs[key]['meta']['color'],
label=subgraphs[key]['meta']['group'])
for tablename in db.tables:
for field in db[tablename]:
f_type = field.type
if isinstance(f_type,str) and (
f_type.startswith('reference') or
f_type.startswith('list:reference')):
referenced_table = f_type.split()[1].split('.')[0]
n1 = graph.get_node(tablename)
n2 = graph.get_node(referenced_table)
graph.add_edge(n1, n2, color="#4C4C4C", label='')
graph.layout()
if not request.args:
response.headers['Content-Type'] = 'image/png'
return graph.draw(format='png', prog='dot')
else:
response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0)
if request.args(0) == 'dot':
return graph.string()
else:
return graph.draw(format=request.args(0), prog='dot')
def bg_graph_model():
graph = pgv.AGraph(layout='dot', directed=True, strict=False, rankdir='LR')
subgraphs = dict()
for tablename in db.tables:
if hasattr(db[tablename],'_meta_graphmodel'):
meta_graphmodel = db[tablename]._meta_graphmodel
else:
meta_graphmodel = dict(group=request.application, color='#ECECEC')
group = meta_graphmodel['group'].replace(' ', '')
if group not in subgraphs:
subgraphs[group] = dict(meta=meta_graphmodel, tables=[])
subgraphs[group]['tables'].append(tablename)
graph.add_node(tablename, name=tablename, shape='plaintext',
label=table_template(tablename))
for n, key in enumerate(subgraphs.iterkeys()):
graph.subgraph(nbunch=subgraphs[key]['tables'],
name='cluster%d' % n,
style='filled',
color=subgraphs[key]['meta']['color'],
label=subgraphs[key]['meta']['group'])
for tablename in db.tables:
for field in db[tablename]:
f_type = field.type
if isinstance(f_type,str) and (
f_type.startswith('reference') or
f_type.startswith('list:reference')):
referenced_table = f_type.split()[1].split('.')[0]
n1 = graph.get_node(tablename)
n2 = graph.get_node(referenced_table)
graph.add_edge(n1, n2, color="#4C4C4C", label='')
graph.layout()
if not request.args:
response.headers['Content-Type'] = 'image/png'
return graph.draw(format='png', prog='dot')
else:
response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0)
if request.args(0) == 'dot':
return graph.string()
else:
return graph.draw(format=request.args(0), prog='dot')