Skip to content
This repository was archived by the owner on Oct 8, 2021. It is now read-only.

Commit e900189

Browse files
authored
Merge pull request #7 from JuliaGraphs/sbromberger/weighted-pagerank
weighted pagerank for SimpleWeightedDiGraph
2 parents b803681 + f0f9fdc commit e900189

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

src/SimpleWeightedGraphs.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ import LightGraphs:
1414

1515
add_vertices!, adjacency_matrix, weights,
1616

17-
AbstractGraphFormat, loadgraph, loadgraphs, savegraph
17+
AbstractGraphFormat, loadgraph, loadgraphs, savegraph,
18+
pagerank
1819

1920
export
2021
AbstractSimpleWeightedGraph,

src/overrides.jl

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,41 @@ function adjacency_matrix(g::AbstractSimpleWeightedGraph, T::DataType=Int; dir::
1818
end
1919
end
2020

21+
function pagerank(g::SimpleWeightedDiGraph, α=0.85, n=100::Integer, ϵ=1.0e-6)
22+
A = weights(g)
23+
S = vec(sum(A, 1))
24+
S = 1 ./ S
25+
S[find(S .== Inf)] = 0.0
26+
M = A' # need a separate line due to bug #17456 in julia
27+
# scaling the adjmat to stochastic adjacency matrix
28+
M = (Diagonal(S) * M)'
29+
N = Int(nv(g))
30+
# solution vector
31+
x = fill(1.0 / N, N)
32+
# personalization vector
33+
p = fill(1.0 / N, N)
34+
# temporary to hold the results of SpMV
35+
y = zeros(Float64, N)
36+
# adjustment for leaf nodes in digraph
37+
dangling_weights = p
38+
is_dangling = find(S .== 0)
39+
# save some flops by precomputing this
40+
pscaled = (1 .- α) .* p
41+
for _ in 1:n
42+
xlast = x
43+
# in place SpMV to conserve memory
44+
A_mul_B!(y, M, x)
45+
# using broadcast to avoid temporaries
46+
x = α .* (y .+ sum(x[is_dangling]) .* dangling_weights) .+ pscaled
47+
# l1 change in solution convergence criterion
48+
err = sum(abs, (x .- xlast))
49+
if (err < N * ϵ)
50+
return x
51+
end
52+
end
53+
error("Pagerank did not converge after $n iterations.")
54+
end
55+
2156
savegraph(fn::AbstractString, g::AbstractSimpleWeightedGraph, gname::AbstractString="graph"; compress=true) =
2257
savegraph(fn, g, gname, SWGFormat(), compress=compress)
2358

test/overrides.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@
1313
for g in testdigraphs(g5)
1414
@test @inferred(adjacency_matrix(g, Bool)) == adjacency_matrix(g, Bool; dir=:out)
1515
@test adjacency_matrix(g; dir=:out) == adjacency_matrix(g; dir=:in)'
16+
@test @inferred(pagerank(g))[3] 0.2266 atol=0.001
17+
@test length(@inferred(pagerank(g))) == nv(g)
18+
@test_throws ErrorException pagerank(g, 2)
19+
@test_throws ErrorException pagerank(g, 0.85, 2)
1620
end
1721
end
1822

0 commit comments

Comments
 (0)