Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faster all_neighbors for SimpleDiGraphs #82

Merged
merged 1 commit into from
Jan 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/SimpleGraphs/SimpleGraphs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ import Base:
import Graphs:
_NI, AbstractGraph, AbstractEdge, AbstractEdgeIter,
src, dst, edgetype, nv, ne, vertices, edges, is_directed,
has_vertex, has_edge, inneighbors, outneighbors, deepcopy_adjlist,
indegree, outdegree, degree, has_self_loops, num_self_loops, insorted
has_vertex, has_edge, inneighbors, outneighbors, all_neighbors,
deepcopy_adjlist, indegree, outdegree, degree, has_self_loops,
num_self_loops, insorted

using Random: GLOBAL_RNG, AbstractRNG

Expand Down
34 changes: 34 additions & 0 deletions src/SimpleGraphs/simpledigraph.jl
Original file line number Diff line number Diff line change
Expand Up @@ -566,3 +566,37 @@ function rem_vertices!(g::SimpleDiGraph{T},

return reverse_vmap
end

function all_neighbors(g::SimpleDiGraph{T}, u::Integer) where T
i, j = 1, 1
in_nbrs, out_nbrs = inneighbors(g, u), outneighbors(g, u)
in_len, out_len = length(in_nbrs), length(out_nbrs)
union_nbrs = Vector{T}(undef, in_len + out_len)
indx = 1
@inbounds while i <= in_len && j <= out_len
if in_nbrs[i] < out_nbrs[j]
union_nbrs[indx] = in_nbrs[i]
i += 1
elseif in_nbrs[i] > out_nbrs[j]
union_nbrs[indx] = out_nbrs[j]
j += 1
else
union_nbrs[indx] = out_nbrs[j]
i += 1
j += 1
end
indx += 1
end
@inbounds while i <= in_len
union_nbrs[indx] = in_nbrs[i]
i += 1
indx += 1
end
@inbounds while j <= out_len
union_nbrs[indx] = out_nbrs[j]
j += 1
indx += 1
end
resize!(union_nbrs, indx-1)
return union_nbrs
end
1 change: 1 addition & 0 deletions test/simplegraphs/simplegraphs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ import Random

@test @inferred(inneighbors(g, 2)) == [1]
@test @inferred(outneighbors(g, 2)) == @inferred(neighbors(g, 2)) == [3]
@test @inferred Set(all_neighbors(g, 2)) == Set(union(inneighbors(g, 2), outneighbors(g, 2)))
@test @inferred(add_vertex!(gc)) # out of order, but we want it for issubset
@test @inferred(g ⊆ gc)
@test @inferred(has_vertex(gc, 5))
Expand Down