def draw(passage):
G = nx.DiGraph()
terminals = sorted(passage.layer(layer0.LAYER_ID).all, key=operator.attrgetter("position"))
G.add_nodes_from([(n.ID, {"label": n.text, "node_color": "white"}) for n in terminals])
G.add_nodes_from([(n.ID, {"label": "IMPLICIT" if n.attrib.get("implicit") else "",
"node_color": "gray" if isinstance(n, Linkage) else (
"white" if n.attrib.get("implicit") else "black")})
for n in passage.layer(layer1.LAYER_ID).all])
G.add_edges_from([(n.ID, e.child.ID, {"label": e.tag, "style": "dashed" if e.attrib.get("remote") else "solid"})
for layer in passage.layers for n in layer.all for e in n])
pos = topological_layout(passage)
nx.draw(G, pos, arrows=False, font_size=10,
node_color=[d["node_color"] for _, d in G.nodes(data=True)],
labels={n: d["label"] for n, d in G.nodes(data=True) if d["label"]},
style=[d["style"] for _, _, d in G.edges(data=True)])
nx.draw_networkx_edge_labels(G, pos, font_size=8,
edge_labels={(u, v): d["label"] for u, v, d in G.edges(data=True)})
python类draw_networkx_edge_labels()的实例源码
dfs_visual.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
def DrawDFSPath(G, dfs_stk):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
for i in dfs_stk:
#if there is more than one node in the dfs-forest, then print the corresponding edges
if len(i) > 1:
for j in i[ :(len(i)-1)]:
if i[i.index(j)+1] in G[j]:
nx.draw_networkx_edges(G, pos, edgelist = [(j,i[i.index(j)+1])], width = 2.5, alpha = 0.6, edge_color = 'r')
else:
#if in case the path was reversed because all the possible neighbours were visited, we need to find the adj node to it.
for k in i[1::-1]:
if k in G[j]:
nx.draw_networkx_edges(G, pos, edgelist = [(j,k)], width = 2.5, alpha = 0.6, edge_color = 'r')
break
#main function
def plot_graph(self, file_name: str='graph.png', label_nodes: bool=True, label_edges: bool=True):
import matplotlib.pyplot as plt
# pos = nx.spring_layout(self.graph)
pos = nx.shell_layout(self.graph, dim=1024, scale=0.5)
# pos = nx.random_layout(self.graph, dim=1024, scale=0.5)
if label_edges:
edge_labels = {
(edge[0], edge[1]): edge[2]['object'] for edge in self.graph.edges(data=True)
}
nx.draw_networkx_edge_labels(self.graph, pos, edge_labels, font_size=5)
if label_nodes:
labels = {node[0]: node[1] for node in self.graph.nodes(data=True)}
nx.draw_networkx_labels(self.graph, pos, labels, font_size=5, alpha=0.8)
# nx.draw(self.graph, with_labels=True, arrows=True, node_size=80)
nx.draw_spectral(self.graph, with_labels=True, arrows=True, node_size=80)
plt.savefig(file_name, dpi=1024)
def draw_grid(ts, edgelabel='control', prop_colors=None, current_node=None):
assert edgelabel is None or nx.is_weighted(ts.g, weight=edgelabel)
pos = nx.get_node_attributes(ts.g, 'location')
if current_node == 'init':
current_node = next(ts.init.iterkeys())
colors = dict([(v, 'w') for v in ts.g])
if current_node:
colors[current_node] = 'b'
for v, d in ts.g.nodes_iter(data=True):
if d['prop']:
colors[v] = prop_colors[tuple(d['prop'])]
colors = colors.values()
labels = nx.get_node_attributes(ts.g, 'label')
nx.draw(ts.g, pos=pos, node_color=colors)
nx.draw_networkx_labels(ts.g, pos=pos, labels=labels)
edge_labels = nx.get_edge_attributes(ts.g, edgelabel)
nx.draw_networkx_edge_labels(ts.g, pos=pos,
edge_labels=edge_labels)
def prepare_plot(graph):
"""
Prepares a Matplotlib plot for further handling
:param graph: datamodel.base.Graph instance
:return: None
"""
G = graph.nxgraph
# Color map for nodes: color is proportional to depth level
# http://matplotlib.org/examples/color/colormaps_reference.html
depth_levels_from_root = nx.shortest_path_length(G, graph.root_node)
vmax = 1.
colormap = plt.get_cmap('BuGn')
step = 1./len(graph)
node_colors = [vmax - step * depth_levels_from_root[n] for n in G.nodes()]
# Draw!
# https://networkx.github.io/documentation/networkx-1.10/reference/drawing.html
pos = nx.spectral_layout(G)
nx.draw_networkx_labels(G, pos,
labels=dict([(n, n.name) for n in G.nodes()]),
font_weight='bold',
font_color='orangered')
nx.draw_networkx_nodes(G, pos,
node_size=2000,
cmap=colormap,
vmin=0.,
vmax=vmax,
node_color=node_colors)
nx.draw_networkx_edge_labels(G, pos,
edge_labels=dict([((u, v,), d['name']) for u, v, d in G.edges(data=True)]))
nx.draw_networkx_edges(G, pos,
edgelist=[edge for edge in G.edges()],
arrows=True)
assignment_prob_hungarian.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def DrawGraph(B):
l, r = nx.bipartite.sets(B)
pos = {}
# Update position for node from each group
pos.update((node, (1, index)) for index, node in enumerate(l))
pos.update((node, (2, index)) for index, node in enumerate(r))
nx.draw(B, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u, v), d['length']) for u, v, d in B.edges(data = True)])
nx.draw_networkx_edge_labels(B, pos, edge_labels = edge_labels, label_pos = 0.2, font_size = 11) #prints weight on all the edges
return pos
#main function
tsp_christofides.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def DrawGraph(G,color):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True, edge_color = color) #with_labels=true is to show the node number in the output graph
edge_labels = nx.get_edge_attributes(G,'length')
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges
return pos
#main function
a_star_search.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def DrawPath(G, source, dest):
pos = nx.spring_layout(G)
val_map = {}
val_map[source] = 'green'
val_map[dest] = 'red'
values = [val_map.get(node, 'blue') for node in G.nodes()]
nx.draw(G, pos, with_labels = True, node_color = values, edge_color = 'b' ,width = 1, alpha = 0.7) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u, v,), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.5, font_size = 11) #prints weight on all the edges
return pos
#main function
bfs.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
def DrawGraph(G):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u,v,), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
return pos
#main function
k_centers_problem.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def DrawGraph(G, centers):
pos = nx.spring_layout(G)
color_map = ['blue'] * len(G.nodes())
#all the center nodes are marked with 'red'
for c in centers:
color_map[c] = 'red'
nx.draw(G, pos, node_color = color_map, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = nx.get_edge_attributes(G, 'length')
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges
#main function
prims.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def DrawGraph(G):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = nx.get_edge_attributes(G,'length')
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) #prints weight on all the edges
return pos
#main function
dijsktras.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def DrawGraph(G):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) #with_labels=true is to show the node number in the output graph
edge_labels = dict([((u, v), d['length']) for u, v, d in G.edges(data = True)])
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, label_pos = 0.3, font_size = 11) #prints weight on all the edges
return pos
#main function
kruskals_quick_union.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def DrawGraph(G):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True) # with_labels=true is to show the node number in the output graph
edge_labels = nx.get_edge_attributes(G, 'length')
nx.draw_networkx_edge_labels(G, pos, edge_labels = edge_labels, font_size = 11) # prints weight on all the edges
return pos
# main function
def _build_graph(show=False):
"""Load word dependencies into graph using networkx. Enables easy traversal of dependencies for parsing particular patterns.
One graph is created for each sentence.
Args:
show (bool): If set to True, labeled visualization of network will be opened via matplotlib for each sentence
Returns:
None: Global variable G is set from within function
"""
global G
G = nx.Graph()
node_labels, edge_labels = {}, {}
for idx, dep in enumerate(A.deps):
types = ["dependent", "governor"]
# nodes, labels
for x in types:
G.add_node(str(dep[x]), word=dep[x + "Gloss"], pos=A.lookup[dep[x]]["pos"])
node_labels[str(dep[x])] = dep[x + "Gloss"] + " : " + A.lookup[dep[x]]["pos"]
# edges, labels
G.add_edge(str(dep[types[0]]), str(dep[types[1]]), dep=dep["dep"])
edge_labels[(str(dep[types[0]]), str(dep[types[1]]))] = dep["dep"]
if show == True:
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos, labels=node_labels, node_color="white", alpha=.5)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)
plt.show()
#########################################
# Dependency / POS parsing functions
#########################################
def plot_and_save_net(self, picpath='../output/net.png'):
net = nx.DiGraph()
edge_label = dict()
for edge in self.edges:
net.add_edge(edge[0], edge[1], weight=1)
edge_label[(edge[0], edge[1])] = edge[3]
if len(edge_label) > 8:
break
# edge_label.update({(edge[0], edge[1]) : edge[2]})
pos = nx.spring_layout(net, k=20) # positions for all nodes
# nodes
nx.draw_networkx_nodes(net, pos, node_size=6000, node_color="green")
# edges
nx.draw_networkx_edges(net, pos,
width=1.5, alpha=0.5, arrows=True, edge_color='black')
# labels
nx.draw_networkx_labels(net, pos, font_size=20)
nx.draw_networkx_edge_labels(net, pos, edge_labels=edge_label, label_pos=0.5, font_family='sans-serif')
plt.axis('off')
plt.savefig(picpath) # save as png
plt.show() # display
def visualize(self, edgelabel='prob', current_node=None,
draw='pygraphviz'):
"""
Visualizes a LOMAP system model.
"""
assert edgelabel is None or nx.is_weighted(self.g, weight=edgelabel)
if draw == 'pygraphviz':
nx.view_pygraphviz(self.g, edgelabel)
elif draw == 'matplotlib':
pos = nx.get_node_attributes(self.g, 'location')
if len(pos) != self.g.number_of_nodes():
pos = nx.spring_layout(self.g)
if current_node is None:
colors = 'r'
else:
if current_node == 'init':
current_node = next(self.init.iterkeys())
colors = dict([(v, 'r') for v in self.g])
colors[current_node] = 'b'
colors = colors.values()
nx.draw(self.g, pos=pos, node_color=colors)
nx.draw_networkx_labels(self.g, pos=pos)
edge_labels = nx.get_edge_attributes(self.g, edgelabel)
nx.draw_networkx_edge_labels(self.g, pos=pos,
edge_labels=edge_labels)
else:
raise ValueError('Expected parameter draw to be either:'
+ '"pygraphviz" or "matplotlib"!')
def visualize(self, edgelabel='control', current_node=None,
draw='pygraphviz'):
"""
Visualizes a LOMAP system model.
"""
assert edgelabel is None or nx.is_weighted(self.g, weight=edgelabel)
if draw == 'pygraphviz':
nx.view_pygraphviz(self.g, edgelabel)
elif draw == 'matplotlib':
pos = nx.get_node_attributes(self.g, 'location')
if len(pos) != self.g.number_of_nodes():
pos = nx.spring_layout(self.g)
if current_node is None:
colors = 'r'
else:
if current_node == 'init':
current_node = next(self.init.iterkeys())
colors = dict([(v, 'r') for v in self.g])
colors[current_node] = 'b'
colors = colors.values()
nx.draw(self.g, pos=pos, node_color=colors)
nx.draw_networkx_labels(self.g, pos=pos)
edge_labels = nx.get_edge_attributes(self.g, edgelabel)
nx.draw_networkx_edge_labels(self.g, pos=pos,
edge_labels=edge_labels)
else:
raise ValueError('Expected parameter draw to be either:'
+ '"pygraphviz" or "matplotlib"!')
def _draw_edge_labels(self, edge_labels, **kwargs):
pos = kwargs.pop('pos', self._pos)
return nx.draw_networkx_edge_labels(self._G, pos, edge_labels=edge_labels, **kwargs)
def animate(self, save=False):
"""
Animates the Given algorithm with given Graph
:param save: Boolean indicating weather output has to be written into output/
"""
result = self.fn(self.graph)
for matrix, active in result:
self.frames.append(matrix)
self.active.append(active)
# Draw the original matrix
if self.pos is None:
self.pos = nx.nx_pydot.graphviz_layout(self.graph)
nx.draw_networkx_nodes(self.graph, self.pos, ax=self.ax1, node_color='g', alpha=0.8,
node_size=self.node_size).set_edgecolor('k')
nx.draw_networkx_edges(self.graph, self.pos, ax=self.ax1, alpha=0.6)
if self.weights:
nx.draw_networkx_edge_labels(self.graph, self.pos, ax=self.ax1,
edge_labels=nx.get_edge_attributes(self.graph, 'weight'))
if self.lables:
nx.draw_networkx_labels(self.graph, self.pos, ax=self.ax1)
# Draw its adjacancy matrix
vmin = 0
vmax = np.max(np.ma.array(self.frames[-1], mask=np.isinf(self.frames[-1])))
cmap = plt.get_cmap('jet')
cmap.set_bad('white', 1.)
masked_array = np.ma.array(self.frames[0], mask=np.isinf(self.frames[0]))
self.ax2.imshow(masked_array, interpolation='nearest', vmin=vmin, vmax=vmax, alpha=0.7)
if self.matrix_labels:
self.__plot_matrix_labels(self.frames[0], self.ax2)
# Now start the animation
x = animation.FuncAnimation(self.fig, self.__update, interval=1000, blit=False,
repeat=False, init_func=self.__init_animation, frames=len(self.frames))
if save:
import errno
import os
path = "output"
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
Writer = animation.writers['ffmpeg']
writer = Writer(fps=1, metadata=dict(artist='V'), bitrate=1800)
from multiprocessing import Process
import os
path = os.path.join('output', '%s.mp4' % self.fn.__name__)
Process(target=x.save, args=(path,), kwargs={'writer': writer}).start()
plt.show()
def apply_to_graph(self, show_graph=True):
"""
Applies the given algorithm to given graph and displays it
:param show_graph: Weather to show the graph in final result or not
"""
# Draw the original matrix
if show_graph:
if self.pos is None:
self.pos = nx.nx_pydot.graphviz_layout(self.graph)
nx.draw_networkx_nodes(self.graph, self.pos, ax=self.ax1, node_color='g', alpha=0.8,
node_size=self.node_size).set_edgecolor('k')
nx.draw_networkx_edges(self.graph, self.pos, ax=self.ax1, alpha=0.5)
if self.weights:
nx.draw_networkx_edge_labels(self.graph, self.pos, ax=self.ax1,
edge_labels=nx.get_edge_attributes(self.graph, 'weight'))
if self.lables:
nx.draw_networkx_labels(self.graph, self.pos, ax=self.ax1)
# Draw its adjacancy matrix
result, adj = None, None
for i, matrix in enumerate(self.fn(self.graph)):
if i == 0:
adj = matrix[0]
result = matrix[0]
# print(adj, result)
cmap = plt.get_cmap('jet')
cmap.set_bad('white', 1.)
vmin = 0
vmax = np.max(result)
from mpl_toolkits.axes_grid1 import make_axes_locatable
div = make_axes_locatable(self.ax2)
cax = div.append_axes('right', '5%', '5%')
cax.axis('off')
masked_array = np.ma.array(adj, mask=np.isinf(adj))
self.ax2.imshow(masked_array, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax)
if self.matrix_labels:
self.__plot_matrix_labels(adj, self.ax2)
# Now draw the final matrix
masked_array = np.ma.array(result, mask=np.isinf(result))
div = make_axes_locatable(self.ax3)
cax = div.append_axes('right', '5%', '5%')
if self.matrix_labels:
self.__plot_matrix_labels(result, self.ax3)
self.img = self.ax3.imshow(masked_array, interpolation='nearest', cmap=cmap, vmin=vmin, vmax=vmax)
self.fig.colorbar(self.img, cax=cax)
plt.show()
def apply_to_graph(fun, G = None):
"""
Applies given algorithm to random geometric graph and displays the results side by side
:param fun: A function which has the signature f(G) and returns iterator of edges of graph G
:param G: a networkx Graph. If None, random geometric graph is created and applied
:return: Plot showing G and fun(G)
"""
if G is None:
G = nx.random_geometric_graph(100, .125)
# position is stored as node attribute data for random_geometric_graph
pos = nx.get_node_attributes(G, 'pos')
nodesize = 80
for u, v in G.edges():
G.edge[u][v]['weight'] = ((G.node[v]['pos'][0] - G.node[u]['pos'][0]) ** 2 +
(G.node[v]['pos'][1] - G.node[u]['pos'][1]) ** 2) ** .5
else:
pos = graphviz_layout(G)
nodesize = 200
# find node near center (0.5,0.5)
color = {}
dmin = 1
ncenter = 0
for n in pos:
x, y = pos[n]
d = (x - 0.5) ** 2 + (y - 0.5) ** 2
color[n] = d
if d < dmin:
ncenter = n
dmin = d
res = nx.Graph(list(fun(G)))
plt.figure(figsize=(10, 8))
plt.suptitle(fun.__name__ + " algorithm application")
plt.subplot(1, 2, 1)
plt.title("Original Graph G")
nx.draw_networkx_edges(G, pos, nodelist=[ncenter], alpha=0.4)
nx.draw_networkx_nodes(G, pos,
nodelist=color.keys(),
node_size=nodesize,
node_color=list(color.values()),
cmap=plt.get_cmap("Reds_r")
).set_edgecolor('k')
if G is not None:
nx.draw_networkx_labels(G,pos)
nx.draw_networkx_edge_labels(G,pos,
edge_labels=nx.get_edge_attributes(G,'weight'))
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title("Resultant Graph, R = {0}(G)".format(fun.__name__))
nx.draw_networkx_edges(res, pos, nodelist=[ncenter], alpha=0.4)
nx.draw_networkx_nodes(res, pos,
node_color=list(color[n] for n in res.nodes()),
node_size=nodesize,
cmap=plt.get_cmap("Greens_r")).set_edgecolor('k')
if G is not None:
nx.draw_networkx_labels(res,pos)
nx.draw_networkx_edge_labels(res, pos,
edge_labels=nx.get_edge_attributes(res, 'weight'))
plt.axis('off')
plt.show()
def visualize_graph(graph, savepath=None):
''' pass in a Graph object '''
node_objs = graph.nodes
edge_hash = graph.edges
G = nx.Graph() # init network obj
# add all nodes
node_assignments = []
for node in node_objs:
G.add_node(node.value)
node_assignments.append(node.label)
for k,v in edge_hash.iteritems():
_, nd_i, nd_j = k.split('_')
node_i = graph.get_node(index=int(nd_i))
node_j = graph.get_node(index=int(nd_j))
weight = 0
for k2, v2 in v.iteritems():
weight += float(v2)
G.add_edge(
node_i.value,
node_j.value,
weight=weight
)
node_labels = {node:node for node in G.nodes()}
edge_labels=dict([((u,v,),d['weight'])
for u,v,d in G.edges(data=True)])
edge_colors = ['black' if float(d['weight']) < 1.0 else 'red' for _, _,d in G.edges(data=True)]
pos=nx.spring_layout(G)
nx.draw_networkx_labels(
G,
pos,
labels=node_labels,
font_color='w'
)
nx.draw_networkx_edge_labels(
G,
pos,
edge_labels=edge_labels
)
nx.draw(
G,
pos,
node_color=node_assignments,
node_size=1500,
edge_color=edge_colors,
edge_cmap=plt.cm.Reds
)
if savepath:
plt.savefig(savepath)
return
plt.show()
def visualize_diagram(bpmn_diagram):
"""
Shows a simple visualization of diagram
:param bpmn_diagram: an instance of BPMNDiagramGraph class.
"""
g = bpmn_diagram.diagram_graph
pos = bpmn_diagram.get_nodes_positions()
nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.task))
nx.draw_networkx_nodes(g, pos, node_shape='s', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.subprocess))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.complex_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.event_based_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.inclusive_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.exclusive_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='d', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.parallel_gateway))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.start_event))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_catch_event))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.end_event))
nx.draw_networkx_nodes(g, pos, node_shape='o', node_color='white',
nodelist=bpmn_diagram.get_nodes_id_list_by_type(consts.Consts.intermediate_throw_event))
node_labels = {}
for node in g.nodes(data=True):
node_labels[node[0]] = node[1].get(consts.Consts.node_name)
nx.draw_networkx_labels(g, pos, node_labels)
nx.draw_networkx_edges(g, pos)
edge_labels = {}
for edge in g.edges(data=True):
edge_labels[(edge[0], edge[1])] = edge[2].get(consts.Consts.name)
nx.draw_networkx_edge_labels(g, pos, edge_labels)
plt.show()
def plot_network_with_results(psstc, model, time=0):
G = create_network(psstc)
fig, axs = plt.subplots(1, 1, figsize=(12, 9))
ax = axs
line_color_dict = dict()
hour = 0
for i, b in branch_df.iterrows():
if model.ThermalLimit[i] != 0:
line_color_dict[(b['F_BUS'], b['T_BUS'])] = round(abs(model.LinePower[i, hour].value / model.ThermalLimit[i]), 2)
else:
line_color_dict[(b['F_BUS'], b['T_BUS'])] = 0
gen_color_dict = dict()
hour = 0
for i, g in generator_df.iterrows():
gen_color_dict[(i, g['GEN_BUS'])] = round(abs(model.PowerGenerated[i, hour].value / model.MaximumPowerOutput[i]), 2)
color_dict = line_color_dict.copy()
color_dict.update(gen_color_dict)
edge_color = list()
for e in G.edges():
try:
edge_color.append( color_dict[(e[0], e[1])] )
except KeyError:
edge_color.append( color_dict[(e[1], e[0])] )
ax.axis('off')
pos = graphviz_layout(G, prog='sfdp')
nx.draw_networkx_nodes(G, pos, list(generator_df.index),)
nx.draw_networkx_nodes(G, pos, list(bus_df.index), node_color='black',)
edges = nx.draw_networkx_edges(G, pos, edge_color=edge_color, edge_cmap=cmap, width=3)
nx.draw_networkx_edge_labels(G, pos, edge_labels=color_dict)
divider = make_axes_locatable(ax)
cax = divider.append_axes("left", size="5%", pad=0.05)
cb = plt.colorbar(edges, cax=cax)
cax.yaxis.set_label_position('left')
cax.yaxis.set_ticks_position('left')
# cb.set_label('Voltage (V)')