Skip to content

Commit 3e1c220

Browse files
committed
Update src/graph.jl
1 parent b1c86db commit 3e1c220

1 file changed

Lines changed: 34 additions & 18 deletions

File tree

src/graph.jl

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -192,20 +192,44 @@ struct AdjacencyGraph{T,has_diagonal}
192192
M::SparseMatrixCSC{T,T}
193193
end
194194

195-
function AdjacencyGraph(
196-
S::SparsityPatternCSC{T}, M::SparseMatrixCSC{T,T}; has_diagonal::Bool=true
197-
) where {T}
195+
function AdjacencyGraph(S::SparsityPatternCSC{T}; has_diagonal::Bool=true) where {T}
196+
nv = size(S, 2)
197+
rows = rowvals(S)
198+
if has_diagonal
199+
ne = 0
200+
for j in 1:nv
201+
for pos in nzrange(S, j)
202+
i = rows[pos]
203+
if i < j
204+
ne += 1
205+
end
206+
end
207+
end
208+
else
209+
ne = nnz(S) ÷ 2
210+
end
211+
colptr = Vector{Int}(undef, nv + 1)
212+
rowval = Vector{Int}(undef, ne)
213+
colptr[1] = 1
214+
k = 1
215+
for j in 1:nv
216+
for pos in nzrange(S, j)
217+
i = rows[pos]
218+
if i < j
219+
rowval[k] = i
220+
k += 1
221+
end
222+
end
223+
colptr[j + 1] = k
224+
end
225+
nzval = collect(Base.OneTo(ne))
226+
M = SparseMatrixCSC(nv, nv, colptr, rowval, nzval)
198227
return AdjacencyGraph{T,has_diagonal}(S, M)
199228
end
200229

201230
function AdjacencyGraph(A::SparseMatrixCSC; has_diagonal::Bool=true)
202231
S = SparsityPatternCSC(A)
203-
M = triu(A, 1)
204-
nnzM = Int(nnz(M))
205-
nzval = collect(Base.OneTo(nnzM))
206-
m, n = size(A)
207-
M = SparseMatrixCSC(m, n, M.colptr, M.rowval, nzval)
208-
return AdjacencyGraph(S, M; has_diagonal)
232+
return AdjacencyGraph(S; has_diagonal)
209233
end
210234

211235
function AdjacencyGraph(A::AbstractMatrix; has_diagonal::Bool=true)
@@ -240,15 +264,7 @@ function degree(g::AdjacencyGraph, v::Integer)
240264
return d
241265
end
242266

243-
function nb_edges(g::AdjacencyGraph)
244-
ne = 0
245-
for v in vertices(g)
246-
for u in neighbors(g, v)
247-
ne += 1
248-
end
249-
end
250-
return ne ÷ 2
251-
end
267+
nb_edges(g::AdjacencyGraph) = nnz(g.M)
252268

253269
maximum_degree(g::AdjacencyGraph) = maximum(Base.Fix1(degree, g), vertices(g))
254270
minimum_degree(g::AdjacencyGraph) = minimum(Base.Fix1(degree, g), vertices(g))

0 commit comments

Comments
 (0)