49. Node Statistics on Graph#

import numpy as np

50. Centrality#

node_ct = 5
adj_mat_rnd = np.random.randint(2, size=(node_ct, node_ct))
np.fill_diagonal(adj_mat_rnd, 0)
adj_mat_rnd = np.floor((adj_mat_rnd + adj_mat_rnd.T)/2)
adj_mat_rnd
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1.],
       [0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0.]])
adj_mat = adj_mat_rnd
np.linalg.eig(adj_mat)
(array([ 1., -1.,  0.,  0.,  0.]),
 array([[ 0.        ,  0.        ,  1.        ,  0.        ,  0.        ],
        [ 0.70710678,  0.70710678,  0.        ,  0.        ,  0.        ],
        [ 0.        ,  0.        ,  0.        ,  1.        ,  0.        ],
        [ 0.        ,  0.        ,  0.        ,  0.        ,  1.        ],
        [ 0.70710678, -0.70710678,  0.        ,  0.        ,  0.        ]]))
e_init = np.ones(node_ct)
e_init
array([1., 1., 1., 1., 1.])
np.matmul(adj_mat, e_init)
array([0., 1., 0., 0., 1.])
e_i = e_init.copy()

for i in range(5):
    e_i = np.matmul(adj_mat, e_i)
    # e_i = e_i/np.linalg.norm(e_i)
    print(e_i.shape)
    print(f"{i}: {e_i}")
(5,)
0: [0. 1. 0. 0. 1.]
(5,)
1: [0. 1. 0. 0. 1.]
(5,)
2: [0. 1. 0. 0. 1.]
(5,)
3: [0. 1. 0. 0. 1.]
(5,)
4: [0. 1. 0. 0. 1.]
def power_iteration(A, num_simulations: int):
    # Ideally choose a random vector
    # To decrease the chance that our vector
    # Is orthogonal to the eigenvector
    b_k = np.random.rand(A.shape[1])

    for _ in range(num_simulations):
        # calculate the matrix-by-vector product Ab
        b_k1 = np.dot(A, b_k)

        # calculate the norm
        b_k1_norm = np.linalg.norm(b_k1)

        # re normalize the vector
        b_k = b_k1 / b_k1_norm

    return b_k
power_iteration(np.array([[0.5, 0.5], [0.2, 0.8]]), 100)
array([0.70710678, 0.70710678])
power_iteration(adj_mat, 500)
array([0.        , 0.87286678, 0.        , 0.        , 0.48795858])
adj_florentine = np.array(
    [
        []
    ]
)
Created in deepnote.com Created in Deepnote