def surf_rank ( A, it_num ): #*****************************************************************************80 # ## surf_rank() uses the "random surfer" method for node rankings of a digraph. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 07 August 2022 # # Author: # # John Burkardt # # Input: # # integer A(N,N): the adjacency matrix. # # integer it_num: the number of iterations to take. # from numpy.random import default_rng import numpy as np rng = default_rng ( ) print ( '' ) print ( 'surf_rank():' ) print ( ' Given an NxN adjacency matrix A,' ) print ( ' compute the transition matrix T,' ) print ( ' and then repeatedly visit nodes, keeping track of' ) print ( ' how often you visited.' ) print ( '' ) print ( ' 15 per cent of the time, simply take a random jump to a node.' ) print ( ' The rest of the time, follow a random link from the current node.' ) print ( '' ) print ( ' When done, the node weight is the number of visits' ) print ( ' normalized by the total number of visits.' ) n = A.shape[0] v = np.zeros ( n ) # # Get the transition matrix from the adjacency matrix. # T = adjacency_to_transition ( A ) # # Carry out many moves. # for k in range ( 0, it_num ): if ( k == 0 ): j = rng.integers ( low = 0, high = n, size = 1, endpoint = False ) else: p1 = rng.random ( ) q1 = 0.15 if ( p1 <= q1 ): j = rng.integers ( low = 0, high = n, size = 1, endpoint = False ) else: p2 = rng.random ( ) q2 = 0.0 for i in range ( 0, n ): q2 = q2 + T[i,j] if ( p2 <= q2 ): j = i break v[j] = v[j] + 1 # # Normalize the counts. # index = list ( range ( 0, n ) ) weight = v / it_num Output = np.column_stack ( [ index, v, weight ] ) print ( '' ) print ( ' index, count, weight' ) print ( Output ) return def adjacency_to_transition ( A ): #*****************************************************************************80 # ## adjacency_to_transition() converts an adjacency matrix to a transition matrix. # # Licensing: # # This code is distributed under the MIT license. # # Modified: # # 07 August 2022 # # Author: # # John Burkardt # # Input: # # integer A(N,N), the adjacency matrix. # # Output: # # real T(N,N): the transition matrix. # import numpy as np n = A.shape[0] # # Get the row sums. # s = np.sum ( A, axis = 1 ) # # Normalize each row so it sums to 1. # T = np.zeros ( [ n, n ] ) for i in range ( 0, n ): if ( s[i] != 0.0 ): T[i,:] = A[i,:] / s[i] else: T[i,i] = 1.0 # # Transpose the matrix. # T = np.transpose ( T ) return T