def DrawGraph(G,egocentric_network_edge_list,egocentric_network_node_list, vert):
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels = True, node_color = 'blue', alpha = 0.8) #with_labels=true is to show the node number in the output graph
nx.draw_networkx_edges(G, pos, edgelist = egocentric_network_edge_list , width = 2.5, alpha = 0.8, edge_color = 'red')
nx.draw_networkx_nodes(G,pos, nodelist = egocentric_network_node_list, node_color = 'red', alpha = 0.5)
nx.draw_networkx_nodes(G,pos,nodelist=[vert],node_color='green',node_size=500,alpha=0.8)
return pos
python类draw()的实例源码
egocentric_network_1.py 文件源码
项目:Visualization-of-popular-algorithms-in-Python
作者: MUSoC
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
dijsktras.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 = 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
项目源码
文件源码
阅读 22
收藏 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 draw_graph(G, labels, colors, show, save_path, close_plot=True):
nx.draw(G, pos=graphviz_layout(G, prog='dot'), labels=labels, arrows=True, node_color=colors)
if show:
plt.show()
else:
plt.savefig(save_path)
if close_plot:
plt.close()
def debug_instance(instance_wf):
print '*' * 20
print instance_wf.graph.nodes(data=False)
print '*' * 21
print instance_wf.graph.edges()
print '*' * 22
print instance_wf.graph.is_multigraph()
print '*' * 23
print instance_wf.graph.number_of_edges()
print '*' * 24
print instance_wf.sorted_tasks
print '*' * 25
test = instance_wf.graph.reverse()
print test.edges()
print '*' * 26
print instance_wf.graph.in_degree()
print instance_wf.check_in_degree_edges()
print '*' * 27
print instance_wf.graph.out_degree()
print instance_wf.check_out_degree_edges()
print '*' * 28
x = instance_wf.get_operations()[0]
print x['ports']
# print instance_wf.get_ports_from_operation_tasks('')
# Show image
# pos = nx.spring_layout(instance_wf.graph)
# pos = nx.fruchterman_reingold_layout(instance_wf.graph)
# nx.draw(instance_wf.graph, pos, node_color='#004a7b', node_size=2000,
# edge_color='#555555', width=1.5, edge_cmap=None,
# with_labels=True, style='dashed',
# label_pos=50.3, alpha=1, arrows=True, node_shape='s',
# font_size=8,
# font_color='#FFFFFF')
# plt.show()
# plt.savefig(filename, dpi=300, orientation='landscape', format=None,
# bbox_inches=None, pad_inches=0.1)
def view_city(self):
pos = nx.circular_layout(self.city)
node_labels = {}
for u in self.city.nodes():
node_labels[u] = u
nx.draw(self.city, pos)
nx.draw_networkx_labels(self.city, pos, labels=node_labels)
self.btnViewCity.setEnabled(True)
plt.show()
def show_topology(self):
if self.pre_link_to_port != self.link_to_port and setting.TOSHOW:
# It means the link_to_port table has changed.
_graph = self.graph.copy()
print "\n---------------------Link Port---------------------"
print '%6s' % ('switch'),
for node in sorted([node for node in _graph.nodes()], key=lambda node: node):
print '%6d' % node,
print
for node1 in sorted([node for node in _graph.nodes()], key=lambda node: node):
print '%6d' % node1,
for node2 in sorted([node for node in _graph.nodes()], key=lambda node: node):
if (node1, node2) in self.link_to_port.keys():
print '%6s' % str(self.link_to_port[(node1, node2)]),
else:
print '%6s' % '/',
print
print
self.pre_link_to_port = self.link_to_port.copy()
if self.pre_access_table != self.access_table and setting.TOSHOW:
# It means the access_table has changed.
print "\n----------------Access Host-------------------"
print '%10s' % 'switch', '%10s' % 'port', '%22s' % 'Host'
if not self.access_table.keys():
print " NO found host"
else:
for sw in sorted(self.access_table.keys()):
print '%10d' % sw[0], '%10d ' % sw[1], self.access_table[sw]
print
self.pre_access_table = self.access_table.copy()
# nx.draw(self.graph)
# plt.savefig("/home/huangmc/exe/matplotlib/%d.png" % int(time.time()))
def plot(self, output=None):
import matplotlib.pyplot as plt #pylint:disable=import-error
plt.close()
networkx.draw(self.make_graph())
if output:
plt.savefig(output)
else:
plt.show()
def visualize(G, savename, savegml):
pos = nx.spring_layout(G) # ???????????????????????????
nx.draw(G, pos, with_labels=True,alpha=0.3,font_size=0.0,node_size=10) # ?????? ????????????????????
plt.savefig(savename+".png")
plt.show()
if savegml:
nx.write_gml(G,savename+".gml")
def make_graph(list_of_edges):
G = nx.Graph()
for x in list_of_edges:
pair = tuple(x.split("-", 1))
G.add_edge(pair[0], pair[1])
print len(G.edges())
pos=nx.fruchterman_reingold_layout(G)
nx.draw(G,pos)
plt.show()
return len(list_of_edges)
def draw_dodag(path):
"""
This function draws the DODAG (to ./results) from the list of motes (from ./simulation.csc) and the list of
edges (from ./data/relationships.log).
:param path: path to the experiment (including [with-|without-malicious])
"""
pyplot.clf()
with_malicious = (basename(normpath(path)) == 'with-malicious')
data, results = join(path, 'data'), join(path, 'results')
with open(join(data, 'relationships.log')) as f:
relationships = f.read()
# first, check if the mote relationships were recorded
if len(relationships.strip()) == 0:
return
# retrieve motes and their colors
dodag = networkx.DiGraph()
motes = get_motes_from_simulation(join(path, 'simulation.csc'))
dodag.add_nodes_from(motes.keys())
colors = []
for n, p in motes.items():
x, y = p
dodag.node[n]['pos'] = motes[n] = (x, -y)
colors.append('green' if n == 0 else ('yellow' if not with_malicious or
(with_malicious and 0 < n < len(motes) - 1) else 'red'))
# retrieve edges from relationships.log
edges = {}
for relationship in relationships.split('\n'):
try:
d = match(RELATIONSHIP_REGEX, relationship.strip()).groupdict()
if int(d['flag']) == 0:
continue
mote, parent = int(d['mote_id']), int(d['parent_id'])
edges[mote] = parent
except AttributeError:
continue
# now, fill in the graph with edges
dodag.add_edges_from(edges.items())
# finally, draw the graph
networkx.draw(dodag, motes, node_color=colors, with_labels=True)
pyplot.savefig(join(results, 'dodag.png'), arrow_style=FancyArrowPatch)
def main():
edges = [] # ???????
domain_name = 'taobao.com'
domain_pkts = get_data(domain_name)
for i in domain_pkts[0]['details']:
for v in i['answers']:
edges.append((v['domain_name'],v['dm_data']))
plt.figure(1, figsize=(10, 8))
G = nx.Graph()
G.add_edges_from(edges)
pos = graphviz_layout(G, prog="fdp") #neato fdp
C = nx.connected_component_subgraphs(G) # ?????????????
for g in C:
c = [random.random()] * nx.number_of_nodes(g)
nx.draw(g,
pos,
node_size=90,
node_color=c,
vmin=0.0,
vmax=1.0,
with_labels=False
)
plt.savefig('./graph/'+domain_name+"_relation.png", dpi=75)
plt.show()
def draw(self, filename="network_view.png"):
"""
Draw this graph to a file, for debugging.
"""
import matplotlib.pyplot as plt
plt.clf()
pos = circular_layout(self.graph)
draw(self.graph, pos, with_labels=False, arrows=False, hold=False,
edge_color=[self.graph[u][v]['color'] for u,v in self.graph.edges()],
node_color=['orange' if v in self._all_addresses else 'green' for v in self.graph.nodes()])
plt.savefig(filename)
def plot_csv(target_dir='', columns=0, sep=' ', separate=False, title=None):
if type(columns) is not list:
columns = [columns]
title = title or 'LDA Inference'
xlabel = 'Iterations'
markers = cycle([ '+', '*', ',', 'o', '.', '1', 'p', ])
if not separate:
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xlabel(xlabel)
ax1.set_title(title)
for column in columns:
if separate:
fig = plt.figure()
plt.title(title)
plt.xlabel('xlabel')
ax1 = plt.gca()
filen = os.path.join(os.path.dirname(__file__), "../PyNPB/data/", target_dir)
with open(filen) as f:
data = f.read()
data = filter(None, data.split('\n'))
data = [x.strip() for x in data if not x.startswith(('#', '%'))]
ll_y = [row.split(sep)[column] for row in data]
ylabel, label = tag_from_csv(column)
ax1.set_ylabel(ylabel)
#ax1.plot(ll_y, c='r',marker='x', label='log likelihood')
ax1.plot(ll_y, marker=next(markers), label=label)
leg = ax1.legend()
plt.draw()
def log_binning(counter_dict,bin_count=35):
max_x = np.log10(max(counter_dict.keys()))
max_y = np.log10(max(counter_dict.values()))
max_base = max([max_x,max_y])
min_x = np.log10(min(drop_zeros(counter_dict.keys())))
bins = np.logspace(min_x,max_base,num=bin_count)
# Based off of: http://stackoverflow.com/questions/6163334/binning-data-in-python-with-scipy-numpy
#bin_means_y = (np.histogram(counter_dict.keys(),bins,weights=counter_dict.values())[0] / np.histogram(counter_dict.keys(),bins)[0])
#bin_means_x = (np.histogram(counter_dict.keys(),bins,weights=counter_dict.keys())[0] / np.histogram(counter_dict.keys(),bins)[0])
bin_means_y = np.histogram(counter_dict.keys(),bins,weights=counter_dict.values())[0]
bin_means_x = np.histogram(counter_dict.keys(),bins,weights=counter_dict.keys())[0]
return bin_means_x,bin_means_y
#def plot_degree(y, title=None, noplot=False):
# if len(y) > 6000:
# return
# G = nxG(y)
# degree = sorted(nx.degree(G).values(), reverse=True)
# if noplot:
# return degree
# #plt.plot(degree)
# x = np.arange(1, y.shape[0] + 1)
# fig = plt.figure()
# plt.loglog(x, degree)
# if title:
# plt.title(title)
# plt.draw()
#
#def plot_degree_(y, title=None):
# if len(y) > 6000:
# return
# G = nxG(y)
# degree = sorted(nx.degree(G).values(), reverse=True)
# x = np.arange(1, y.shape[0] + 1)
# plt.loglog(x, degree)
# if title:
# plt.title(title)
def draw_blocks(comm):
#nx.draw(H,G.position,
# node_size=[G.population[v] for v in H],
# node_color=node_color,
# with_labels=False)
blocks = comm.get('block_hist')
ties = comm.get('block_ties')
blocks = 2*blocks / np.linalg.norm(blocks)
max_n = max(blocks)
G = nx.Graph(nodesep=0.7)
u_colors.reset()
ind_color = np.arange(0, len(blocks)**2, 2) % len(u_colors.seq)
#ind_color = np.diag(np.arange(len(blocks)**2).reshape([len(blocks)]*2)) % len(u_colors.seq)
colors = np.array(u_colors.seq)[ind_color]
# if sorted
sorted_blocks, sorted_ind = zip(*sorted( zip(blocks, range(len(blocks))) , reverse=True))
for l, s in enumerate(sorted_blocks):
if s == 0:
continue
G.add_node(int(l), width=s, height=s, fillcolor=colors[l], style='filled')
max_t = max(ties, key=lambda x:x[1])[1]
if max_t > max_n:
scale = np.exp(2) * float(max_n) / max_t
for l, s in ties:
i, j = l
# if sorted
i = sorted_ind.index(int(i))
j = sorted_ind.index(int(j))
G.add_edge(i, j, penwidth = s * scale)
return write_dot(G, 'graph.dot')
def draw_graph_circular(y, clusters='blue', ns=30):
G = nxG(y)
pos = graphviz_layout(G, prog='twopi', args='')
plt.figure()
nx.draw(G, pos, node_size=ns, alpha=0.8, node_color=clusters, with_labels=False)
plt.axis('equal')
def adjshow_4(Y,title=[], pixelspervalue=20):
minvalue = np.amin(Y)
maxvalue = np.amax(Y)
cmap = plt.cm.hot
fig = plt.figure()
plt.subplot(2,2,1)
plt.axis('off')
implot = plt.imshow(Y[0], cmap=cmap, clim=(minvalue, maxvalue), interpolation='nearest')
plt.title(title[0])
plt.subplot(2,2,2)
plt.axis('off')
implot = plt.imshow(Y[1], cmap=cmap, clim=(minvalue, maxvalue), interpolation='nearest')
plt.title(title[1])
plt.subplot(2,2,3)
plt.axis('off')
implot = plt.imshow(Y[2], cmap=cmap, clim=(minvalue, maxvalue), interpolation='nearest')
plt.title(title[2])
plt.subplot(2,2,4)
plt.axis('off')
implot = plt.imshow(Y[3], cmap=cmap, clim=(minvalue, maxvalue), interpolation='nearest')
plt.title(title[3])
plt.draw()
##########################
### Curve Plot
##########################
# @deprecated
def displayMatplot():
# display in matplotlib
pos=nx.get_node_attributes(g,'pos')
nx.draw(g,pos)
plt.show()
# plt.savefig("/tmp/path.png")
def run(self):
ip_addresses = ['192.168.1.%s' % x for x in range(1, self._number_clients)]
ports = [x for x in range(1, 2)]
clients = []
progress = 0
for ip_addr in ip_addresses:
print_progress(progress, self._number_clients, suffix="Running simulation")
for port in ports:
progress += 1
client = Client(ip_addr, port, clients[0] if len(clients) > 0 else None,
max_chache_size=self._number_connections_per_client)
clients.append(client)
connection = Connection(client, clients[0])
connection.initiate()
bootstrapper_connections = clients[0].get_connections()
for conn in bootstrapper_connections:
connection = Connection(client, conn.second_client)
connection.initiate()
graph = networkx.nx.Graph()
for client in clients:
logging.error(client.get_ident())
logging.error(client.get_connection_idents())
for node in client.get_connections():
graph.add_edge(node.first_client.get_ident(), node.second_client.get_ident())
networkx.draw(graph, with_labels=False)
plt.savefig("path_graph.pdf")
print("Network is connected: %s" % networkx.is_connected(graph))
print("Average shortest path length: %s" % networkx.average_shortest_path_length(graph))
print("Average bipartite clustering coefficent %s" % networkx.average_clustering(graph))
print("Bipartite clustering coefficent %s" % networkx.clustering(graph))
print("degree_assortativity_coefficient %s" % networkx.degree_assortativity_coefficient(graph))