本文整理汇总了Python中networkx.is_aperiodic函数的典型用法代码示例。如果您正苦于以下问题:Python is_aperiodic函数的具体用法?Python is_aperiodic怎么用?Python is_aperiodic使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了is_aperiodic函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_is_aperiodic_disconnected
def test_is_aperiodic_disconnected():
# disconnected graph
G = nx.DiGraph()
nx.add_cycle(G, [1, 2, 3, 4])
nx.add_cycle(G, [5, 6, 7, 8])
assert_false(nx.is_aperiodic(G))
G.add_edge(1, 3)
G.add_edge(5, 7)
assert_true(nx.is_aperiodic(G))
示例2: output_aperiodicity_info
def output_aperiodicity_info (graph, path):
"""Output aperiodicity information about the graph.
graph : (networkx.Graph)
path: (String) contains the path to the output file
"""
with open(path, 'w') as out:
out.write('***Aperiodicity***\n')
out.write('Is aperiodic: %s' % nx.is_aperiodic(graph))
示例3: is_aperiodic
def is_aperiodic(G):
"""Return True if G is aperiodic.
A directed graph is aperiodic if there is no integer k > 1 that
divides the length of every cycle in the graph.
Parameters
----------
G : NetworkX DiGraph
Graph
Returns
-------
aperiodic : boolean
True if the graph is aperiodic False otherwise
Raises
------
NetworkXError
If G is not directed
Notes
-----
This uses the method outlined in [1]_, which runs in O(m) time
given m edges in G. Note that a graph is not aperiodic if it is
acyclic as every integer trivial divides length 0 cycles.
References
----------
.. [1] Jarvis, J. P.; Shier, D. R. (1996),
Graph-theoretic analysis of finite Markov chains,
in Shier, D. R.; Wallenius, K. T., Applied Mathematical Modeling:
A Multidisciplinary Approach, CRC Press.
"""
if not G.is_directed():
raise nx.NetworkXError(
"is_aperiodic not defined for undirected graphs")
s = arbitrary_element(G)
levels = {s: 0}
this_level = [s]
g = 0
l = 1
while this_level:
next_level = []
for u in this_level:
for v in G[u]:
if v in levels: # Non-Tree Edge
g = gcd(g, levels[u] - levels[v] + 1)
else: # Tree Edge
next_level.append(v)
levels[v] = l
this_level = next_level
l += 1
if len(levels) == len(G): # All nodes in tree
return g == 1
else:
return g == 1 and nx.is_aperiodic(G.subgraph(set(G) - set(levels)))
示例4: 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
示例5: test_eig_error
def test_eig_error():
#graph_file = '/home/michal/SALSA_files/tmp/real_run/graph_11'
#G = gm.read_graph_from_file(graph_file)
graph_list = [(354, 354, {'weight': 0.5}),\
(354, 13291, {'weight': 0.25}),\
(354, 11354, {'weight': 0.25}),\
(15204, 15204, {'weight': 0.5}),\
(15204, 14639, {'weight': 0.5}),\
(11210, 6898, {'weight': 0.25}),\
(11210, 11210, {'weight': 0.5}),\
(11210, 11354, {'weight': 0.25}),\
(13291, 354, {'weight': 0.5}),\
(13291, 13291, {'weight': 0.5}),\
(14639, 13236, {'weight': 0.16666666666666666}),\
(14639, 6898, {'weight': 0.16666666666666666}),\
(14639, 15204, {'weight': 0.25}),\
(14639, 14639, {'weight': 0.41666666666666663}),\
(6898, 6898, {'weight': 0.6111111111111112}),\
(6898, 13236, {'weight': 0.1111111111111111}),\
(6898, 11210, {'weight': 0.16666666666666666}),\
(6898, 14639, {'weight': 0.1111111111111111}),\
(13236, 6898, {'weight': 0.3333333333333333}),\
(13236, 13236, {'weight': 0.3333333333333333}),\
(13236, 14639, {'weight': 0.3333333333333333}),\
(11354, 11210, {'weight': 0.25}),\
(11354, 354, {'weight': 0.25}),\
(11354, 11354, {'weight': 0.5})]
#(11354, 11354, {'weight': 0.5})]
G = nx.DiGraph(graph_list)
#print G.edges(data=True)
print '--- eig_calc: is sub graph stochastic? ' + str(gm.check_if_stochastic_matrix(nx.to_numpy_matrix(G)))#; sys.stdout.flush()
print '--- eig_calc: is sub graph strongly connected? ' + str(nx.is_strongly_connected(G))#; sys.stdout.flush()
print '--- eig_calc: is sub graph aperiodic? ' + str(nx.is_aperiodic(G));# sys.stdout.flush()
#np_mat = nx.to_numpy_matrix(G)
#print 'det= '+ str(np.linalg.det(np_mat))
print salsa.eig_calc(G)
'''try:
print salsa.eig_calc(G)
except RuntimeError:
max_weight = max(e[2]['weight'] for e in G.edges_iter(data=True))
noise = 1e-13
for e in G.edges_iter(data=True):
if e[2]['weight'] == max_weight:
e[2]['weight'] += noise
if not gm.check_if_stochastic_matrix(nx.to_numpy_matrix(G)):
nx.stochastic_graph(G, copy=False)
print salsa.eig_calc(G)'''
return
示例6: test_is_aperiodic_bipartite
def test_is_aperiodic_bipartite():
# Bipartite graph
G = nx.DiGraph(nx.davis_southern_women_graph())
assert_false(nx.is_aperiodic(G))
示例7: test_is_aperiodic_selfloop
def test_is_aperiodic_selfloop():
G = nx.DiGraph()
nx.add_cycle(G, [1, 2, 3, 4])
G.add_edge(1, 1)
assert_true(nx.is_aperiodic(G))
示例8: test_is_aperiodic_cycle3
def test_is_aperiodic_cycle3():
G = nx.DiGraph()
nx.add_cycle(G, [1, 2, 3, 4])
nx.add_cycle(G, [3, 4, 5, 6])
assert_false(nx.is_aperiodic(G))
示例9: test_is_aperiodic_cycle2
def test_is_aperiodic_cycle2():
G = nx.DiGraph()
nx.add_cycle(G, [1, 2, 3, 4])
nx.add_cycle(G, [3, 4, 5, 6, 7])
assert_true(nx.is_aperiodic(G))
示例10: _transition_matrix
def _transition_matrix(G, nodelist=None, weight='weight',
walk_type=None, alpha=0.95):
"""Returns the transition matrix of G.
This is a row stochastic giving the transition probabilities while
performing a random walk on the graph. Depending on the value of walk_type,
P can be the transition matrix induced by a random walk, a lazy random walk,
or a random walk with teleportation (PageRank).
Parameters
----------
G : DiGraph
A NetworkX graph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist.
If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight')
The edge data key used to compute each value in the matrix.
If None, then each edge has weight 1.
walk_type : string or None, optional (default=None)
If None, `P` is selected depending on the properties of the
graph. Otherwise is one of 'random', 'lazy', or 'pagerank'
alpha : real
(1 - alpha) is the teleportation probability used with pagerank
Returns
-------
P : NumPy array
transition matrix of G.
Raises
------
NetworkXError
If walk_type not specified or alpha not in valid range
"""
import scipy as sp
from scipy.sparse import identity, spdiags
if walk_type is None:
if nx.is_strongly_connected(G):
if nx.is_aperiodic(G):
walk_type = "random"
else:
walk_type = "lazy"
else:
walk_type = "pagerank"
M = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight,
dtype=float)
n, m = M.shape
if walk_type in ["random", "lazy"]:
DI = spdiags(1.0 / sp.array(M.sum(axis=1).flat), [0], n, n)
if walk_type == "random":
P = DI * M
else:
I = identity(n)
P = (I + DI * M) / 2.0
elif walk_type == "pagerank":
if not (0 < alpha < 1):
raise nx.NetworkXError('alpha must be between 0 and 1')
# this is using a dense representation
M = M.todense()
# add constant to dangling nodes' row
dangling = sp.where(M.sum(axis=1) == 0)
for d in dangling[0]:
M[d] = 1.0 / n
# normalize
M = M / M.sum(axis=1)
P = alpha * M + (1 - alpha) / n
else:
raise nx.NetworkXError("walk_type must be random, lazy, or pagerank")
return P
示例11: directed_laplacian_matrix
def directed_laplacian_matrix(G, nodelist=None, weight='weight',
walk_type=None, alpha=0.95):
r"""Return the directed Laplacian matrix of G.
The graph directed Laplacian is the matrix
.. math::
L = I - (\Phi^{1/2} P \Phi^{-1/2} + \Phi^{-1/2} P^T \Phi^{1/2} ) / 2
where `I` is the identity matrix, `P` is the transition matrix of the
graph, and `\Phi` a matrix with the Perron vector of `P` in the diagonal and
zeros elsewhere.
Depending on the value of walk_type, `P` can be the transition matrix
induced by a random walk, a lazy random walk, or a random walk with
teleportation (PageRank).
Parameters
----------
G : DiGraph
A NetworkX graph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist.
If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight')
The edge data key used to compute each value in the matrix.
If None, then each edge has weight 1.
walk_type : string or None, optional (default=None)
If None, `P` is selected depending on the properties of the
graph. Otherwise is one of 'random', 'lazy', or 'pagerank'
alpha : real
(1 - alpha) is the teleportation probability used with pagerank
Returns
-------
L : NumPy array
Normalized Laplacian of G.
Raises
------
NetworkXError
If NumPy cannot be imported
NetworkXNotImplemnted
If G is not a DiGraph
Notes
-----
Only implemented for DiGraphs
See Also
--------
laplacian_matrix
References
----------
.. [1] Fan Chung (2005).
Laplacians and the Cheeger inequality for directed graphs.
Annals of Combinatorics, 9(1), 2005
"""
import scipy as sp
from scipy.sparse import identity, spdiags, linalg
if walk_type is None:
if nx.is_strongly_connected(G):
if nx.is_aperiodic(G):
walk_type = "random"
else:
walk_type = "lazy"
else:
walk_type = "pagerank"
M = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight,
dtype=float)
n, m = M.shape
if walk_type in ["random", "lazy"]:
DI = spdiags(1.0/sp.array(M.sum(axis=1).flat), [0], n, n)
if walk_type == "random":
P = DI * M
else:
I = identity(n)
P = (I + DI * M) / 2.0
elif walk_type == "pagerank":
if not (0 < alpha < 1):
raise nx.NetworkXError('alpha must be between 0 and 1')
# this is using a dense representation
M = M.todense()
# add constant to dangling nodes' row
dangling = sp.where(M.sum(axis=1) == 0)
for d in dangling[0]:
M[d] = 1.0 / n
# normalize
M = M / M.sum(axis=1)
P = alpha * M + (1 - alpha) / n
else:
#.........这里部分代码省略.........
示例12: salsa_numpy
def salsa_numpy(G,normalized=True):
"""Return HITS hubs and authorities values for nodes.
The HITS algorithm computes two numbers for a node.
Authorities estimates the node value based on the incoming links.
Hubs estimates the node value based on outgoing links.
Parameters
-----------
G : graph
A NetworkX graph
normalized : bool (default=True)
Normalize results by the sum of all of the values.
Returns
-------
(hubs,authorities) : two-tuple of dictionaries
Two dictionaries keyed by node containing the hub and authority
values.
Examples
--------
>>> G=nx.path_graph(4)
>>> h,a=nx.hits(G)
Notes
-----
The eigenvector calculation uses NumPy's interface to LAPACK.
The HITS algorithm was designed for directed graphs but this
algorithm does not check if the input graph is directed and will
execute on undirected graphs.
References
----------
.. [1] A. Langville and C. Meyer,
"A survey of eigenvector methods of web information retrieval."
http://citeseer.ist.psu.edu/713792.html
.. [2] Jon Kleinberg,
Authoritative sources in a hyperlinked environment
Journal of the ACM 46 (5): 604-32, 1999.
doi:10.1145/324133.324140.
http://www.cs.cornell.edu/home/kleinber/auth.pdf.
"""
print '\n\t~~~~~~ salsa_numpy (eigenvector calc) ~~~~~~\n'
try:
import numpy as np
import scipy as sp
except ImportError:
raise ImportError(\
"hits_numpy() requires NumPy: http://scipy.org/")
if len(G) == 0:
return {},{}
print '--- salsa_numpy: start time- ' + str(datetime.now())
startTime = datetime.now()
#np.set_printoptions(precision=3) # For printing numpy objects- prints 3 decimal after the point.
H_sparse = get_matrix(G,mat_type='hub',sparse=True)
print '--- salsa_numpy: get_matrix (hub) took: '+str(datetime.now()-startTime); tmpTime = datetime.now()
eps = gm.epsilon
# DEBUG:
new_G_h = nx.DiGraph(H_sparse)
print 'is new graph strongly connected? ' + str(nx.is_strongly_connected(new_G_h))
print 'is new graph aperiodic? ' + str(nx.is_aperiodic(new_G_h))
#H = gm.convert_all_matrix_zeros_to_val(H_sparse, val=eps, stochastic_out=True)
#print '--- salsa_numpy: convert_all_matrix_zeros_to_eps took: '+str(datetime.now()-tmpTime); tmpTime = datetime.now()
H = H_sparse.todense()
#e,ev=np.linalg.eig(H)
e,ev=sp.linalg.eig(H,left=True,right=False)
#e,ev=np.linalg.eig(H.T) #we send H.T for calculating the LEFT eigenvector!
print '--- salsa_numpy: calculating hub eigs took: ' + str(datetime.now()-tmpTime)
#e,ev=sps.linalg.eigs(H,left=True,right=False)
m=e.argsort()[-1] # index of maximum eigenvalue
'''#DEBUG:
print('\nH:\n' + str(H.round(3)))
print'\ne rounded (3)\n' + str(e.round(3)) + '\nev rounded (3)\n' + str(ev.round(3))
print 'm- index of maximum eigenvalue= ' + str(m) + ', max eigenvalue= ' + str(e[m]) + \
'\nev rounded (3)\n' + str(np.array(ev[:,m]).flatten().round(3))'''
h=np.array(ev[:,m]).flatten()
# DEBUG:
print h
tmpTime = datetime.now()
A_sparse = get_matrix(G,mat_type='authority',sparse=True)
print '--- salsa_numpy: get_matrix (authority) took: '+str(datetime.now()-tmpTime); tmpTime = datetime.now()
new_G_a = nx.DiGraph(A_sparse)
print 'is new graph strongly connected? ' + str(nx.is_strongly_connected(new_G_a))
print 'is new graph aperiodic? ' + str(nx.is_aperiodic(new_G_a))
#A = gm.convert_all_matrix_zeros_to_val(A_sparse, val=eps, stochastic_out=True)
#print '--- salsa_numpy: convert_all_matrix_zeros_to_eps took: '+str(datetime.now()-tmpTime); tmpTime = datetime.now()
A = A_sparse.todense()
e,ev=sp.linalg.eig(A,left=True,right=False)
#e,ev=sps.linalg.eigs(A,left=True,right=False)
#e,ev=np.linalg.eig(A.T) #we send A.T for calculating the LEFT eigenvector!
print '--- salsa_numpy: calculating hub eigs took: ' + str(datetime.now()-tmpTime)
m=e.argsort()[-1] # index of maximum eigenvalue
a=np.array(ev[:,m]).flatten()
'''#DEBUG:
#.........这里部分代码省略.........
示例13: test_is_aperiodic_disconnected2
def test_is_aperiodic_disconnected2():
G = nx.DiGraph()
nx.add_cycle(G, [0, 1, 2])
G.add_edge(3, 3)
assert_false(nx.is_aperiodic(G))
示例14: measure
# components
nx.is_strongly_connected(G)
nx.number_strongly_connected_components(G)
scc = nx.strongly_connected_components(G)
nx.strongly_connected_components_recursive(G)
nx.condensation(G, scc)
# attracting components
nx.is_attracting_component(G)
nx.number_attracting_components(G)
nx.attracting_components(G)
# directed acyclic graphs
nx.is_directed_acyclic_graph(G)
nx.is_aperiodic(G)
# distance measure (all for connected graph)
nx.center(Gcc)
nx.diameter(Gcc)
nx.eccentricity(Gcc)
nx.periphery(Gcc)
nx.radius(Gcc)
# flows (seg fault currently)
#nx.max_flow(Gcc, 1, 2)
#nx.min_cut(G, 1, 2)
# isolates
nx.is_isolate(G, 1) # False
nx.is_isolate(G, 5) # True
示例15: salsa_scipy_old
def salsa_scipy_old(G,max_iter=100,tol=1.0e-6,nstart_dict=None,normalized=True, debug=False):
"""Return HITS hubs and authorities values for nodes.
The HITS algorithm computes two numbers for a node.
Authorities estimates the node value based on the incoming links.
Hubs estimates the node value based on outgoing links.
Parameters
-----------
G : graph
A NetworkX graph
max_iter : interger, optional
Maximum number of iterations in power method.
tol : float, optional
Error tolerance used to check convergence in power method iteration.
nstart : dictionary, optional
Starting value of each node for power method iteration.
normalized : bool (default=True)
Normalize results by the sum of all of the values.
Returns
-------
(hubs,authorities) : two-tuple of dictionaries
Two dictionaries keyed by node containing the hub and authority
values.
Examples
--------
>>> G=nx.path_graph(4)
>>> h,a=nx.hits(G)
Notes
-----
This implementation uses SciPy sparse matrices.
The eigenvector calculation is done by the power iteration method
and has no guarantee of convergence. The iteration will stop
after max_iter iterations or an error tolerance of
number_of_nodes(G)*tol has been reached.
The HITS algorithm was designed for directed graphs but this
algorithm does not check if the input graph is directed and will
execute on undirected graphs.
References
----------
.. [1] A. Langville and C. Meyer,
"A survey of eigenvector methods of web information retrieval."
http://citeseer.ist.psu.edu/713792.html
.. [2] Jon Kleinberg,
Authoritative sources in a hyperlinked environment
Journal of the ACM 46 (5): 604-632, 1999.
doi:10.1145/324133.324140.
http://www.cs.cornell.edu/home/kleinber/auth.pdf.
"""
#import sys
print '\n\t~~~~~~ salsa_scipy (G, max_iter='+str(max_iter)+', tol='+str(tol)+', nstart_dict, normalized='+str(normalized)+') ~~~~~~\n'; sys.stdout.flush()
try:
import scipy#.sparse as sp
import numpy as np
import sys
except ImportError:
raise ImportError(\
"hits_scipy() requires SciPy: http://scipy.org/")
if len(G) == 0:
return {},{}
print '--- salsa_scipy: ' + str(datetime.now()); sys.stdout.flush(); startTime = datetime.now()
''''M=nx.to_scipy_sparse_matrix(G,nodelist=G.nodes())
(n,m)=M.shape # should be square
A=M.T*M # authority matrix'''
A=get_matrix(G,mat_type='authority',sparse=True,force_ergodicity=True, CN_name=10)
(n,m)=A.shape # should be square
if debug:
new_G_h = nx.DiGraph(A)
print '\n--- salsa_scipy_old: hub- is new graph stochastic? ' + str(gm.check_if_stochastic_matrix(nx.to_numpy_matrix(new_G_h))); sys.stdout.flush()
print '--- salsa_scipy_old: hub- is new graph strongly connected? ' + str(nx.is_strongly_connected(new_G_h)); sys.stdout.flush()
print '--- salsa_scipy_old: hub- is new graph aperiodic? ' + str(nx.is_aperiodic(new_G_h)); sys.stdout.flush()
new_G_h.clear()
#print '--- salsa_scipy_old: debug steps (hub) took: '+str(datetime.now()-tmpTime); tmpTime = datetime.now(); sys.stdout.flush()
print '--- salsa_scipy: get authority matrix took: ' + str(datetime.now()-startTime); sys.stdout.flush(); tmpTime = datetime.now()
# choose fixed starting vector if not given
if nstart_dict is None:
a=scipy.ones((n,1))/n # initial guess
else:
a=np.asarray(nstart_dict.values()).flatten() # IN MY CASE: is it the init of hubs or authorities??
# normalize starting vector
s=1.0/a.sum()
for k in a:
a[k]*=s
# power iteration on authority matrix
i=0
a=a.T
#.........这里部分代码省略.........