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

Commit

Permalink
fixed adjacency matrix (#745)
Browse files Browse the repository at this point in the history
  • Loading branch information
sbromberger authored Sep 8, 2017
1 parent c7a8fd1 commit 640e2de
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 8 deletions.
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,4 @@ function inner!(storage::AbstractVector{Int}, g::AbstractGraph, v::Integer)
end
```
This allows us to reuse the memory and improve performance.

13 changes: 7 additions & 6 deletions src/linalg/spectral.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ function adjacency_matrix(g::AbstractGraph, T::DataType=Int; dir::Symbol=:out)
# see below - we iterate over columns. That's why we take the
# "opposite" neighbor function. It's faster than taking the transpose
# at the end.

if (dir == :out)
_adjacency_matrix(g, T, in_neighbors, 1)
elseif (dir == :in)
Expand All @@ -38,10 +37,11 @@ end
function _adjacency_matrix(g::AbstractGraph, T::DataType, neighborfn::Function, nzmult::Int=1)
n_v = nv(g)
nz = ne(g) * (is_directed(g) ? 1 : 2) * nzmult
colpt = ones(Int, n_v + 1)

rowval = sizehint!(Vector{Int}(), nz)
selfloops = Vector{Int}()
U = eltype(g)
colpt = ones(U, n_v + 1)

rowval = sizehint!(Vector{U}(), nz)
selfloops = Vector{U}()
for j in 1:n_v # this is by column, not by row.
if has_edge(g, j, j)
push!(selfloops, j)
Expand Down Expand Up @@ -77,11 +77,12 @@ For undirected graphs, `dir` defaults to `:out`; for directed graphs,
`dir` defaults to `:both`.
"""
function laplacian_matrix(g::AbstractGraph, T::DataType=Int; dir::Symbol=:unspec)
U = eltype(g)
if dir == :unspec
dir = is_directed(g) ? :both : :out
end
A = adjacency_matrix(g, T; dir=dir)
D = spdiagm(sum(A, 2)[:])
D = convert(SparseMatrixCSC{T, U}, spdiagm(sum(A, 2)[:]))
return D - A
end

Expand Down
5 changes: 3 additions & 2 deletions test/linalg/spectral.jl
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,11 @@ full(nbt::Nonbacktracking) = full(sparse(nbt))

#check properties of the undirected laplacian carry over.
for dir in [:in, :out, :both]
T = eltype(g)
amat = adjacency_matrix(g, Float64; dir=dir)
lmat = laplacian_matrix(g, Float64; dir=dir)
@test isa(amat, SparseMatrixCSC{Float64,Int64})
@test isa(lmat, SparseMatrixCSC{Float64,Int64})
@test isa(amat, SparseMatrixCSC{Float64,T})
@test isa(lmat, SparseMatrixCSC{Float64,T})
evals = eigvals(full(lmat))
@test all(evals .>= -1e-15) # positive semidefinite
@test (minimum(evals)) 0 atol = 1e-13
Expand Down

0 comments on commit 640e2de

Please sign in to comment.