本文整理汇总了Python中pygraphviz.AGraph.get_node方法的典型用法代码示例。如果您正苦于以下问题:Python AGraph.get_node方法的具体用法?Python AGraph.get_node怎么用?Python AGraph.get_node使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygraphviz.AGraph
的用法示例。
在下文中一共展示了AGraph.get_node方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: to_dot
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_node [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)
示例2: draw_graph
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_node [as 别名]
def draw_graph(state_manager, filename):
graph = AGraph()
graph.node_attr["style"] = "filled"
graph.node_attr["shape"] = "circle"
graph.node_attr["fixedsize"] = "true"
graph.node_attr["width"] = 0.5
graph.node_attr["height"] = 0.5
# we add all nodes (keys = ID)
graph.add_nodes_from(state_manager.state.keys())
for var_id in state_manager.state:
# and for each of these nodes, we change color
node = graph.get_node(var_id)
node.attr["fillcolor"] = get_color(state_manager.state[var_id])
# finally, we add edges
for c in state_manager.constraints:
e = c.list_vars
graph.add_edge(e[0], e[1])
graph.write(filename)
示例3: convert
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_node [as 别名]
#.........这里部分代码省略.........
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
if isinstance(o, BNode):
for o2 in graph.objects(o, OWL.unionOf):
for o3 in list_content(o2, graph):
add_edge(s, o3, arrowhead="open")
for o2 in graph.objects(o, OWL.intersectionOf):
for o3 in list_content(o2, graph):
add_edge(s, o3, arrowhead="open")
continue
add_edge(s, o, arrowhead="open")
for (s, p, o) in graph.triples((None, OWL.inverseOf, None)):
if isinstance(s, BNode) or isinstance(o, BNode):
continue
if str(o) < str(s):
s, o = o, s
add_edge(o, s, arrowhead="crow", arrowtail="crow", dir="both")
for ressource in included_resources:
labels = graph.objects(ressource, RDFS.label)
en_labels = [l for l in labels if l.language == 'eng']
if en_labels:
label = en_labels[0]
qname = nsm.qname(ressource)
prefix, name = qname.split(':', 1)
if normalize_label(name) != normalize_label(label):
node = agraph.get_node(qname)
node.attr['label'] = "%s\n(%s)" % (qname, label)
return agraph
示例4: dot_layout
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_node [as 别名]
#.........这里部分代码省略.........
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():
top = float(sg.graph_attr["bb"].split(",")[3])
if top > y_origin:
y_origin = top
for e in elements:
if e["group"] == "nodes" and e["classes"] != "non_existing":
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":
if node_gt(e["data"]["source"], e["data"]["target"]):
attr = g.get_edge(e["data"]["target"], e["data"]["source"], e["data"]["id"]).attr
pos = attr["pos"]
pe = pos.split()
ppe = pe[1:]
ppe.reverse()
pos = " ".join([pe[0].replace("s", "e")] + ppe)
else:
attr = g.get_edge(e["data"]["source"], e["data"]["target"], e["data"]["id"]).attr
pos = attr["pos"]
e["data"].update(_to_edge_position(pos))
if edge_labels and e["data"]["label"] != "":
e["data"]["lp"] = _to_position(attr["lp"])
# g.draw('g.png')
if subgraph_boxes:
for sg in g.subgraphs():
box = cy_elements.add_shape(sg.name, classes="subgraphs")
coords = _to_coord_list(sg.graph_attr["bb"])
box["data"]["coords"] = coords
return cy_elements
示例5: recalculate
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_node [as 别名]
def recalculate(user):
# remove old ranking
RankedTeam.objects.filter(team__user = user).delete()
for pic in RankingPicture.objects.all():
pic.image.delete()
pic.delete()
color_index = 0
team_graph = Graph()
gvfull = AGraph(directed = True)
for team in user.teams.all():
gvfull.add_node(asciiname(team), label = team.name)
team_graph.add_node(team)
for game in Game.objects.filter(team_1__user = user, team_2__user = user):
team_graph.add_edge(game.winner(), game.loser(), game.jugg_diff())
for source, dest, weight in team_graph.edges():
gvfull.add_edge(asciiname(source), asciiname(dest), label = str(weight))
current_place = 1
gvcircles = AGraph(directed = True)
gvtiebreaker = AGraph(directed = True)
for place in team_graph.topological_sort():
place_list = []
relevant_teams = set()
for circle in place:
relevant_teams |= circle
if len(circle) == 1:
continue
color_index, current_color = getcolor(color_index)
for team in circle:
gvcircles.add_node(asciiname(team), label = team.name, color = current_color, fontcolor = current_color)
gvfull.get_node(asciiname(team)).attr['color'] = current_color
gvfull.get_node(asciiname(team)).attr['fontcolor'] = current_color
for source, dest, weight in team_graph.edges():
if source in circle and dest in circle:
gvcircles.add_edge(asciiname(source), asciiname(dest), label = str(weight), color = current_color, fontcolor = current_color)
gvfull.get_edge(asciiname(source), asciiname(dest)).attr['color'] = current_color
gvfull.get_edge(asciiname(source), asciiname(dest)).attr['fontcolor'] = current_color
place = [[(team.normalized_jugg_diff(relevant_teams), team.name, team) for team in circle] for circle in place]
for circle in place:
circle.sort(reverse = True)
while place:
place_list.append(set())
i = 0
while i < len(place):
circle = place[i]
jd = circle[0][0]
while circle and circle[0][0] == jd:
place_list[-1].add(circle.pop(0))
if not circle:
place.remove(circle)
else:
i += 1
for same_place_set in place_list:
# tie breaker
if len(same_place_set) > 1:
# teams that everyone on this place played against
relevant_teams = team_graph.nodes()
for circ_jugg_diff, name, team in same_place_set:
opponents = set()
for game in team.games():
if game.team_1 == team:
opponents.add(game.team_2)
else:
opponents.add(game.team_1)
relevant_teams &= opponents
if len(relevant_teams) > 0:
color_index, current_color_a = getcolor(color_index)
color_index, current_color_b = getcolor(color_index)
for team in relevant_teams:
gvtiebreaker.add_node("b-" + asciiname(team), label = team.name, color = current_color_b, fontcolor = current_color_b)
for void, void, team in same_place_set:
gvtiebreaker.add_node("a-" + asciiname(team), label = team.name, color = current_color_a, fontcolor = current_color_a)
for game in team.games():
if game.team_1 == team and game.team_2 in relevant_teams:
if game.winner() == team:
gvtiebreaker.add_edge("a-" + asciiname(team), "b-" + asciiname(game.team_2), label = game.jugg_diff(), color = current_color_a, fontcolor = current_color_a)
else:
gvtiebreaker.add_edge("b-" + asciiname(game.team_2), "a-" + asciiname(team), label = game.jugg_diff(), color = current_color_b, fontcolor = current_color_b)
elif game.team_2 == team and game.team_1 in relevant_teams:
if game.winner() == team:
gvtiebreaker.add_edge("a-" + asciiname(team), "b-" + asciiname(game.team_1), label = game.jugg_diff(), color = current_color_a, fontcolor = current_color_a)
else:
gvtiebreaker.add_edge("b-" + asciiname(game.team_1), "a-" + asciiname(team), label = game.jugg_diff(), color = current_color_b, fontcolor = current_color_b)
# jugg differences against relevant teams
rel_jugg_diffs = set()
for team_tuple in same_place_set:
rel_jugg_diffs.add((team_tuple, team_tuple[2].normalized_jugg_diff(relevant_teams)))
# pop all teams, highest relevant jugg difference first
while rel_jugg_diffs:
# current maximum
max_rel_jugg_diff = None
# teams with maximum jugg difference
to_remove = None
for team_tuple, rel_jugg_diff in rel_jugg_diffs:
# new maximum
if max_rel_jugg_diff is None or rel_jugg_diff > max_rel_jugg_diff[0]:
max_rel_jugg_diff = (rel_jugg_diff, {team_tuple})
to_remove = {(team_tuple, rel_jugg_diff)}
# same as maximum
#.........这里部分代码省略.........
示例6: DotGraphSearchProblem
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_node [as 别名]
class DotGraphSearchProblem(Problem):
"""
Playground for stuff in the library... eats a .dot graph and allows you
to try it with the search methods.
"""
def __init__(self, filename):
self.G = AGraph(filename)
xs = [(nodo, nodo.attr.get("initial", None))
for nodo in self.G.iternodes()]
xs = [x for x in xs if x[1]]
if len(xs) == 0:
raise BadInputGraph("Missing 'initial' node")
elif len(xs) > 1:
raise BadInputGraph("Cannot have two initial nodes")
if not any(nodo.attr.get("goal", None) for nodo in self.G.iternodes()):
raise BadInputGraph("Missing a goal state '[goal=\"1\"]'")
super(DotGraphSearchProblem, self).__init__(xs[0][0])
self.initial_state.attr["shape"] = "doublecircle"
for node in self.G.iternodes():
if self.is_goal(node):
node.attr["shape"] = "hexagon"
node.attr["color"] = "blue"
self.seen = set()
self.visit(self.initial_state)
for edge in self.G.iteredges():
edge.attr["style"] = "dotted"
x = edge.attr.get("weight", None)
if x:
x = int(x)
else:
x = 1
edge.attr["weight"] = x
edge.attr["label"] = x
def actions(self, state):
assert state in self.G
if self.G.is_directed():
return self.G.itersucc(state)
else:
assert self.G.is_undirected()
return self.G.iterneighbors(state)
def result(self, state, action):
assert state in self.G and action in self.G
self.visit(state)
return action
def cost(self, state1, action, state2):
assert state1 in self.G and action in self.G and action == state2
x = self.G.get_edge(state1, state2).attr["weight"]
if float(x) == int(x):
return int(x)
else:
return float(x)
def visit(self, state):
if state in self.seen:
return
self.seen.add(state)
attr = self.G.get_node(state).attr
attr["color"] = "firebrick"
def is_goal(self, state):
return bool(state.attr.get("goal", False))
def value(self, state):
assert state in self.G
value = self.G.get_node(state).attr.get("value", None)
if not value:
return 0
return float(value)
示例7: Hagberg
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_node [as 别名]
__author__ = """Aric Hagberg ([email protected])"""
from pygraphviz import AGraph
A = AGraph()
# set some default node attributes
A.node_attr['style'] = 'filled'
A.node_attr['shape'] = 'circle'
A.node_attr['fixedsize'] = 'true'
A.node_attr['fontcolor'] = '#FFFFFF'
# make a star in shades of red
for i in range( 16 ):
A.add_edge( 0, i )
n = A.get_node( i )
n.attr['fillcolor'] = "#%2x0000" % ( i * 16 )
n.attr['height'] = "%s" % ( i / 16.0 + 0.5 )
n.attr['width'] = "%s" % ( i / 16.0 + 0.5 )
print A.string() # print to screen
A.write( "star.dot" ) # write to simple.dot
print "Wrote star.dot"
A.draw( 'star.png', prog="circo" ) # draw to png using circo
print "Wrote star.png"
import matplotlib.pyplot as plt
a = plt.imread( 'star.png' )
plt.imshow( a )
plt.show()
示例8: dot_layout
# 需要导入模块: from pygraphviz import AGraph [as 别名]
# 或者: from pygraphviz.AGraph import get_node [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