<s> from scipy . sparse import csr_matrix <EOL> from scipy . linalg import eig <EOL> from numpy import empty as empty_matrix <EOL> try : <EOL> from numpy import VisibleDeprecationWarning <EOL> import warnings <EOL> warnings . filterwarnings ( "<STR_LIT:ignore>" , category = VisibleDeprecationWarning ) <EOL> except ImportError : <EOL> pass <EOL> CONVERGENCE_THRESHOLD = <NUM_LIT> <EOL> def pagerank_weighted ( graph , initial_value = None , damping = <NUM_LIT> ) : <EOL> """<STR_LIT>""" <EOL> if initial_value == None : initial_value = <NUM_LIT:1.0> / len ( graph . nodes ( ) ) <EOL> scores = dict . fromkeys ( graph . nodes ( ) , initial_value ) <EOL> iteration_quantity = <NUM_LIT:0> <EOL> for iteration_number in xrange ( <NUM_LIT:100> ) : <EOL> iteration_quantity += <NUM_LIT:1> <EOL> convergence_achieved = <NUM_LIT:0> <EOL> for i in graph . nodes ( ) : <EOL> rank = <NUM_LIT:1> - damping <EOL> for j in graph . neighbors ( i ) : <EOL> neighbors_sum = sum ( graph . edge_weight ( ( j , k ) ) for k in graph . neighbors ( j ) ) <EOL> rank += damping * scores [ j ] * graph . edge_weight ( ( j , i ) ) / neighbors_sum <EOL> if abs ( scores [ i ] - rank ) <= CONVERGENCE_THRESHOLD : <EOL> convergence_achieved += <NUM_LIT:1> <EOL> scores [ i ] = rank <EOL> if convergence_achieved == len ( graph . nodes ( ) ) : <EOL> break <EOL> return scores <EOL> def pagerank_weighted_scipy ( graph , damping = <NUM_LIT> ) : <EOL> adjacency_matrix = build_adjacency_matrix ( graph ) <EOL> probability_matrix = build_probability_matrix ( graph ) <EOL> pagerank_matrix = damping * adjacency_matrix . todense ( ) + ( <NUM_LIT:1> - damping ) * probability_matrix <EOL> vals , vecs = eig ( pagerank_matrix , left = True , right = False ) <EOL> return process_results ( graph , vecs ) <EOL> def build_adjacency_matrix ( graph ) : <EOL> row = [ ] <EOL> col = [ ] <EOL> data = [ ] <EOL> nodes = graph . nodes ( ) <EOL> length = len ( nodes ) <EOL> for i in xrange ( length ) : <EOL> current_node = nodes [ i ] <EOL> neighbors_sum = sum ( graph . edge_weight ( ( current_node , neighbor ) ) for neighbor in graph . neighbors ( current_node ) ) <EOL> for j in xrange ( length ) : <EOL> edge_weight = float ( graph . edge_weight ( ( current_node , nodes [ j ] ) ) ) <EOL> if i != j and edge_weight != <NUM_LIT:0> : <EOL> row . append ( i ) <EOL> col . append ( j ) <EOL> data . append ( edge_weight / neighbors_sum ) <EOL> return csr_matrix ( ( data , ( row , col ) ) , shape = ( length , length ) ) <EOL> def build_probability_matrix ( graph ) : <EOL> dimension = len ( graph . nodes ( ) ) <EOL> matrix = empty_matrix ( ( dimension , dimension ) ) <EOL> probability = <NUM_LIT:1> / float ( dimension ) <EOL> matrix . fill ( probability ) <EOL> return matrix <EOL> def process_results ( graph , vecs ) : <EOL> scores = { } <EOL> for i , node in enumerate ( graph . nodes ( ) ) : <EOL> scores [ node ] = abs ( vecs [ i ] [ <NUM_LIT:0> ] ) <EOL> return scores </s>
