library(knitr)
library(igraph)
##
## Attaching package: 'igraph'
##
## The following objects are masked from 'package:stats':
##
## decompose, spectrum
##
## The following object is masked from 'package:base':
##
## union
### Assume Matrix A as below
A <- matrix(c(1,0,1/6,0,0,0,
1/2,0,1/6,0,0,0,
1/2,1,0,0,0,1/2,
0,0,0,0,1/2,1/2,
0,0,1/6,1/2,0,1,
0,0,1/6,1/2,1/2,1),nrow=6, byrow = TRUE)
A
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 1.0 0 0.1666667 0.0 0.0 0.0
## [2,] 0.5 0 0.1666667 0.0 0.0 0.0
## [3,] 0.5 1 0.0000000 0.0 0.0 0.5
## [4,] 0.0 0 0.0000000 0.0 0.5 0.5
## [5,] 0.0 0 0.1666667 0.5 0.0 1.0
## [6,] 0.0 0 0.1666667 0.5 0.5 1.0
### Form the B Matrix - week 10 assignment
B <- 0.85*A +0.15/6
B
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 0.875 0.025 0.1666667 0.025 0.025 0.025
## [2,] 0.450 0.025 0.1666667 0.025 0.025 0.025
## [3,] 0.450 0.875 0.0250000 0.025 0.025 0.450
## [4,] 0.025 0.025 0.0250000 0.025 0.450 0.450
## [5,] 0.025 0.025 0.1666667 0.450 0.025 0.875
## [6,] 0.025 0.025 0.1666667 0.450 0.450 0.875
### Matrix Uniform Rank Vector r
r<- matrix(c(1/6,1/6,1/6,1/6,1/6,1/6),nrow=6)
r
## [,1]
## [1,] 0.1666667
## [2,] 0.1666667
## [3,] 0.1666667
## [4,] 0.1666667
## [5,] 0.1666667
## [6,] 0.1666667
converged <- FALSE
B_i <- diag(6)
n<- 10000
i <- 1
r_conv <- r
while(!converged & i<n) {
B_i <- B_i%*%B
r_conv <- B_i%*%r_conv
converged <- isTRUE(all.equal(r_conv, B_i%*%r_conv))
i <- i+1
}
### Solution for Convergence is below
i
## [1] 58
### and the rank for the decayed matrix A is:
r_conv
## [,1]
## [1,] Inf
## [2,] Inf
## [3,] Inf
## [4,] Inf
## [5,] Inf
## [6,] Inf
## Eigenvalue of B
evofB <- eigen(B)
evofB$values
## [1] 1.5559676 1.0006888 -0.4250000 -0.3420774 0.1727224 -0.1123014
### As you can see here, the Delta is 1 which is the largest value. The corresponding vector is below
r_ev <- evofB$vectors[,1]
r_ev
## [1] 0.1376227 0.1000322 0.3112928 0.3643322 0.5318700 0.6771460
grph <- random.graph.game(25, 5/25, directed=TRUE)
grph <- make_empty_graph(n = 6) %>%
add_edges(c(1,2,1,3,2,3,3,1,3,2,3,5,3,6,4,5,4,6,5,4,5,6,6,3,6,4))
plot(grph)

r_graph <- page.rank(grph)$vector
r_graph
## [1] 0.07735886 0.11023638 0.24639464 0.18635389 0.15655927 0.22309696
### Verify that you do get the same page rank vector in the two approaches
# Comparing the two approaches
all.equal(as.matrix(r_conv),as.matrix(r_graph))
## [1] "Mean absolute difference: Inf"
# Comparing the eigenvector solution vs graph pagerank
all.equal(as.matrix(r_ev),as.matrix(r_graph))
## [1] "Mean relative difference: 0.5384283"