本文整理汇总了Python中networkx.is_strongly_connected函数的典型用法代码示例。如果您正苦于以下问题:Python is_strongly_connected函数的具体用法?Python is_strongly_connected怎么用?Python is_strongly_connected使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_strongly_connected函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_is_strongly_connected
def test_is_strongly_connected(self):
ncc=nx.number_strongly_connected_components
for G,C in self.gc:
if len(C)==1:
assert_true(nx.is_strongly_connected(G))
else:
assert_false(nx.is_strongly_connected(G))
示例2: test_scipy_sparse_eigs
def test_scipy_sparse_eigs(G, CN_name, self_link=False, seed_creation=False):
eps = gm.epsilon
print 'percentage of non-zero elements: '+str(float(np.count_nonzero(Transition_Matrix))/G.number_of_nodes()**2)
print 'is strongly connected? '+str(nx.is_strongly_connected(G))+'\nis aperiodic? '+str(nx.is_aperiodic(G))
M = salsa.get_matrix(G, mat_type='hub', sparse=True)
CN_index = G.nodes().index(CN_name)
M = gm.convert_SL_and_CN_weights_to_val(M, val=eps, CN_idx=CN_index, stochastic_out=True)
new_G = nx.DiGraph(M)
print 'AFTER get matrix:\npercentage of non-zero elements: ' + str(float(M.getnnz())/G.number_of_nodes()**2)
print 'is strongly connected? '+str(nx.is_strongly_connected(new_G))+'\nis aperiodic? '+str(nx.is_aperiodic(new_G))
print 'is stochastic? '+str(gm.check_if_stochastic_matrix(M.todense()))
print M
print M.shape[0]
#M_pow = np.linalg.matrix_power(M.todense(), 111)
#print M_pow
e,ev=sp.sparse.linalg.eigen.arpack.eigs(M.copy().T, k=1,sigma=1, which='LM')#, maxiter=100000)
h = ev/ev.sum()
print e; print h;
if (h.imag.sum() != 0.):
print '##### COMPLEX VECTOR!!!! #####'
print map(float,h.real)
'''e1,ev1=sp.linalg.eig(M.todense(),left=True,right=False)
m=e1.argsort()[-1]
evMax1=np.array(ev1[:,m]).flatten()
print '\n\tnp.linalg.eig(left)\n' + str(e1[m]) + '\n' + str(evMax1)
'''
return
示例3: directed_stats
def directed_stats(self):
# UG = nx.to_undirected(g) #claims to not have this function
if nx.is_strongly_connected(g):
sconl = nx.strongly_connected_components(g)
else: sconl = 'NA - graph is not strongly connected'
result = {#"""returns boolean"""
'scon': nx.is_strongly_connected(g),
'sconn': nx.number_connected_components(g),
# """returns boolean"""
'dag': nx.is_directed_acyclic_graph(g),
# """returns lists"""
'sconl': nx.strongly_connected_components(g),
#Conl = connected_component_subgraphs(Ug)
}
return result
示例4: test_hsdf_analysis
def test_hsdf_analysis(n = 15, p = 0.2, runs = 10000, debug = None):
for run in range(runs) if debug is None else [debug]:
sdfg = random_sdf_graph(n, p, seed = run)
vectors = core.check_consistency(sdfg)
assert nx.is_strongly_connected( sdfg )
# Analysis of single-rate equivalent
hsdfg = transform.single_rate_equivalent( sdfg, vectors['q'] )
mg = make_marked_graph(hsdfg)
# HSDF graph may not be strongly connected, compute its strongly connected components
condensed = nx.DiGraph()
idx = 0
scc_idx = {}
graph_mcr = None
for scc in nx.strongly_connected_components(mg):
idx += 1
for v in scc:
scc_idx[v] = idx
cycletime, _, _ = mcr.compute_mcr(nx.subgraph(mg, scc), next(iter(scc)))
condensed.add_node(idx, mcr = cycletime, size = len(scc))
graph_mcr = cycletime if graph_mcr is None else max(cycletime, graph_mcr)
for v, w in mg.edges_iter():
if scc_idx[v] != scc_idx[w]:
condensed.add_edge( scc_idx[v], scc_idx[w] )
critical_size = mg.number_of_nodes()
for v, data in condensed.nodes(data = True):
d_in = condensed.in_degree(v)
d_out = condensed.out_degree(v)
if d_in == 0:
critical_size = data['size']
if d_in == 0 and data['mcr'] < graph_mcr:
raise AssertionError("Run {}: SCC {} has MCR {} < {}".format(run, v, data['mcr'], graph_mcr))
if d_in > 1 or d_out > 1:
pass
# raise AssertionError("Run {}: SCC {}: in-degree = {}, out-degree = {}".format(run, v, d_in, d_out))
if debug:
import pdb; pdb.set_trace()
unfolded, _, _ = transform.unfold_depth_first( sdfg, vectors['q'], vectors['s'], vectors['q'] )
assert nx.is_strongly_connected( unfolded )
print("Run {:05}: MCR = {}, condensed: {} nodes. HSDF size: {}. Compression: {:.3f}".format(run, graph_mcr, condensed.number_of_nodes(), hsdfg.number_of_nodes(), hsdfg.number_of_nodes() / critical_size))
示例5: gen_network
def gen_network(graph,machines,basedata):
""" Generates an LLD network from a graph
distributing participants in a list of machines
"""
network = ET.Element('network')
#network.set('type',graphtype)
network.set('participants',str(graph.number_of_nodes()))
network.set('edges',str(graph.size()))
network.set('density',str(NX.density(graph)))
network.set('connected',str(NX.is_weakly_connected(graph)))
network.set('stronglyconnected',str(NX.is_strongly_connected(graph)))
for node in graph.nodes_iter():
nodelement = ET.SubElement(network,'participant')
nodelement.set('id','participant'+str(node))
hostelem = ET.SubElement(nodelement,'host')
#hostelem.text = 'node'+str(int(node) % len(machines))
hostelem.text = machines[int(node) % len(machines)]
portelem = ET.SubElement(nodelement,'port')
portelem.text = str(20500+int(node))
baseelem = ET.SubElement(nodelement,'basedata')
baseelem.text = basedata
nodelement.append(gen_dynamic())
for source in gen_sources(graph,node):
nodelement.append(source)
return network
示例6: netstats_listsdi
def netstats_listsdi(graph):
G = graph
# UG = nx.to_undirected(G) #claims to not have this function
if nx.is_strongly_connected(G):
sconl = nx.strongly_connected_components(G)
else: sconl = 'NA - graph is not strongly connected'
result = {#"""returns boolean"""
'scon': nx.is_strongly_connected(G),
'sconn': nx.number_connected_components(G),
# """returns boolean"""
'dag': nx.is_directed_acyclic_graph(G),
# """returns lists"""
'sconl': nx.strongly_connected_components(G),
# Conl = connected_component_subgraphs(UG)
}
return result
示例7: create_shortest_path_matrix
def create_shortest_path_matrix(weighted=False, discount_highways=False):
G = nx.DiGraph()
logging.info("Loading graph to NetworkX from database...")
c = connection.cursor()
if discount_highways:
c.execute("SELECT l.beg_node_id, l.end_node_id, (CASE WHEN l.link_type='1' THEN 0.5 WHEN l.link_type='2' THEN 0.5 ELSE 1.0 END) FROM microsim_link l")
else:
c.execute("SELECT l.beg_node_id, l.end_node_id, l.length/l.lane_count AS resistance FROM microsim_link l")
G.add_weighted_edges_from(c.fetchall())
logging.debug("Road network is strongly connected: %s" % repr(nx.is_strongly_connected(G)))
logging.info("Computing shortest paths...")
if weighted:
sp = nx.all_pairs_dijkstra_path_length(G)
else:
sp = nx.all_pairs_shortest_path_length(G)
logging.info("Converting shortest paths into matrix...")
c.execute("SELECT ROW_NUMBER() OVER (ORDER BY id), beg_node_id, end_node_id FROM microsim_link")
links = c.fetchall()
N_LINKS = len(links)
shortest_paths = np.zeros((N_LINKS, N_LINKS))
for col_idx, _, col_end_node in links:
for row_idx, _, row_end_node in links:
if col_idx == row_idx:
continue
nodes = sp[col_end_node]
if row_end_node not in nodes:
shortest_paths[row_idx - 1, col_idx - 1] = float(N_LINKS)
else:
shortest_paths[row_idx - 1, col_idx - 1] = nodes[row_end_node]
logging.info("Shortest path matrix complete.")
return shortest_paths
示例8: draw_graph
def draw_graph(nodes, edges, graphs_dir, default_lang='all'):
lang_graph = nx.MultiDiGraph()
lang_graph.add_nodes_from(nodes)
for edge in edges:
if edges[edge] == 0:
lang_graph.add_edge(edge[0], edge[1])
else:
lang_graph.add_edge(edge[0], edge[1], weight=float(edges[edge]), label=str(edges[edge]))
# print graph info in stdout
# degree centrality
print('-----------------\n\n')
print(default_lang)
print(nx.info(lang_graph))
try:
# When ties are associated to some positive aspects such as friendship or collaboration,
# indegree is often interpreted as a form of popularity, and outdegree as gregariousness.
DC = nx.degree_centrality(lang_graph)
max_dc = max(DC.values())
max_dc_list = [item for item in DC.items() if item[1] == max_dc]
except ZeroDivisionError:
max_dc_list = []
# https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BC%D0%BF%D0%BB%D0%B5%D0%BA%D1%81%D0%BD%D1%8B%D0%B5_%D1%81%D0%B5%D1%82%D0%B8
print('maxdc', str(max_dc_list), sep=': ')
# assortativity coef
AC = nx.degree_assortativity_coefficient(lang_graph)
print('AC', str(AC), sep=': ')
# connectivity
print("Слабо-связный граф: ", nx.is_weakly_connected(lang_graph))
print("количество слабосвязанных компонент: ", nx.number_weakly_connected_components(lang_graph))
print("Сильно-связный граф: ", nx.is_strongly_connected(lang_graph))
print("количество сильносвязанных компонент: ", nx.number_strongly_connected_components(lang_graph))
print("рекурсивные? компоненты: ", nx.number_attracting_components(lang_graph))
print("число вершинной связности: ", nx.node_connectivity(lang_graph))
print("число рёберной связности: ", nx.edge_connectivity(lang_graph))
# other info
print("average degree connectivity: ", nx.average_degree_connectivity(lang_graph))
print("average neighbor degree: ", sorted(nx.average_neighbor_degree(lang_graph).items(),
key=itemgetter(1), reverse=True))
# best for small graphs, and our graphs are pretty small
print("pagerank: ", sorted(nx.pagerank_numpy(lang_graph).items(), key=itemgetter(1), reverse=True))
plt.figure(figsize=(16.0, 9.0), dpi=80)
plt.axis('off')
pos = graphviz_layout(lang_graph)
nx.draw_networkx_edges(lang_graph, pos, alpha=0.5, arrows=True)
nx.draw_networkx(lang_graph, pos, node_size=1000, font_size=12, with_labels=True, node_color='green')
nx.draw_networkx_edge_labels(lang_graph, pos, edges)
# saving file to draw it with dot-graphviz
# changing overall graph view, default is top-bottom
lang_graph.graph['graph'] = {'rankdir': 'LR'}
# marking with blue nodes with maximum degree centrality
for max_dc_node in max_dc_list:
lang_graph.node[max_dc_node[0]]['fontcolor'] = 'blue'
write_dot(lang_graph, os.path.join(graphs_dir, default_lang + '_links.dot'))
# plt.show()
plt.savefig(os.path.join(graphs_dir, 'python_' + default_lang + '_graph.png'), dpi=100)
plt.close()
示例9: is_eulerian
def is_eulerian(G):
"""Returns ``True`` if and only if ``G`` is Eulerian.
An graph is *Eulerian* if it has an Eulerian circuit. An *Eulerian
circuit* is a closed walk that includes each edge of a graph exactly
once.
Parameters
----------
G : NetworkX graph
A graph, either directed or undirected.
Examples
--------
>>> nx.is_eulerian(nx.DiGraph({0: [3], 1: [2], 2: [3], 3: [0, 1]}))
True
>>> nx.is_eulerian(nx.complete_graph(5))
True
>>> nx.is_eulerian(nx.petersen_graph())
False
Notes
-----
If the graph is not connected (or not strongly connected, for
directed graphs), this function returns ``False``.
"""
if G.is_directed():
# Every node must have equal in degree and out degree and the
# graph must be strongly connected
return (all(G.in_degree(n) == G.out_degree(n) for n in G)
and nx.is_strongly_connected(G))
# An undirected Eulerian graph has no vertices of odd degree and
# must be connected.
return all(d % 2 == 0 for v, d in G.degree()) and nx.is_connected(G)
示例10: test_load_call_graph_return_edges_file_granularity
def test_load_call_graph_return_edges_file_granularity(self):
# Act
graph = self.target.load_call_graph(granularity=Gran.FILE)
# Assert
self.assertTrue(nx.is_strongly_connected(graph))
for (u, v) in nx.get_edge_attributes(graph, 'call'):
self.assertTrue('return' in graph[v][u])
示例11: prog_27
def prog_27(fname):
graph = nx.DiGraph()
f = open(fname)
ns,es = map(int, f.readline().strip().split())
graph.add_nodes_from(range(1,ns+1))
for line in f:
e1,e2 = map(int, line.strip().split())
graph.add_edge(e1,e2)
f.close()
print nx.is_strongly_connected(graph)
# print 'xxxxxxxx'
print nx.number_strongly_connected_components(graph)
示例12: test_networkx_methods
def test_networkx_methods():
reducible_G = nx.DiGraph(np.matrix([[1,0],[0,1]]))
print 'reducible- is strongly connected? ' + str(nx.is_strongly_connected(reducible_G)) #False
print 'reducible- strongly connected components: ' + str(nx.strongly_connected_components(reducible_G)) #[[0], [1]]
print 'reducible- is aperiodic? ' + str(nx.is_aperiodic(reducible_G)) #True
irreducible_periodic_G = nx.DiGraph(np.matrix([[0,1],[1,0]]))
print '\nirreducible_periodic- is strongly connected? ' + str(nx.is_strongly_connected(irreducible_periodic_G)) #True
print 'irreducible_periodic- strongly connected components: ' + str(nx.strongly_connected_components(irreducible_periodic_G)) #[[0, 1]]
print 'irreducible_periodic- is aperiodic? ' + str(nx.is_aperiodic(irreducible_periodic_G)) #False (2)
ergodic_G = nx.DiGraph(np.matrix([[0,1,1,0],[1,0,0,1],[0,1,0,0],[0,1,0,0]]))
modified_G = nx.DiGraph(salsa.get_matrix(ergodic_G, mat_type='hub', sparse=False))
print 'modified- is strongly connected? ' + str(nx.is_strongly_connected(modified_G)) #False
print 'modified- strongly connected components: ' + str(nx.strongly_connected_components(modified_G)) #[[0, 2, 3], [1]]
print 'modified- is aperiodic? ' + str(nx.is_aperiodic(modified_G)) #True
return
示例13: test_load_call_graph_return_edges_file_granularity
def test_load_call_graph_return_edges_file_granularity(self):
# Act
test_graph = self.test_loader.load_call_graph(granularity=Gran.FILE)
# Assert
call_edges = nx.get_edge_attributes(test_graph, 'call')
self.assertTrue(nx.is_strongly_connected(test_graph))
for (u, v) in call_edges:
self.assertTrue('return' in test_graph[v][u])
示例14: output_conectivity_info
def output_conectivity_info (graph, path):
"""Output connectivity information about the graph.
graph : (networkx.Graph)
path: (String) contains the path to the output file
"""
with open(path, 'w') as out:
out.write('***Conectivity***\n')
out.write('Is weakly connected: %s\n' % nx.is_weakly_connected(graph))
out.write('Number of weakly connected components: %d\n' % nx.number_weakly_connected_components(graph))
out.write('Is strongly connected: %s\n' % nx.is_strongly_connected(graph))
out.write('Number of strongly connected components: %d' % nx.number_strongly_connected_components(graph))
示例15: get_relation_node_free_graph
def get_relation_node_free_graph(self):
if nx.is_strongly_connected(self):
raise ArgGraphException(('Cannot produce relation node free graph.'
'Arggraph contains cycles.'))
if False in [self.out_degree(node) <= 1 for node in self.nodes()]:
raise ArgGraphException(('Cannot produce relation node free graph.'
'Nodes with multiple outgoing edges.'))
a = ArgGraph(self)
if ('relation-node-free' in a.graph and
a.graph['relation-node-free'] == True):
return a
# reduce multi-source relations to adu.addsource->adu
for rel_node in [node for node, d in a.nodes(data=True)
if a.out_degree(node) >= 1 and d['type'] == 'rel']:
sources = sorted_nicely(
[source for source in a.predecessors(rel_node)
if a.node[source]['type'] == 'adu']
)
for source in sources[1:]:
a.remove_edge(source, rel_node)
a.add_edge(source, sources[0], type="add")
# first reduce rel->rel
remove_nodes = []
remove_edges = []
for (src, trg, d) in a.edges(data=True):
if a.node[src]['type'] == 'rel' and a.node[trg]['type'] == 'rel':
src_pre = a.predecessor_by_edge_type(src, 'src')[0]
trg_pre = a.predecessor_by_edge_type(trg, 'src')[0]
a.remove_edge(src, trg)
a.add_edge(src_pre, trg_pre, type=d['type'])
remove_edges.append((src_pre, src, ))
remove_nodes.append(src)
for src, trg in remove_edges:
a.remove_edge(src, trg)
for node in remove_nodes:
a.remove_node(node)
# then reduce rel->adu (remaining relnodes)
for (src, trg, d) in a.edges(data=True):
if a.node[src]['type'] == 'rel' and a.node[trg]['type'] == 'adu':
src_pre = a.predecessors(src)[0]
a.add_edge(src_pre, trg, type=d['type'])
a.remove_edge(src_pre, src)
a.remove_edge(src, trg)
a.remove_node(src)
a.graph['relation-node-free'] = True
return a