本文整理汇总了Python中networkx.diameter函数的典型用法代码示例。如果您正苦于以下问题:Python diameter函数的具体用法?Python diameter怎么用?Python diameter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了diameter函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compare_graphs
def compare_graphs(graph):
n = nx.number_of_nodes(graph)
m = nx.number_of_edges(graph)
k = np.mean(list(nx.degree(graph).values()))
erdos = nx.erdos_renyi_graph(n, p=m/float(n*(n-1)/2))
barabasi = nx.barabasi_albert_graph(n, m=int(k)-7)
small_world = nx.watts_strogatz_graph(n, int(k), p=0.04)
print(' ')
print('Compare the number of edges')
print(' ')
print('My network: ' + str(nx.number_of_edges(graph)))
print('Erdos: ' + str(nx.number_of_edges(erdos)))
print('Barabasi: ' + str(nx.number_of_edges(barabasi)))
print('SW: ' + str(nx.number_of_edges(small_world)))
print(' ')
print('Compare average clustering coefficients')
print(' ')
print('My network: ' + str(nx.average_clustering(graph)))
print('Erdos: ' + str(nx.average_clustering(erdos)))
print('Barabasi: ' + str(nx.average_clustering(barabasi)))
print('SW: ' + str(nx.average_clustering(small_world)))
print(' ')
print('Compare average path length')
print(' ')
print('My network: ' + str(nx.average_shortest_path_length(graph)))
print('Erdos: ' + str(nx.average_shortest_path_length(erdos)))
print('Barabasi: ' + str(nx.average_shortest_path_length(barabasi)))
print('SW: ' + str(nx.average_shortest_path_length(small_world)))
print(' ')
print('Compare graph diameter')
print(' ')
print('My network: ' + str(nx.diameter(graph)))
print('Erdos: ' + str(nx.diameter(erdos)))
print('Barabasi: ' + str(nx.diameter(barabasi)))
print('SW: ' + str(nx.diameter(small_world)))
示例2: testRun
def testRun(self):
sim = watts_strogatz.WS()
sim.run(
steps=self.starting_network_size,
rewiring_probability=self.rewiring_probability,
lattice_connections=self.lattice_connections,
starting_network_size=self.starting_network_size)
with sim.graph.handle as graph:
self.assertEqual(
self.comparison_graph.number_of_nodes(),
graph.number_of_nodes())
self.assertEqual(
self.comparison_graph.number_of_edges(),
graph.number_of_edges())
if False:
self.assertAlmostEqual(
nx.diameter(self.comparison_graph),
nx.diameter(graph),
delta=1.
)
self.assertAlmostEqual(
nx.average_shortest_path_length(self.comparison_graph),
nx.average_shortest_path_length(graph),
delta=1.
)
示例3: make_graph
def make_graph(self,save_graph=True):
graph = nx.DiGraph()
all_tweets = [tweet for page in self.results for tweet in page['results']]
for tweet in all_tweets:
rt_sources = self.get_rt_sources(tweet["text"])
if not rt_sources: continue
for rt_source in rt_sources:
graph.add_edge(rt_source, tweet["from_user"], {"tweet_id": tweet["id"]})
#--Calculate graph summary statistics
if nx.is_connected(graph.to_undirected()):
diameter = nx.diameter(graph.to_undirected())
average_shortest_path = nx.average_shortest_path_length(graph.to_undirected())
print 'Diameter: ', diameter
print 'Average Shortest Path: ',average_shortest_path
else:
print "Graph is not connected so calculating the diameter and average shortest path length on all connected components."
diameter = []
average_shortest_path = []
for subgraph in nx.connected_component_subgraphs(graph.to_undirected()):
diameter.append(nx.diameter(subgraph))
average_shortest_path.append(nx.average_shortest_path_length(subgraph))
from numpy import median
from scipy.stats import scoreatpercentile
print 'Diameter: ',median(diameter),u'\xB1',str(scoreatpercentile(diameter,75)-scoreatpercentile(diameter,25))
print 'Average Path Length :',median(average_shortest_path),u'\xB1',str(scoreatpercentile(average_shortest_path,75)-scoreatpercentile(average_shortest_path,25))
degree_sequence=sorted(nx.degree(graph).values(),reverse=True) # degree sequence
import matplotlib.pyplot as plt
plt.loglog(degree_sequence,'b-',marker='o')
plt.title("Distribution of Degrees for %s tweets" %(self.drug_name), fontsize=20)
plt.ylabel("Degree", fontsize=20)
plt.xlabel("Rank", fontsize=20)
# draw graph in inset
ax = plt.axes([0.35,0.25,0.55,0.55])
plt.axis('off')
nx.draw(graph, ax=ax, alpha=0.8, with_labels=False)
plt.savefig("degree_distribution_%s.png"%(self.drug_name.replace(' ','_')), dpi=300)
plt.close()
if save_graph:
output_file = self.drug_name.replace(' ','_') + '.dot'
try:
nx.drawing.write_dot(graph,output_file)
print 'Graph saved as ',output_file
except (ImportError, UnicodeEncodeError) as e:
dot = ['"%s" -> "%s" [tweetid=%s]' % (node1,node2,graph[node1][node2]['tweet_id'])
for node1,node2, in graph.edges()]
with codecs.open(output_file,'w', encoding='utf-8') as f:
f.write('strict digraph G{\n%s\n}' % (';\n'.join(dot),))
print 'Saved ',output_file,' by brute force'
return diameter, average_shortest_path
示例4: attaccoPercent
def attaccoPercent(compagnia, steps):
adiacenzaFinal = numpy.genfromtxt(("/home/protoss/Documenti/Siscomp_datas/data/AdiacenzaEuclidea_{0}.csv".format(compagnia)),delimiter=',',dtype='int')
grafoFinal = networkx.Graph(adiacenzaFinal)
graphSize = networkx.number_of_nodes(grafoFinal)
passo = networkx.number_of_nodes(grafoFinal)/steps
i = 0
ascisse.append(i)
aziendaFinal.append(compagnia)
diametro.append(2)
relSizeGC.append(1)
while (networkx.number_of_nodes(grafoFinal) > passo):
gradiFinal = pandas.DataFrame(grafoFinal.degree().items(), columns=['index', 'grado'])
gradiFinal.sort(["grado"], ascending=[False], inplace=True)
sortedIDnode = gradiFinal['index'].values
# grafoFinal.remove_nodes_from(sortedIDnode[0:passo])
for identificativo in sortedIDnode:
if (networkx.number_of_nodes(grafoFinal) > len(sortedIDnode) - passo):
grafoFinal.remove_node(identificativo)
giantCluster = max(networkx.connected_component_subgraphs(grafoFinal), key = len)
i += 100/float(steps)
ascisse.append(i)
aziendaFinal.append(compagnia)
graphSize = networkx.number_of_nodes(grafoFinal)
diametro.append(networkx.diameter(giantCluster, e=None))
relSizeGC.append((networkx.number_of_nodes(giantCluster))/(float(graphSize)))
示例5: calc_D
def calc_D(G):
'''
A function to calculate the diameter
input parameters:
G: A graph in networkX format.
returns:
D: The diameter, which is the largest diameter among all the sub
components.
'''
subD = []
subGs = list(nx.connected_component_subgraphs(G))
indsubG = 1
for H in subGs:
if len(H.nodes())>1:
print('D: Subgraph '+str(indsubG)+' with '+str(len(H.nodes()))+' nodes')
subD.append(nx.diameter(H))
else:
subD.append(0)
indsubG += 1
# returning the maximum diameter among all the sub components
D = np.max(subD)
return D
示例6: min_connectivity
def min_connectivity(self, graph):
apnc = nx.all_pairs_node_connectivity(graph)
# start with graph diameter; minimum won't be larger than this
mc = nx.diameter(graph)
for targets in apnc.itervalues():
mc = min(min(targets.itervalues()), mc)
return mc
示例7: printStats
def printStats(filename):
'''
Converts json adjacency list into networkx to calculate and print the
graphs's
- average clustering coefficient
- overall clustering coefficient
- maximum diameter
- average diameter
- number of paritions using community.best_parition
- modularity of community.best_partition
'''
g = makeGraphFromJSON(filename)
print "Average Clustering Coefficient: %f" % nx.average_clustering(g)
print "Overall Clustering Coefficient: %f" % nx.transitivity(g)
connected_subgraphs = list(nx.connected_component_subgraphs(g))
largest = max(nx.connected_component_subgraphs(g), key=len)
print "# Connected Components: %d" % len(connected_subgraphs)
print " Maximal Diameter: %d" % nx.diameter(largest)
print " Average Diameter: %f" % nx.average_shortest_path_length(largest)
# Find partition that maximizes modularity using Louvain's algorithm
part = community.best_partition(g)
print "# Paritions: %d" % (max(part.values()) + 1)
print "Louvain Modularity: %f" % community.modularity(part, g)
示例8: strongly_connected_components
def strongly_connected_components():
conn = sqlite3.connect("zhihu.db")
#following_data = pd.read_sql('select user_url, followee_url from Following where followee_url in (select user_url from User where agree_num > 50000) and user_url in (select user_url from User where agree_num > 50000)', conn)
following_data = pd.read_sql('select user_url, followee_url from Following where followee_url in (select user_url from User where agree_num > 10000) and user_url in (select user_url from User where agree_num > 10000)', conn)
conn.close()
G = nx.DiGraph()
cnt = 0
for d in following_data.iterrows():
G.add_edge(d[1][0],d[1][1])
cnt += 1
print 'links number:', cnt
scompgraphs = nx.strongly_connected_component_subgraphs(G)
scomponents = sorted(nx.strongly_connected_components(G), key=len, reverse=True)
print 'components nodes distribution:', [len(c) for c in scomponents]
#plot graph of component, calculate saverage_shortest_path_length of components who has over 1 nodes
index = 0
print 'average_shortest_path_length of components who has over 1 nodes:'
for tempg in scompgraphs:
index += 1
if len(tempg.nodes()) != 1:
print nx.average_shortest_path_length(tempg)
print 'diameter', nx.diameter(tempg)
print 'radius', nx.radius(tempg)
pylab.figure(index)
nx.draw_networkx(tempg)
pylab.show()
# Components-as-nodes Graph
cG = nx.condensation(G)
pylab.figure('Components-as-nodes Graph')
nx.draw_networkx(cG)
pylab.show()
示例9: ltDecomposeTestBatFull
def ltDecomposeTestBatFull(dsName, path, outfile, cd, wccOnly, revEdges, undir, diaF, fillF):
origNet = loadNw(dsName, path, cd, wccOnly, revEdges, undir)
prodNet = origNet
# prodNet = copy.deepcopy(origNet)
# print("dc")
outfile = open(path + outfile + ".csv", "w")
intFlag = False
print("NW-WIDE MEASURES:\n")
nodeStr = str(origNet.number_of_nodes())
edgeStr = str(origNet.number_of_edges())
avgDeg = str(float(origNet.number_of_edges()) / float(origNet.number_of_nodes()))
dens = str(nx.density(origNet))
avgCl = "--"
# avgCl = str(nx.average_clustering(origNet))
if diaF:
print(" Starting dia calc")
diameter = str(nx.diameter(origNet))
print(" --> done w. dia calc")
else:
diameter = "---"
# outfile.write("Dataset,NumNodes,NumEdges,avgDeg,dens,avgCl,diameter\n")
# outfile.write(dsName+","+nodeStr+","+edgeStr+","+avgDeg+","+dens+","+avgCl+","+diameter+"\n")
# if fillF:
# print("FULL THRESH TEST\n")
# outfile.write("Dataset,ThreshType,ThreshVal,PercSize,NumNodes,NumEdges,TimeAlg,TimeAlgAndSetup,Check\n")
# thresh=1.0
# outfile.write(ltDecomposeNoSetWithCheck(prodNet,thresh,dsName,intFlag,origNet))
outfile.close()
print("Done.")
示例10: topologyNetx
def topologyNetx(gestore):
adiacenza = numpy.genfromtxt("/home/protoss/Documenti/Siscomp_datas/data/AdiacenzaEuclidea_{0}.csv".format(gestore),delimiter=',',dtype='int')
grafo = networkx.Graph(adiacenza)
c = networkx.average_clustering(grafo)
d = networkx.diameter(grafo)
l = networkx.average_shortest_path_length(grafo)
return c, d, l
示例11: NetStats
def NetStats(G):
return { 'radius': nx.radius(G),
'diameter': nx.diameter(G),
'connected_components': nx.number_connected_components(G),
'density' : nx.density(G),
'shortest_path_length': nx.shortest_path_length(G),
'clustering': nx.clustering(G)}
示例12: get_diameters
def get_diameters(graph):
connected_components = nx.connected_component_subgraphs(graph)
print "number of connected components: ", len(connected_components)
diameters = []
for subgraph in connected_components:
diameters.append((len(subgraph), nx.diameter(subgraph)))
print "diameters: ", diameters
示例13: getDiameter
def getDiameter(self):
graph = self.getGraph()
try:
diameter = nx.diameter(graph)
# NetworkX will throw an exception if the graph is not connected (~ infinite diameter)
except nx.NetworkXError:
return -1
示例14: write_network_characteristics
def write_network_characteristics(g):
nodes = len(g.nodes())
edges = len(g.edges())
avg_degree = float(2*edges)/nodes
max_conn = (nodes*(nodes-1))/2
clustering = nx.average_clustering(g)
density = nx.density(g)
diameter = nx.diameter(g)
a_p_l = nx.average_shortest_path_length(g)
conn = nx.is_connected(g)
n_comp_con = nx.number_connected_components(g)
# write them on file
out = open("statistics_giant.csv", "w")
out.write("#Nodes,#Edges,Avg_Degree, Max Connection, Clustering Coefficient, Density, Diameter , Average Shortest Path , Is Connected? , Number Connected Component\n")
out.write("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n" % (nodes, edges, avg_degree , max_conn, clustering, density ,diameter ,a_p_l, conn , n_comp_con))
g = read_graph("dataset/cutted_graph(0.15).csv")
degree_distribution(g0)
#Extract max Giant component
cc=sorted(nx.connected_component_subgraphs(g), key = len, reverse=True)
g0=gcc[0]
write_network_characteristics(g0)
示例15: write_network
def write_network(network, time, targets, seed, filename="network.dat"):
print("\tDetermining network type.")
if isinstance(network,nx.DiGraph):
network_type = "Directed"
else:
network_type = "Undirected"
print("\tCalculaing edges and vertices.")
edges = network.number_of_edges()
vertices = network.number_of_nodes()
undirected = network.to_undirected()
print("\tFinding subgraphs.")
subgraphs = nx.connected_component_subgraphs(undirected)
print("\tFinding network diameter.")
diameter = nx.diameter(subgraphs[0])
print("\tStoring network parameters")
out = open(filename, "w")
out.write("Simulation name: {0}\n\n".format(time))
out.write("Network properties\n===============\n")
out.write("Network type: {0}\n".format(network_type))
out.write("Number of vertices: {0}\n".format(vertices))
out.write("Number of edges: {0}\n".format(edges))
out.write("Diameter: {0}\n".format(diameter))
out.close()