本文整理汇总了Python中networkx.to_pydot函数的典型用法代码示例。如果您正苦于以下问题:Python to_pydot函数的具体用法?Python to_pydot怎么用?Python to_pydot使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了to_pydot函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_tree
def parse_tree(self, string, explicit=False, display=False):
'''
Returns graph representation of the equation tree of string,
as a networkx graph.
If explicit is True, then '-x' -> '0-x'
'''
stack, indices = self.parse(string)
tree = EquationTreeParser._create_tree(stack, indices)
if explicit:
idx = -1
for node, data in tree.nodes(data=True):
if data['label'] == '-' and len(tree[node]) == 1:
nbr = tree[node].keys()[0]
tree.remove_edge(node, nbr)
tree.add_node(idx, label='0')
tree.add_edge(node, idx, label='left')
tree.add_edge(node, nbr, label='right')
idx -= 1
if display:
_, image_path = tempfile.mkstemp()
pydot_graph = nx.to_pydot(tree)
pydot_graph.write_png(image_path)
cv2.imshow('equation tree', cv2.imread(image_path))
cv2.waitKey()
cv2.destroyAllWindows()
return tree
示例2: build_graph
def build_graph(self, G):
G.add_edge("A", "B")
G.add_edge("A", "C")
G.add_edge("B", "C")
G.add_edge("A", "D")
G.add_node("E")
return G, nx.to_pydot(G)
示例3: neato_from_networkx
def neato_from_networkx( g, min_node_size = 0.5, max_node_size = 2.0, min_edge_width = 1.0, max_edge_width = 5.0, legend_attribute=None, label_nodes_directly = False ) :
d = nx.to_pydot( g )
d.set_overlap(False)
# normalize node size
nodewidths = array( [float(n.get_width()) for n in d.get_nodes()] )
# done this way in case input has all the same size to avoid divide by zero
node_range = (nodewidths.max() - nodewidths.min())/(max_node_size - min_node_size)
for n in d.get_nodes() :
n.set_width( min_node_size + (float(n.get_width()) - nodewidths.min()) / node_range )
n.set_fixedsize( "true" )
n.set_shape('circle')
# normalize edge width
edge_widths = array( [float(e.get_penwidth()) for e in d.get_edges()] )
edge_width_range = (edge_widths.max() - edge_widths.min())/(max_edge_width - min_edge_width)
for e in d.get_edges() :
e.set_penwidth( min_edge_width + (float(e.get_penwidth()) - edge_widths.min() )/edge_width_range )
# if the legend attribute is set, create a legend node
if label_nodes_directly :
if legend_attribute == None :
legend_attribute = 'labelval'
for n in d.get_nodes() :
n.set_label( n.get_attributes()[legend_attribute] )
else :
legend = pydot.Node( "legend" )
nodelist = [n.get_label()+": "+n.get_attributes()[legend_attribute] for n in d.get_nodes()]
nodelist.sort( lambda a,b : cmp( int( a.split(':')[0] ), int (b.split(':')[0] ) ))
legend.set_label( "\l".join([x for x in nodelist])+"\l" )
legend.set_shape("box")
d.add_node(legend)
return d
示例4: visualize_mcts_tree
def visualize_mcts_tree(mcts, depth, filename):
"""
Creates a small subgraph for visualization with a
number of levels equal to 2 + depth labelled with the
MCTS values from mcts and saves it as filename.png
"""
# Find root of the MCTS tree
mcts_root = nx.topological_sort(mcts.digraph)[0]
# root = GameState()
subgraph = nx.DiGraph()
# Don't include the empty board (the root) in the graphs
# for first_move in mcts.digraph.successors(root):
print(mcts_root)
print(type(mcts_root))
for first_move in mcts.digraph.successors(mcts_root):
add_edges(mcts.digraph, subgraph, first_move, depth)
dot_graph = nx.to_pydot(subgraph)
for node in dot_graph.get_nodes():
attr = node.get_attributes()
try:
node.set_label('{}{}/{}\n{:.2f}'.format(attr['state'],
int(attr['w']),
int(attr['n']),
float(attr['uct'])))
except KeyError:
pass
dot_graph.set_graph_defaults(fontname='Courier')
dot_graph.set_rankdir('LR')
dot_graph.write_png('{}.png'.format(filename))
示例5: pydot_checks
def pydot_checks(self, G):
G.add_edge('A','B')
G.add_edge('A','C')
G.add_edge('B','C')
G.add_edge('A','D')
G.add_node('E')
P = nx.to_pydot(G)
G2 = G.__class__(nx.from_pydot(P))
assert_graphs_equal(G, G2)
fname = tempfile.mktemp()
assert_true( P.write_raw(fname) )
Pin = pydotplus.graph_from_dot_file(fname)
n1 = sorted([p.get_name() for p in P.get_node_list()])
n2 = sorted([p.get_name() for p in Pin.get_node_list()])
assert_true( n1 == n2 )
e1=[(e.get_source(),e.get_destination()) for e in P.get_edge_list()]
e2=[(e.get_source(),e.get_destination()) for e in Pin.get_edge_list()]
assert_true( sorted(e1)==sorted(e2) )
Hin = nx.drawing.nx_pydot.read_dot(fname)
Hin = G.__class__(Hin)
assert_graphs_equal(G, Hin)
示例6: dump
def dump(self, output=False):
"""Prints out network and returns networkx graph
Prints the devices, links, and flows associated with the network, and
returns a pydot object with the network graph.
Parameters
----------
output : boolean, optional
Specifies whether to print the network information (the default is
False).
Returns
-------
pydot
pydot object containing the network graph
"""
# Print network information if output is True
if output:
print "Devices:\n"
for device_id in self.devices:
print self.devices[device_id]
print "Links:\n"
for link_id in self.links:
print self.links[link_id]
print "Flows:\n"
for flow_id in self.flows:
print self.flows[flow_id]
# Convert the graph to a pydot object and return
return nx.to_pydot(self.g)
示例7: get_dot
def get_dot(G_orig):
"""Change labels and colors to be presented with graphviz"""
G = G_orig.copy()
cluster_networks.relabel_graph(G)
tr = {}
for node in G.nodes_iter():
tr[node] = '"{}"'.format(node)
nx.relabel_nodes(G, tr, copy=False)
for node in G.nodes_iter():
label = str(node)
if len(label) > MAX_LABEL:
label = u'{}..."'.format(label[:MAX_LABEL])
G.node[node]['label'] = label
for node in cluster_networks.get_leaf_nodes(G):
G.node[node]['color'] = "blue"
for node in cluster_networks.hybrid_nodes(G):
G.node[node]['color'] = "#7BFF74" # light green
G.node[node]['style'] = 'filled'
for node in cluster_networks.get_root_nodes(G):
G.node[node]['color'] = "orange"
for node in cluster_networks.problematic_treechild_nodes(G):
G.node[node]['color'] = "#FF77EB" # light pink
G.node[node]['style'] = 'filled'
for u, v in cluster_networks.removable_edges(G):
G.edge[u][v]['color'] = "red"
for root in cluster_networks.get_root_nodes(G):
G.node[root]['label'] = '"R"'
dot = nx.to_pydot(G).to_string()
return dot.strip()
示例8: _graph2pydot
def _graph2pydot(graph, wrap=10, tikz=False,
rankdir='TB'):
"""Convert (possibly labeled) state graph to dot str.
@type graph: L{LabeledDiGraph}
@rtype: str
"""
pydot = import_pydot()
if pydot is None:
return None
dummy_nx_graph = nx.MultiDiGraph()
_states2dot_str(graph, dummy_nx_graph, wrap=wrap, tikz=tikz,
rankdir=rankdir)
_transitions2dot_str(graph.transitions, dummy_nx_graph, tikz=tikz)
pydot_graph = nx.to_pydot(dummy_nx_graph)
_place_initial_states(graph, pydot_graph, tikz)
pydot_graph.set_overlap('false')
#pydot_graph.set_size('"0.25,1"')
#pydot_graph.set_ratio('"compress"')
pydot_graph.set_nodesep(0.5)
pydot_graph.set_ranksep(0.1)
return pydot_graph
示例9: build_graph
def build_graph(self, G):
G.add_edge('A','B')
G.add_edge('A','C')
G.add_edge('B','C')
G.add_edge('A','D')
G.add_node('E')
return G, nx.to_pydot(G)
示例10: dot_graph
def dot_graph(filename='conversions'):
# Edges from Convert
dg = nx.DiGraph()
for a, b in convert.graph.edges():
cost = convert.graph.edge[a][b]['cost']
dg.add_edge(cls_name(a), cls_name(b),
cost=cost,
penwidth=max(log(1./(cost + 0.06)), 1))
# Edges from Append
for a, b in append.funcs:
if b is not object and a != b:
dg.add_edge(cls_name(b), cls_name(a), color='blue')
# Color edges
for n in convert.graph.nodes() + list(pluck(0, append.funcs)):
if issubclass(n, tuple(ooc_types)):
dg.node[cls_name(n)]['color'] = 'red'
# Convert to pydot
p = nx.to_pydot(dg)
p.set_overlap(False)
p.set_splines(True)
with open(filename + '.dot', 'w') as f:
f.write(p.to_string())
os.system('neato -Tpdf %s.dot -o %s.pdf' % (filename, filename))
print("Writing graph to %s.pdf" % filename)
os.system('neato -Tpng %s.dot -o %s.png' % (filename, filename))
print("Writing graph to %s.png" % filename)
示例11: drawGraph
def drawGraph(self, key=None, filename="graph", format="pdf"):
graph = self.graphs.get(key)
if( not graph ):
return
if( graph.number_of_nodes() > 1 ):
ag = nx.to_pydot(graph)
ag.write("%s.%s"%(filename,format),format=format)
示例12: to_pydot
def to_pydot(self, detailed=False):
"""Create GraphViz dot string from given AST.
@type ast: L{ASTNode}
@rtype: str
"""
g = ast_to_labeled_graph(self, detailed)
return nx.to_pydot(g)
示例13: graph
def graph(self, out_file=None):
if out_file is None:
doc_dir = self.config["dir"].get("doc")
out_file = os.path.join(doc_dir, "pipeline_viz.png")
if file_exists(out_file):
return out_file
pd = nx.to_pydot(self.dag)
pd.write_png(out_file, prog="dot")
示例14: plotGraph
def plotGraph(self):
cntxt = self.context["disease"]
g = cntxt.getDocumentGraph()
ag = nx.to_pydot(g, strict=True)
gfile = os.path.join(self.save_dir,
"report_%s_unc%s_%s_critical.pdf"%(self.proc_category,
self.allow_uncertainty,
self.currentCase))
ag.write(gfile,format="pdf")
示例15: write_networkx_to_dot
def write_networkx_to_dot(dg, filename='mydask'):
import os
p = nx.to_pydot(dg)
p.set_rankdir('BT')
with open(filename + '.dot', 'w') as f:
f.write(p.to_string())
os.system('dot -Tpdf %s.dot -o %s.pdf' % (filename, filename))
os.system('dot -Tpng %s.dot -o %s.png' % (filename, filename))
print("Writing graph to %s.pdf" % filename)