本文整理汇总了Python中pydot.Dot.add_node方法的典型用法代码示例。如果您正苦于以下问题:Python Dot.add_node方法的具体用法?Python Dot.add_node怎么用?Python Dot.add_node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pydot.Dot
的用法示例。
在下文中一共展示了Dot.add_node方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_state
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def plot_state(self, boxes, deltas, name = '', outdir = None):
""" Make a graph of a given state """
graph = Dot(graph_type='digraph', fontname="Verdana", size="10, 5", fixedsize= True)
i_box = 0
for box in boxes:
textcolor = 'white' if sum( [ self.color_chars.index(col) for col in self.plots_conf[box]['color'].split('#')[1] ] ) < 35 else 'black'
node_box = Node(box, style="filled", label = '<<font POINT-SIZE="10" color="'+textcolor+'">'+box+'<br/> '+
"%.7f" % round(deltas[i_box], 7)+'</font>>',
fillcolor = self.plots_conf[box]['color'], shape = self.plots_conf[box]['shape'])
i_box += 1
graph.add_node(node_box)
for box_from, boxes_to in self.Flux.iteritems():
for box_to, flux in boxes_to.iteritems():
if flux !=0:
if flux > 0:
edge = Edge(box_from, box_to, label = '<<font POINT-SIZE="10">'+str(flux)+'</font>>')
elif flux < 0:
edge = Edge(box_to, box_from, label = '<<font POINT-SIZE="10">'+str(flux)+'</font>>')
graph.add_edge(edge)
if outdir is None:
outdir = self.result_dir
outfile = outdir+'/state'+name+'.png'
graph.write_png(outfile)
logger.info('State has been saved to '+set_style(outfile, 'emph'))
示例2: save
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def save(self, cfg, filename, print_ir=False, format='dot', options=None):
"""Save basic block graph into a file.
"""
if options is None:
options = {}
try:
dot_graph = Dot(**self.graph_format)
# Add nodes.
nodes = {}
for bb in cfg.basic_blocks:
nodes[bb.address] = self._create_node(bb, cfg.name, print_ir, options)
dot_graph.add_node(nodes[bb.address])
# Add edges.
for bb_src in cfg.basic_blocks:
for bb_dst_addr, branch_type in bb_src.branches:
edge = self._create_edge(nodes[bb_src.address], nodes[bb_dst_addr], branch_type)
dot_graph.add_edge(edge)
# Save graph.
dot_graph.write("{}.{}".format(filename, format), format=format)
except Exception:
logger.error("Failed to save basic block graph: %s (%s)", filename, format, exc_info=True)
示例3: create_example_graph
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def create_example_graph():
g = Dot(graph_name="workflow: example",
labelloc="t", label="workflow: example", fontsize=18, fontcolor="blue")
g.set_node_defaults(shape="box", fontsize=12)
g.set_edge_defaults(fontsize=13, labeldistance=3)
n1 = Node(name="Start")
g.add_node(n1)
n2 = Node(name="StepTrueEnd", color="#04B45F")
g.add_node(n2)
n3 = Node(name="StepFalse")
g.add_node(n3)
n4 = Node(name="StepFalse2")
g.add_node(n4)
n5 = Node(name="StepFalse3End", color="#04B45F")
g.add_node(n5)
e1 = true_edge(n1, n2)
g.add_edge(e1)
e2 = false_edge(n1, n3)
g.add_edge(e2)
e3 = true_edge(n3, n4)
g.add_edge(e3)
e_back = false_edge(n4, n1, label="back if false")
g.add_edge(e_back)
e4 = true_edge(n4, n5)
g.add_edge(e4)
return g
示例4: get_session_svg
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def get_session_svg(viz_data):
"""Take session visualization data and return svg."""
graph = Dot('graphname', graph_type='digraph')
#loop create all nodes and store by id
node_dict = {}
for i, node_data in enumerate(viz_data['nodes']):
id = node_data['id']
node_dict[id] = str(i)
graph.add_node(Node(str(i)))
#add edges by links
for link_data in viz_data['links']:
snode = node_dict[viz_data['nodes'][link_data['source']]['id']]
tnode = node_dict[viz_data['nodes'][link_data['target']]['id']]
graph.add_edge(Edge(snode, tnode))
#get svg of graph
file = NamedTemporaryFile()
graph.write_svg(file.name)
svg = file.read()
file.close()
#f = open('/tmp/session/session.svg', 'w')
#f.write("%s\n" % svg)
#f.close()
return svg
示例5: handle
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def handle(self, filename=None, **options):
try:
from pydot import Dot, Edge, Node
except ImportError:
raise CommandError("need pydot python module ( apt-get install python-pydot )")
graph = Dot()
for status, description in STATUS_CHOICES:
graph.add_node(Node(
'status-%s' % status,
label='"%s (%s)"' %
(description.encode('utf-8'), status))
)
from sadiki.core.workflow import workflow
for transition_index in workflow.available_transitions():
transition = workflow.get_transition_by_index(transition_index)
graph.add_edge(Edge(
'status-%s'% transition.src,
'status-%s' % transition.dst,
label='"%s (%s)"' % (transition.comment.encode('utf-8'), transition.index),
style='solid' if transition.required_permissions else 'dashed',
))
if filename:
graph.write_png(filename)
else:
print graph.to_string()
示例6: save
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def save(self, filename, print_ir=False, format='dot'):
"""Save basic block graph into a file.
"""
node_format = {
'shape' : 'Mrecord',
'rankdir' : 'LR',
'fontname' : 'monospace',
'fontsize' : '9.0'
}
edge_format = {
'fontname' : 'monospace',
'fontsize' : '8.0'
}
edge_colors = {
'taken' : 'green',
'not-taken' : 'red',
'direct' : 'blue'
}
try:
# for each conneted component
for idx, gr in enumerate(networkx.connected_component_subgraphs(self._graph.to_undirected())):
graph = Dot(graph_type="digraph", rankdir="TB")
# add nodes
nodes = {}
for bb_addr in gr.node.keys():
dump = self._dump_bb(self._bb_by_addr[bb_addr], print_ir)
# html-encode colon character
dump = dump.replace("!", "!")
dump = dump.replace("#", "#")
dump = dump.replace(":", ":")
dump = dump.replace("{", "{")
dump = dump.replace("}", "}")
label = "{<f0> 0x%08x | %s}" % (bb_addr, dump)
nodes[bb_addr] = Node(bb_addr, label=label, **node_format)
graph.add_node(nodes[bb_addr])
# add edges
for bb_src_addr in gr.node.keys():
for bb_dst_addr, branch_type in self._bb_by_addr[bb_src_addr].branches:
graph.add_edge(Edge(nodes[bb_src_addr],
nodes[bb_dst_addr], label=branch_type, \
color=edge_colors[branch_type], **edge_format))
graph.write("%s_%03d.%s" % (filename, idx, format), format=format)
except Exception as err:
import traceback
import sys
print("[E] Error loading BARF (%s:%d) : '%s'" %
(__name__, sys.exc_traceback.tb_lineno, str(err)))
print("")
print(traceback.format_exc())
示例7: buildDependencyControlGraph
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def buildDependencyControlGraph(dependencies,sizes=[1,2],productionTarget=1.25):
from pydot import Dot, Node, Edge, Cluster
dgraph = Dot(graph_type='graph',fontname='Verdana',splines="line",maxiter="500")
#splines="line",
nodes = {}
edges = {}
for (controlMap,pvalue) in dependencies:
targetNames = []
size = len(controlMap)
if size not in sizes:
continue
for (targetName,cvalue) in controlMap.items():
#targetTag = "%s(%s)" % (targetName,cvalue)
targetTag = targetName
targetNames.append(targetTag)
if size not in nodes.keys():
nodes[size] = set()
nodes[size].add((targetName,cvalue))
edgeCombos = combinations(targetNames,2)
for value in edgeCombos:
key = list(value)
key.sort()
(e1,e2) = key
if (e1,e2) not in edges.keys() and (e2,e1) not in edges.keys():
edge = Edge(e1,e2)
edges[(e1,e2)] = edge
else:
#print "dup key %s %s" % (e1,e2)
pass
nodes = cleanNodeNames(nodes)
for (key,nodeValues) in nodes.items():
if key == 1:
ishape = "rectangle"
elif key == 2:
ishape = "oval"
elif key == 3:
ishape = "hexagon"
else:
ishape = "circle"
for (name,value) in nodeValues:
icolor = "black"
if value > 0:
icolor = "red"
if value < 0:
icolor = "green"
targetTag = "%s(%s)" % (name,value)
targetTag = name
dgraph.add_node(Node(targetTag,shape=ishape,color=icolor))
#print "Node: [%s] : size[%s] value[%s] shape[%s]" % (name,key,value,ishape)
for (key,edge) in edges.items():
dgraph.add_edge(edge)
return dgraph
示例8: visualize
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def visualize(graph, filename="graph.png", include_args=True, transitive=False):
data = to_graphviz(graph, transitive)
dot = Dot(graph_type="digraph")
for node in data["nodes"]:
fmt = format_edge(graph, node) if include_args else node
dot.add_node(Node(node, label=fmt))
for a, b in data["edges"]:
dot.add_edge(Edge(a, b))
dot.write_png(filename)
示例9: RenderSIPCollection
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def RenderSIPCollection(sipGraph, dot=None):
try:
from pydot import Node, Edge, Dot
except:
import warnings
warnings.warn("Missing pydot library", ImportWarning)
if not dot:
dot = Dot(graph_type='digraph')
dot.leftNodesLookup = {}
nodes = {}
for N, prop, q in sipGraph.query(
'SELECT ?N ?prop ?q { ?prop a magic:SipArc . ?N ?prop ?q . }',
initNs={u'magic': MAGIC}):
if MAGIC.BoundHeadPredicate in sipGraph.objects(
subject=N, predicate=RDF.type):
NCol = [N]
else:
NCol = Collection(sipGraph, N)
if q not in nodes:
newNode = Node(makeMD5Digest(q),
label=normalizeTerm(q, sipGraph),
shape='plaintext')
nodes[q] = newNode
dot.add_node(newNode)
bNode = BNode()
nodeLabel = ', '.join([normalizeTerm(term, sipGraph)
for term in NCol])
edgeLabel = ', '.join([var.n3()
for var in Collection(sipGraph,
first(sipGraph.objects(
prop, MAGIC.bindings)))])
markedEdgeLabel = ''
if nodeLabel in dot.leftNodesLookup:
bNode, leftNode, markedEdgeLabel = dot.leftNodesLookup[nodeLabel]
# print("\t", nodeLabel, edgeLabel,
# markedEdgeLabel, not edgeLabel == markedEdgeLabel
else:
leftNode = Node(makeMD5Digest(bNode),
label=nodeLabel, shape='plaintext')
dot.leftNodesLookup[nodeLabel] = (bNode, leftNode, edgeLabel)
nodes[bNode] = leftNode
dot.add_node(leftNode)
if not edgeLabel == markedEdgeLabel:
edge = Edge(leftNode,
nodes[q],
label=edgeLabel)
dot.add_edge(edge)
return dot
示例10: draw
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def draw(self, path: str, format: str = "raw") -> None:
node_aggr = {}
for node in self._nodes:
level = node.get_level()
label = node.get_label()
identifier = node.get_id()
if node_aggr.get(level) is None:
node_aggr[level] = {}
if level != 0:
gv_cluster = GVCluster(identifier)
gv_cluster.set("label", label)
node_aggr[level][identifier] = gv_cluster
else:
gv_node = GVNode(identifier)
gv_node.set("label", label)
node_aggr[level][identifier] = gv_node
gv_dot = GVDot()
gv_dot.set("ranksep", "1.0 equally")
if self._lable is not None:
gv_dot.set("label", self._lable)
for node in self._nodes:
level = node.get_level()
parent = node.get_parent()
parent_level = node.get_parent_level()
identifier = node.get_id()
if level != 0:
if parent is not None:
node_aggr[parent_level][parent].add_subgraph(node_aggr[level][identifier])
else:
gv_dot.add_subgraph(node_aggr[level][identifier])
else:
if parent is not None:
node_aggr[parent_level][parent].add_node(node_aggr[level][identifier])
else:
gv_dot.add_node(node_aggr[level][identifier])
for edge in self._edges:
label = edge.get_label()
gv_edge = GVEdge(edge.get_src(), edge.get_dst())
if label is not None:
gv_edge.set("label", edge.get_label())
gv_dot.add_edge(gv_edge)
gv_dot.write(path, format=format)
示例11: process_plan
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def process_plan(filename, plan):
graph = Dot()
teams = fetch_teams()
nodes = make_nodes(plan, teams)
for team_node in nodes:
graph.add_node(nodes[team_node])
for team in plan:
edges = graph_way(team, plan[team], nodes)
for edge in edges:
graph.add_edge(edge)
graph.set_prog("circo")
graph.write_png(filename)
示例12: draw
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def draw(self, prob, targetFile):
# Do the graphing stuff here...
# Root graph
g = Dot(graph_type="digraph", nodesep=2, overlap=False)
#g.set_edge_defaults(weight="0", minlen="10")
# Organise by adding constraints (adds edges too)
for constr in prob.constrs:
# Node for constraint
constrNode = Node(constr.name, shape="ellipse", style="filled", fillcolor = "#aaaaff")
constrNode.set_label(constr.name + ": " + constr.getTextFormula())
g.add_node(constrNode)
# Associated expressions
for expr in constr.exprs:
self.addNodesForChildren(g, expr, constr)
# Finally, render
#g.write_png("problem_structure.png", prog="dot")
g.write_png(targetFile, prog="neato")
示例13: renderNetwork
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def renderNetwork(network, nsMap={}):
"""
Takes an instance of a compiled ReteNetwork and a namespace mapping (for constructing QNames
for rule pattern terms) and returns a BGL Digraph instance representing the Rete network
#(from which GraphViz diagrams can be generated)
"""
# from FuXi.Rete import BuiltInAlphaNode
# from BetaNode import LEFT_MEMORY, RIGHT_MEMORY, LEFT_UNLINKING
dot = Dot(graph_type='digraph')
namespace_manager = NamespaceManager(Graph())
for prefix, uri in list(nsMap.items()):
namespace_manager.bind(prefix, uri, override=False)
visitedNodes = {}
edges = []
idx = 0
for node in list(network.nodes.values()):
if node not in visitedNodes:
idx += 1
visitedNodes[node] = generateBGLNode(
dot, node, namespace_manager, str(idx))
dot.add_node(visitedNodes[node])
nodeIdxs = {}
for node in list(network.nodes.values()):
for mem in node.descendentMemory:
if not mem:
continue
bNode = mem.successor
for bNode in node.descendentBetaNodes:
for idx, otherNode in enumerate([bNode.leftNode, bNode.rightNode]):
if node == otherNode and (node, otherNode) not in edges:
for i in [node, bNode]:
if i not in visitedNodes:
idx += 1
nodeIdxs[i] = idx
visitedNodes[i] = generateBGLNode(
dot, i, namespace_manager, str(idx))
dot.add_node(visitedNodes[i])
edge = Edge(visitedNodes[node],
visitedNodes[bNode],
label=idx == 0 and 'left' or 'right')
dot.add_edge(edge)
edges.append((node, bNode))
return dot
示例14: render_state_diagram
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def render_state_diagram(C_M, S_M, filename, depth=None):
tot_M = C_M + S_M
if depth:
reachable_states = find_reachable_states(tot_M, len(tot_M) - 1, depth)
reachable_states.add(len(tot_M) - 1)
else:
reachable_states = range(len(tot_M))
graph = Dot(graph_type="digraph", rankdir="LR")
nodes = [Node(str(i), shape="circle") for i in range(len(tot_M) + 1)]
nodes[-2].set_shape("point")
nodes[-1].set_shape("doublecircle")
for i in reachable_states:
graph.add_node(nodes[i])
graph.add_node(nodes[-1])
def _render_edges(M, color, end_state):
for i in reachable_states:
row_sum = sum(tot_M[i])
col_sum = sum(tot_M[:, i])
if not end_state:
for j in reachable_states:
elem = M[i, j]
if elem > 0:
if col_sum > 0:
prob = elem / col_sum
else:
prob = elem / row_sum
edge = Edge(nodes[i], nodes[j], label="%.2f" % prob, color=color)
graph.add_edge(edge)
else:
if row_sum < col_sum:
prob = (col_sum - row_sum) / col_sum
edge = Edge(nodes[i], nodes[-1], label="%.2f" % prob, color=color)
graph.add_edge(edge)
_render_edges(C_M, "blue", False)
_render_edges(S_M, "red", False)
_render_edges(None, "black", True)
graph.write_png(filename)
示例15: process_plan
# 需要导入模块: from pydot import Dot [as 别名]
# 或者: from pydot.Dot import add_node [as 别名]
def process_plan(filename, plan, names=True, with_dist=False, with_label=False):
graph = Dot(overlap="false", splines="true", esep=.2)
teams = fetch_teams()
distances = fetch_distances()
nodes = make_nodes(plan, teams, names)
for team_node in nodes:
graph.add_node(nodes[team_node])
for team in plan:
edges = graph_way(team, plan[team], nodes, distances, with_dist, with_label)
for edge in edges:
graph.add_edge(edge)
if with_dist:
graph.write_png(filename, prog="neato")
else:
graph.write_png(filename, prog="dot")