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 erdos_renyi #212

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 22 additions & 7 deletions src/SimpleGraphs/generators/randgraphs.jl
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Random: randperm, shuffle!
using Random: randperm, shuffle!, randsubseq
using Statistics: mean
using Graphs: sample!

Expand Down Expand Up @@ -126,6 +126,18 @@ function randbn(
return x
end

"maps 1:binomial(n,2) into an upper triangle of [1,n]×[1,n]"
function trianglemap(r, n)
j, i = fldmod1(r, n - 1)
return i ≥ j ? Edge(i + 1, j) : Edge(n - i + 1, n - j + 1)
end

"maps 1:n*(n-1) into non-diagonal elements of [1,n]×[1,n]"
function nondiagmap(r, n)
i, j = fldmod1(r, n - 1)
return Edge(i + (i ≥ j), j)
end

"""
erdos_renyi(n, p)

Expand All @@ -149,7 +161,7 @@ julia> erdos_renyi(10, 0.5)
julia> using Graphs

julia> erdos_renyi(10, 0.5, is_directed=true, seed=123)
{10, 49} directed simple Int64 graph
{10, 41} directed simple Int64 graph
```
"""
function erdos_renyi(
Expand All @@ -160,13 +172,16 @@ function erdos_renyi(
seed::Union{Nothing,Integer}=nothing,
)
p >= 1 && return is_directed ? complete_digraph(n) : complete_graph(n)
m = is_directed ? n * (n - 1) : div(n * (n - 1), 2)
ne = randbn(m, p; rng=rng, seed=seed)
return if is_directed
SimpleDiGraph(n, ne; rng=rng, seed=seed)
m = is_directed ? n * (n - 1) : binomial(n, 2)
seq = randsubseq(rng_from_rng_or_seed(rng, seed), 1:m, p)
g = if is_directed
SimpleDiGraphFromIterator(nondiagmap(r, n) for r in seq)
else
SimpleGraph(n, ne; rng=rng, seed=seed)
SimpleGraphFromIterator(trianglemap(r, n) for r in seq)
end
# complete to exactly n vertices
add_vertices!(g, n - nv(g))
return g
end

"""
Expand Down