def malt_demo(nx=False):
"""
A demonstration of the result of reading a dependency
version of the first sentence of the Penn Treebank.
"""
dg = DependencyGraph("""Pierre NNP 2 NMOD
Vinken NNP 8 SUB
, , 2 P
61 CD 5 NMOD
years NNS 6 AMOD
old JJ 2 NMOD
, , 2 P
will MD 0 ROOT
join VB 8 VC
the DT 11 NMOD
board NN 9 OBJ
as IN 9 VMOD
a DT 15 NMOD
nonexecutive JJ 15 NMOD
director NN 12 PMOD
Nov. NNP 9 VMOD
29 CD 16 NMOD
. . 9 VMOD
""")
tree = dg.tree()
tree.pprint()
if nx:
# currently doesn't work
import networkx
from matplotlib import pylab
g = dg.nx_graph()
g.info()
pos = networkx.spring_layout(g, dim=1)
networkx.draw_networkx_nodes(g, pos, node_size=50)
# networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
networkx.draw_networkx_labels(g, pos, dg.nx_labels)
pylab.xticks([])
pylab.yticks([])
pylab.savefig('tree.png')
pylab.show()
python类draw_networkx_labels()的实例源码
def create_web_network_graph(self):
''' Functions that creates a NetworkX network visualization from the
explored pages
For documentation about NetworkX, check : https://networkx.github.io/'''
#Create a directed graph
web_graph=nx.DiGraph()
# Add our start nodes first to the graph, as the center.
web_graph.add_nodes_from(self.to_visit_urls[0])
#Now we explore our results to add the relevant websites to the graph
for base_url in os.listdir(self.main_directory+"web_content/"):
if self.is_danish_company(base_url): #Only Danish companies are added :
web_graph.add_node(base_url)
#Explore again to fill up all the edges (connections/links) between websites
for base_url in os.listdir(self.main_directory+"web_content/"):
if self.is_danish_company(base_url): # Same as before only Danish companies
#Load up the links from this Danish company to other websites
filename = self.main_directory+"web_content/"+base_url+"/external_urls_"+str(self.redirect_count)+"_redirect.p"
external_base_urls=pickle.load(open(filename, "rb" ))
#Now we also filter the list of external links
for external_link in external_base_urls:
if web_graph.has_node(external_link) : # The link is also in the graph, so the connection is added
web_graph.add_edge(base_url,external_link)
#Finally draw the network
#plt.figure(figsize=(120, 90))
plt.figure(figsize=(40, 40))
pos = nx.random_layout(web_graph)
nx.draw_networkx_nodes(web_graph,pos,node_size=2500)
nx.draw_networkx_nodes(web_graph,nodelist=self.to_visit_urls[0],pos=pos,node_size=3000,node_color='b')
#nx.draw_networkx_labels(web_graph,pos,fontsize=12)
nx.draw_networkx_edges(web_graph,pos,alpha=0.5)
plt.savefig(self.main_directory+"DTU network.png",dpi=40)
plt.show()
def malt_demo(nx=False):
"""
A demonstration of the result of reading a dependency
version of the first sentence of the Penn Treebank.
"""
dg = DependencyGraph("""Pierre NNP 2 NMOD
Vinken NNP 8 SUB
, , 2 P
61 CD 5 NMOD
years NNS 6 AMOD
old JJ 2 NMOD
, , 2 P
will MD 0 ROOT
join VB 8 VC
the DT 11 NMOD
board NN 9 OBJ
as IN 9 VMOD
a DT 15 NMOD
nonexecutive JJ 15 NMOD
director NN 12 PMOD
Nov. NNP 9 VMOD
29 CD 16 NMOD
. . 9 VMOD
""")
tree = dg.tree()
tree.pprint()
if nx:
# currently doesn't work
import networkx
from matplotlib import pylab
g = dg.nx_graph()
g.info()
pos = networkx.spring_layout(g, dim=1)
networkx.draw_networkx_nodes(g, pos, node_size=50)
# networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
networkx.draw_networkx_labels(g, pos, dg.nx_labels)
pylab.xticks([])
pylab.yticks([])
pylab.savefig('tree.png')
pylab.show()
def save_topology(adj, sample_folder, dataset_name, graph_name):
graph = nx.Graph()
path = sample_folder+'/'+dataset_name
if not os.path.isdir(path):
os.makedirs(path)
# 1. transfer adj to nx
# adj_list = list(np.squeeze(adj[0,:,:,:]))
adj_list = list(adj)
for src in range(len(adj_list)):
graph.add_node(src)
for dst in range(len(adj_list[src])):
if adj_list[src][dst] >= 0.2: # ?? sample ?? ?? [0,1]???
graph.add_edge(src,dst)
# 2. read position
pos_file = glob.glob(path+'/*.pos')
if pos_file == []:
pos = nx.spring_layout(graph)
pickle.dump(pos, open(path+'/graph.pos','wb'))
else:
pos = pickle.load(open(pos_file[0],'rb'))
# 3. draw graph
nx.draw_networkx_nodes(graph, pos, node_size=300, node_color='b', alpha=0.8)
nx.draw_networkx_edges(graph, pos, width=1.5, alpha=0.8)
nx.draw_networkx_labels(graph, pos, font_color='w')
plt.savefig(path+'/'+graph_name+'.png')
plt.savefig(path+'/'+graph_name+'.pdf')
# plt.show()
# 4. store graph
pickle.dump(graph, open(path+'/'+graph_name+'.graph','wb'))
def save_topology(adj, path, graph_name, link_possibility):
graph = nx.Graph()
if not os.path.isdir(path):
os.makedirs(path)
# 1. transfer adj to nx
adj_list = list(np.squeeze(adj[0,:,:,:]))
for src in range(len(adj_list)):
graph.add_node(src)
for dst in range(len(adj_list[src])):
if adj_list[src][dst] >= link_possibility: # ?? sample ?? ?? [0,1]???
graph.add_edge(src,dst)
# 2. read position
pos_file = glob.glob(path+'*.pos')
if pos_file == []:
node_size = len(graph.nodes())
tmp_graph = nx.barabasi_albert_graph(node_size,2)
pos = nx.spring_layout(tmp_graph)
pickle.dump(pos, open(path+'graph.pos','wb'))
else:
pos = pickle.load(open(pos_file[0],'rb'))
# 3. draw graph
nx.draw_networkx_nodes(graph, pos, node_size=300, node_color='b', alpha=0.8)
nx.draw_networkx_edges(graph, pos, width=1.5, alpha=0.8)
nx.draw_networkx_labels(graph, pos, font_color='w')
plt.savefig(path+'/'+graph_name+'.png')
plt.savefig(path+'/'+graph_name+'.pdf')
# plt.show()
plt.clf()
# 4. store graph
pickle.dump(graph, open(path+graph_name+'.graph','wb'))
# ------------------------------
# show_all_variables()
# @purpose: ??TF??????
# ------------------------------
def malt_demo(nx=False):
"""
A demonstration of the result of reading a dependency
version of the first sentence of the Penn Treebank.
"""
dg = DependencyGraph("""Pierre NNP 2 NMOD
Vinken NNP 8 SUB
, , 2 P
61 CD 5 NMOD
years NNS 6 AMOD
old JJ 2 NMOD
, , 2 P
will MD 0 ROOT
join VB 8 VC
the DT 11 NMOD
board NN 9 OBJ
as IN 9 VMOD
a DT 15 NMOD
nonexecutive JJ 15 NMOD
director NN 12 PMOD
Nov. NNP 9 VMOD
29 CD 16 NMOD
. . 9 VMOD
""")
tree = dg.tree()
tree.pprint()
if nx:
# currently doesn't work
import networkx
from matplotlib import pylab
g = dg.nx_graph()
g.info()
pos = networkx.spring_layout(g, dim=1)
networkx.draw_networkx_nodes(g, pos, node_size=50)
# networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
networkx.draw_networkx_labels(g, pos, dg.nx_labels)
pylab.xticks([])
pylab.yticks([])
pylab.savefig('tree.png')
pylab.show()
def draw_tier3():
print 'loading tier3 data'
loadEntity(tier3filename)
print 'entity size: ', len(entityList)
G = nx.Graph()
for entity in entityList:
name = entity.name[0].decode('utf8')
print name
G.add_node(name)
for parent in entity.parent:
pr = parent.decode('utf8')
G.add_node(pr)
G.add_edge(pr, name)
for child in entity.child:
cn = child.decode('utf8')
G.add_node(cn)
G.add_edge(name, cn)
pos=nx.spring_layout(G) # positions for all nodes
nx.draw_networkx_edges(G,pos,width=1.0,alpha=0.5)
# labels
nx.draw_networkx_labels(G,pos,font_size=10,font_family='sans-serif')
plt.axis('off')
plt.show()
def malt_demo(nx=False):
"""
A demonstration of the result of reading a dependency
version of the first sentence of the Penn Treebank.
"""
dg = DependencyGraph("""Pierre NNP 2 NMOD
Vinken NNP 8 SUB
, , 2 P
61 CD 5 NMOD
years NNS 6 AMOD
old JJ 2 NMOD
, , 2 P
will MD 0 ROOT
join VB 8 VC
the DT 11 NMOD
board NN 9 OBJ
as IN 9 VMOD
a DT 15 NMOD
nonexecutive JJ 15 NMOD
director NN 12 PMOD
Nov. NNP 9 VMOD
29 CD 16 NMOD
. . 9 VMOD
""")
tree = dg.tree()
tree.pprint()
if nx:
# currently doesn't work
import networkx
from matplotlib import pylab
g = dg.nx_graph()
g.info()
pos = networkx.spring_layout(g, dim=1)
networkx.draw_networkx_nodes(g, pos, node_size=50)
# networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
networkx.draw_networkx_labels(g, pos, dg.nx_labels)
pylab.xticks([])
pylab.yticks([])
pylab.savefig('tree.png')
pylab.show()
def plot_module_dependency_graph(graph):
"""
Plot a graph of specified yang modules. this function is used to plot
both the full dependency graph of all yang modules in the DB, or a
subgraph of dependencies for a specified module
:param graph: Graph to be plotted
:return: None
"""
# fixed_pos = { 'ietf-interfaces':(0.01,0.01) }
# fixed_nodes = fixed_pos.keys()
# pos = nx.spring_layout(graph, iterations=200,
# pos=fixed_pos, fixed=fixed_nodes)
#pos = nx.circular_layout(graph)
pos = nx.spring_layout(graph, iterations=2000)
# Draw RFC nodes (yang modules) in red
nx.draw_networkx_nodes(graph, pos=pos, nodelist=prune_graph_nodes(graph, RFC_TAG), node_size=200,
node_shape='s', node_color='red', alpha=0.5, linewidths=0.5)
# Draw draft nodes (yang modules) in green
nx.draw_networkx_nodes(graph, pos=pos, nodelist=prune_graph_nodes(graph, DRAFT_TAG), node_size=200,
node_shape='o', node_color='green', alpha=0.5, linewidths=0.5)
# Draw unknown nodes (yang modules) in orange
nx.draw_networkx_nodes(graph, pos=pos, nodelist=prune_graph_nodes(graph, UNKNOWN_TAG), node_size=200,
node_shape='^', node_color='orange', alpha=1.0, linewidths=0.5)
# Draw edges in light gray (fairly transparent)
nx.draw_networkx_edges(graph, pos=pos, alpha=0.25, linewidths=0.1, arrows=False)
# Draw labels on nodes (modules)
nx.draw_networkx_labels(graph, pos=pos, font_size=10, font_weight='bold', alpha=1.0)
def show_network(self):
import time
plt.figure(time.time())
for v in self.G.nodes():
self.G.node[v]['state'] = str(v)
node_labels = nx.get_node_attributes(self.G, 'state')
pos = nx.circular_layout(self.G)
nx.draw_networkx_labels(self.G, pos, node_labels=node_labels)
nx.draw(self.G, pos)
plt.savefig('./assets/result2.png')
# plt.show(block=False)
plt.close()
def malt_demo(nx=False):
"""
A demonstration of the result of reading a dependency
version of the first sentence of the Penn Treebank.
"""
dg = DependencyGraph("""Pierre NNP 2 NMOD
Vinken NNP 8 SUB
, , 2 P
61 CD 5 NMOD
years NNS 6 AMOD
old JJ 2 NMOD
, , 2 P
will MD 0 ROOT
join VB 8 VC
the DT 11 NMOD
board NN 9 OBJ
as IN 9 VMOD
a DT 15 NMOD
nonexecutive JJ 15 NMOD
director NN 12 PMOD
Nov. NNP 9 VMOD
29 CD 16 NMOD
. . 9 VMOD
""")
tree = dg.tree()
tree.pprint()
if nx:
# currently doesn't work
import networkx
from matplotlib import pylab
g = dg.nx_graph()
g.info()
pos = networkx.spring_layout(g, dim=1)
networkx.draw_networkx_nodes(g, pos, node_size=50)
# networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
networkx.draw_networkx_labels(g, pos, dg.nx_labels)
pylab.xticks([])
pylab.yticks([])
pylab.savefig('tree.png')
pylab.show()
def malt_demo(nx=False):
"""
A demonstration of the result of reading a dependency
version of the first sentence of the Penn Treebank.
"""
dg = DependencyGraph("""Pierre NNP 2 NMOD
Vinken NNP 8 SUB
, , 2 P
61 CD 5 NMOD
years NNS 6 AMOD
old JJ 2 NMOD
, , 2 P
will MD 0 ROOT
join VB 8 VC
the DT 11 NMOD
board NN 9 OBJ
as IN 9 VMOD
a DT 15 NMOD
nonexecutive JJ 15 NMOD
director NN 12 PMOD
Nov. NNP 9 VMOD
29 CD 16 NMOD
. . 9 VMOD
""")
tree = dg.tree()
tree.pprint()
if nx:
# currently doesn't work
import networkx
from matplotlib import pylab
g = dg.nx_graph()
g.info()
pos = networkx.spring_layout(g, dim=1)
networkx.draw_networkx_nodes(g, pos, node_size=50)
# networkx.draw_networkx_edges(g, pos, edge_color='k', width=8)
networkx.draw_networkx_labels(g, pos, dg.nx_labels)
pylab.xticks([])
pylab.yticks([])
pylab.savefig('tree.png')
pylab.show()
def display_graph(G):
pos=nx.spring_layout(G)
node_labels = {node:node for node in G.nodes()}
nx.draw_networkx_labels(G, pos, labels=node_labels)
nx.draw(G,pos)
pylab.show()
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 visualize(self, edgelabel=None, draw='pygraphviz'):
"""
Visualizes a LOMAP system model
"""
if draw == 'pygraphviz':
nx.view_pygraphviz(self.g, edgelabel)
elif draw == 'matplotlib':
pos = nx.spring_layout(self.g)
nx.draw(self.g, pos=pos)
nx.draw_networkx_labels(self.g, pos=pos)
else:
raise ValueError('Expected parameter draw to be either:'
+ '"pygraphviz" or "matplotlib"!')
def _draw_node_labels(self, labels, **kwargs):
pos = kwargs.pop('pos', self._pos)
return nx.draw_networkx_labels(self._G, pos, labels=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()