From 66424818eb7c0e9d959fe45a5fdeac1bd45ed534 Mon Sep 17 00:00:00 2001 From: Seth Bromberger Date: Wed, 12 Jul 2017 15:34:02 -0700 Subject: [PATCH] fix whitespace issues throughout codebase (#687) --- benchmark/benchmarks.jl | 6 +- benchmark/edges.jl | 8 +- benchmark/insertions.jl | 2 +- benchmark/max-flow.jl | 4 +- benchmark/parallel/egonets.jl | 4 +- src/LightGraphs.jl | 3 - src/biconnectivity/biconnect.jl | 2 +- src/centrality/betweenness.jl | 2 +- src/centrality/closeness.jl | 12 +- src/centrality/degree.jl | 6 +- src/centrality/katz.jl | 2 +- src/centrality/pagerank.jl | 14 +- src/community/cliques.jl | 2 +- src/community/clustering.jl | 6 +- src/community/core-periphery.jl | 4 +- src/community/label_propagation.jl | 18 +- src/community/modularity.jl | 14 +- src/connectivity.jl | 34 ++-- src/core.jl | 30 ++-- src/degeneracy.jl | 16 +- src/digraph/cycles/hadwick-james.jl | 2 +- src/digraph/cycles/johnson.jl | 27 ++- src/digraph/transitivity.jl | 2 +- src/distance.jl | 10 +- src/edit_distance.jl | 30 ++-- src/flow/boykov_kolmogorov.jl | 32 ++-- src/flow/dinic.jl | 8 +- src/flow/edmonds_karp.jl | 26 +-- src/flow/ext_multiroute_flow.jl | 8 +- src/flow/maximum_flow.jl | 2 +- src/flow/multiroute_flow.jl | 6 +- src/flow/push_relabel.jl | 30 ++-- src/generators/euclideangraphs.jl | 14 +- src/generators/randgraphs.jl | 143 ++++++++-------- src/generators/smallgraphs.jl | 128 +++++++------- src/generators/staticgraphs.jl | 62 +++---- src/graphtypes/simplegraphs/SimpleGraphs.jl | 4 +- src/graphtypes/simplegraphs/simpledigraph.jl | 24 +-- src/graphtypes/simplegraphs/simpleedge.jl | 4 +- src/graphtypes/simplegraphs/simpleedgeiter.jl | 4 +- src/graphtypes/simplegraphs/simplegraph.jl | 14 +- src/interface.jl | 2 +- src/linalg/graphmatrices.jl | 102 +++++------ src/linalg/nonbacktracking.jl | 38 ++--- src/linalg/spectral.jl | 26 +-- src/operators.jl | 48 +++--- src/persistence/common.jl | 6 +- src/persistence/lg.jl | 10 +- src/shortestpaths/astar.jl | 4 +- src/shortestpaths/bellman-ford.jl | 8 +- src/shortestpaths/dijkstra.jl | 40 ++--- src/shortestpaths/floyd-warshall.jl | 42 ++--- src/shortestpaths/yen.jl | 24 +-- src/traversals/bfs.jl | 17 +- src/traversals/dfs.jl | 6 +- src/traversals/graphvisit.jl | 2 +- src/traversals/maxadjvisit.jl | 40 ++--- src/traversals/parallel_bfs.jl | 28 +-- src/traversals/randomwalks.jl | 24 +-- src/utils.jl | 4 +- test/biconnectivity/articulation.jl | 2 +- test/biconnectivity/biconnect.jl | 2 +- test/centrality/betweenness.jl | 32 ++-- test/centrality/closeness.jl | 40 ++--- test/centrality/degree.jl | 2 +- test/centrality/eigenvector.jl | 3 +- test/centrality/katz.jl | 2 +- test/centrality/pagerank.jl | 4 +- test/community/cliques.jl | 20 +-- test/community/core-periphery.jl | 8 +- test/community/label_propagation.jl | 10 +- test/community/modularity.jl | 2 +- test/connectivity.jl | 161 +++++++++--------- test/core.jl | 100 +++++------ test/degeneracy.jl | 2 +- test/digraph/cycles/hadwick-james.jl | 4 +- test/digraph/cycles/johnson.jl | 8 +- test/distance.jl | 4 +- test/edit_distance.jl | 34 ++-- test/flow/boykov_kolmogorov.jl | 8 +- test/flow/dinic.jl | 22 +-- test/flow/edmonds_karp.jl | 88 +++++----- test/flow/maximum_flow.jl | 42 ++--- test/flow/push_relabel.jl | 30 ++-- test/generators/binomial.jl | 6 +- test/generators/euclideangraphs.jl | 12 +- test/generators/staticgraphs.jl | 60 +++---- test/graphtypes/simplegraphs/simpleedge.jl | 6 +- .../graphtypes/simplegraphs/simpleedgeiter.jl | 16 +- test/graphtypes/simplegraphs/simplegraphs.jl | 32 ++-- test/interface.jl | 24 +-- test/linalg/graphmatrices.jl | 56 +++--- test/linalg/spectral.jl | 90 +++++----- test/operators.jl | 34 ++-- test/persistence/persistence.jl | 6 +- test/runtests.jl | 2 +- test/shortestpaths/astar.jl | 4 +- test/shortestpaths/bellman-ford.jl | 8 +- test/shortestpaths/dijkstra.jl | 122 ++++++------- test/shortestpaths/floyd-warshall.jl | 16 +- test/shortestpaths/yen.jl | 112 ++++++------ test/spanningtrees/kruskal.jl | 40 ++--- test/spanningtrees/prim.jl | 30 ++-- test/traversals/bfs.jl | 22 +-- test/traversals/dfs.jl | 4 +- test/traversals/graphvisit.jl | 2 +- test/traversals/maxadjvisit.jl | 4 +- test/traversals/parallel_bfs.jl | 12 +- test/traversals/randomwalks.jl | 18 +- test/utils.jl | 6 +- 110 files changed, 1300 insertions(+), 1314 deletions(-) diff --git a/benchmark/benchmarks.jl b/benchmark/benchmarks.jl index c9d96fd1b..2d183dfc1 100644 --- a/benchmark/benchmarks.jl +++ b/benchmark/benchmarks.jl @@ -2,7 +2,7 @@ using PkgBenchmark using LightGraphs -testdatadir = joinpath(dirname(@__FILE__), "..","test","testdata") +testdatadir = joinpath(dirname(@__FILE__), "..", "test", "testdata") benchdatadir = joinpath(dirname(@__FILE__), "data") paramsfile = joinpath(benchdatadir, "params.jld") @@ -11,13 +11,13 @@ println("paramsfile = $paramsfile") dg1fn = joinpath(testdatadir, "graph-5k-50k.jgz") -DIGRAPHS = Dict{String, DiGraph}( +DIGRAPHS = Dict{String,DiGraph}( "complete100" => CompleteDiGraph(100), "5000-50000" => LightGraphs.load(dg1fn)["graph-5000-50000"], "path500" => PathDiGraph(500) ) -GRAPHS = Dict{String, Graph}( +GRAPHS = Dict{String,Graph}( "complete100" => CompleteGraph(100), "tutte" => smallgraph(:tutte), "path500" => PathGraph(500), diff --git a/benchmark/edges.jl b/benchmark/edges.jl index 491170bc0..066ea8ecd 100644 --- a/benchmark/edges.jl +++ b/benchmark/edges.jl @@ -1,13 +1,13 @@ import Base: convert -const P = Pair{Int, Int} +const P = Pair{Int,Int} convert(::Type{Tuple}, e::Pair) = (e.first, e.second) function fille(n) t = Array{LightGraphs.Edge,1}(n) for i in 1:n - t[i] = LightGraphs.Edge(i, i+1) + t[i] = LightGraphs.Edge(i, i + 1) end return t end @@ -15,7 +15,7 @@ end function fillp(n) t = Array{P,1}(n) for i in 1:n - t[i] = P(i, i+1) + t[i] = P(i, i + 1) end return t end @@ -23,7 +23,7 @@ end function tsum(t) x = 0 for i in 1:length(t) - u,v = Tuple(t[i]) + u, v = Tuple(t[i]) x += u x += v end diff --git a/benchmark/insertions.jl b/benchmark/insertions.jl index 9e3dcaf8b..10a767495 100644 --- a/benchmark/insertions.jl +++ b/benchmark/insertions.jl @@ -1,4 +1,4 @@ @benchgroup "insertions" begin n = 10000 - @bench "ER Generation" g = Graph($n, 16*$n) + @bench "ER Generation" g = Graph($n, 16 * $n) end diff --git a/benchmark/max-flow.jl b/benchmark/max-flow.jl index 46a0f10cd..15e66d792 100644 --- a/benchmark/max-flow.jl +++ b/benchmark/max-flow.jl @@ -2,9 +2,9 @@ for n in 9:5:29 srand(1) p = 8.0 / n - A = sprand(n,n,p) + A = sprand(n, n, p) g = DiGraph(A) - cap = round.(A*100) + cap = round.(A * 100) @bench "n = $n" LightGraphs.maximum_flow($g, 1, $n, $cap) end end # max-flow diff --git a/benchmark/parallel/egonets.jl b/benchmark/parallel/egonets.jl index bb9e3c1ad..d06cbc05f 100644 --- a/benchmark/parallel/egonets.jl +++ b/benchmark/parallel/egonets.jl @@ -16,7 +16,7 @@ using BenchmarkTools a = 0 for u in neighbors(g, i) for v in neighbors(g, u) - a += degree(g,v) + a += degree(g, v) end end return a @@ -53,7 +53,7 @@ using BenchmarkTools end nv_ = 10000 - g = Graph(nv_, 64*nv_) + g = Graph(nv_, 64 * nv_) f = vertex_function println(g) diff --git a/src/LightGraphs.jl b/src/LightGraphs.jl index 7ca43fac5..8483afa5b 100644 --- a/src/LightGraphs.jl +++ b/src/LightGraphs.jl @@ -86,9 +86,6 @@ CombinatorialAdjacency, non_backtracking_matrix, incidence_matrix, nonbacktrack_embedding, Nonbacktracking, contract, -# astar -a_star, - # persistence loadgraph, loadgraphs, savegraph, LGFormat, diff --git a/src/biconnectivity/biconnect.jl b/src/biconnectivity/biconnect.jl index d7c1ec037..264749327 100644 --- a/src/biconnectivity/biconnect.jl +++ b/src/biconnectivity/biconnect.jl @@ -39,7 +39,7 @@ function visit!(g::AbstractGraph, state::Biconnections, u::Integer, v::Integer) if (u == v && children > 1) || (u != v && state.low[w] >= state.depth[v]) e = Edge(0, 0) #Invalid Edge, used for comparison only st = Vector{Edge}() - while e != Edge(min(v, w),max(v, w)) + while e != Edge(min(v, w), max(v, w)) e = pop!(state.stack) push!(st, e) end diff --git a/src/centrality/betweenness.jl b/src/centrality/betweenness.jl index e18efd88f..a1e75932a 100644 --- a/src/centrality/betweenness.jl +++ b/src/centrality/betweenness.jl @@ -36,7 +36,7 @@ function betweenness_centrality( betweenness = zeros(n_v) for s in vs - if degree(g,s) > 0 # this might be 1? + if degree(g, s) > 0 # this might be 1? state = dijkstra_shortest_paths(g, s; allpaths=true, trackvertices=true) if endpoints _accumulate_endpoints!(betweenness, state, g, s) diff --git a/src/centrality/closeness.jl b/src/centrality/closeness.jl index f94b0c3d2..31e223240 100644 --- a/src/centrality/closeness.jl +++ b/src/centrality/closeness.jl @@ -21,14 +21,14 @@ function closeness_centrality( if degree(g, u) == 0 # no need to do Dijkstra here closeness[u] = 0.0 else - d = dijkstra_shortest_paths(g,u,distmx).dists - δ = filter(x->x != typemax(x), d) + d = dijkstra_shortest_paths(g, u, distmx).dists + δ = filter(x -> x != typemax(x), d) σ = sum(δ) l = length(δ) - 1 if σ > 0 closeness[u] = l / σ if normalize - n = l / (n_v-1) + n = l / (n_v - 1) closeness[u] *= n end end @@ -50,14 +50,14 @@ function parallel_closeness_centrality( if degree(g, u) == 0 # no need to do Dijkstra here closeness[u] = 0.0 else - d = dijkstra_shortest_paths(g,u,distmx).dists - δ = filter(x->x != typemax(x), d) + d = dijkstra_shortest_paths(g, u, distmx).dists + δ = filter(x -> x != typemax(x), d) σ = sum(δ) l = length(δ) - 1 if σ > 0 closeness[u] = l / σ if normalize - n = l * 1.0 / (n_v-1) + n = l * 1.0 / (n_v - 1) closeness[u] *= n end end diff --git a/src/centrality/degree.jl b/src/centrality/degree.jl index befbed414..ee664126f 100644 --- a/src/centrality/degree.jl +++ b/src/centrality/degree.jl @@ -3,14 +3,14 @@ function _degree_centrality(g::AbstractGraph, gtype::Integer; normalize=true) c = zeros(n_v) for v in vertices(g) if gtype == 0 # count both in and out degree if appropriate - deg = is_directed(g)? outdegree(g, v) + indegree(g, v) : outdegree(g, v) + deg = is_directed(g) ? outdegree(g, v) + indegree(g, v) : outdegree(g, v) elseif gtype == 1 # count only in degree deg = indegree(g, v) else # count only out degree deg = outdegree(g, v) end - s = normalize? (1.0 / (n_v - 1.0)) : 1.0 - c[v] = deg*s + s = normalize ? (1.0 / (n_v - 1.0)) : 1.0 + c[v] = deg * s end return c end diff --git a/src/centrality/katz.jl b/src/centrality/katz.jl index 720226df0..8ea1b3767 100644 --- a/src/centrality/katz.jl +++ b/src/centrality/katz.jl @@ -32,7 +32,7 @@ function katz_centrality(g::AbstractGraph, α::Real=0.3) v = ones(Float64, nvg) spI = speye(Float64, nvg) A = adjacency_matrix(g, :in, Bool) - v = (spI - α*A)\v + v = (spI - α * A) \ v v /= norm(v) return v end diff --git a/src/centrality/pagerank.jl b/src/centrality/pagerank.jl index 3464b974d..f10c8e904 100644 --- a/src/centrality/pagerank.jl +++ b/src/centrality/pagerank.jl @@ -13,18 +13,18 @@ is not reached within `n` iterations. function pagerank end @traitfn function pagerank(g::::IsDirected, α=0.85, n=100::Integer, ϵ=1.0e-6) - A = adjacency_matrix(g,:in,Float64) - S = vec(sum(A,1)) - S = 1./S - S[find(S .== Inf)]=0.0 - M = A' # need a separate line due to bug #17456 in julia + A = adjacency_matrix(g, :in, Float64) + S = vec(sum(A, 1)) + S = 1 ./ S + S[find(S .== Inf)] = 0.0 + M = A' # need a separate line due to bug #17456 in julia # scaling the adjmat to stochastic adjacency matrix M = (Diagonal(S) * M)' N = Int(nv(g)) # solution vector - x = fill(1.0/N, N) + x = fill(1.0 / N, N) # personalization vector - p = fill(1.0/N, N) + p = fill(1.0 / N, N) # temporary to hold the results of SpMV y = zeros(Float64, N) # adjustment for leaf nodes in digraph diff --git a/src/community/cliques.jl b/src/community/cliques.jl index 30a72f16f..48326a4e4 100644 --- a/src/community/cliques.jl +++ b/src/community/cliques.jl @@ -53,7 +53,7 @@ function maximal_cliques end # union!(cand, keys(nnbrs)) smallcand = setdiff(cand, pivotnbrs) done = Set{T}() - stack = Vector{Tuple{Set{T}, Set{T}, Set{T}}}() + stack = Vector{Tuple{Set{T},Set{T},Set{T}}}() clique_so_far = Vector{T}() cliques = Vector{Array{T}}() diff --git a/src/community/clustering.jl b/src/community/clustering.jl index ca85accff..c4d77fe4f 100644 --- a/src/community/clustering.jl +++ b/src/community/clustering.jl @@ -13,7 +13,7 @@ end function local_clustering_coefficient(g::AbstractGraph, vs = vertices(g)) ntriang, nalltriang = local_clustering(g, vs) - return map(p->p[2]==0? 0. : p[1]*1.0/p[2], zip(ntriang, nalltriang)) + return map(p -> p[2] == 0 ? 0. : p[1] * 1.0 / p[2], zip(ntriang, nalltriang)) end function local_clustering!(storage::AbstractVector{Bool}, g::AbstractGraph, v::Integer) @@ -30,7 +30,7 @@ function local_clustering!(storage::AbstractVector{Bool}, g::AbstractGraph, v::I end end end - return is_directed(g) ? (tcount , k*(k-1)) : (div(tcount,2) , div(k*(k-1),2)) + return is_directed(g) ? (tcount, k * (k - 1)) : (div(tcount, 2), div(k * (k - 1), 2)) end function local_clustering!(storage::AbstractVector{Bool}, @@ -101,7 +101,7 @@ function global_clustering_coefficient(g::AbstractGraph) end end k = degree(g, v) - ntriangles += k*(k-1) + ntriangles += k * (k - 1) end ntriangles == 0 && return 1. return c / ntriangles diff --git a/src/community/core-periphery.jl b/src/community/core-periphery.jl index 7831a85ac..91ad51a4c 100644 --- a/src/community/core-periphery.jl +++ b/src/community/core-periphery.jl @@ -14,8 +14,8 @@ function core_periphery_deg end s = sum(degs) / 2. sbest = +Inf kbest = 0 - for k = 1:nv(g)-1 - s = s + k - 1 - degree(g, p[k]) + for k = 1:nv(g) - 1 + s = s + k - 1 - degree(g, p[k]) if s < sbest sbest = s kbest = k diff --git a/src/community/label_propagation.jl b/src/community/label_propagation.jl index ebcba9ae7..01a3c1e8c 100644 --- a/src/community/label_propagation.jl +++ b/src/community/label_propagation.jl @@ -14,7 +14,7 @@ function label_propagation(g::AbstractGraph, maxiter=1000) n = nv(g) label = collect(one(T):n) active_vs = IntSet(vertices(g)) - c = NeighComm(collect(one(T):n), fill(-1,n), one(T)) + c = NeighComm(collect(one(T):n), fill(-1, n), one(T)) convergence_hist = Vector{Int}() random_order = Vector{T}(n) i = 0 @@ -24,11 +24,11 @@ function label_propagation(g::AbstractGraph, maxiter=1000) i += 1 # processing vertices in random order - for (j,node) in enumerate(active_vs) + for (j, node) in enumerate(active_vs) random_order[j] = node end range_shuffle!(1:num_active, random_order) - @inbounds for j=1:num_active + @inbounds for j = 1:num_active u = random_order[j] old_comm = label[u] label[u] = vote!(g, label, c, u) @@ -64,11 +64,11 @@ Fast shuffle Array `a` in UnitRange `r`. """ function range_shuffle!(r::UnitRange, a::AbstractVector) (r.start > 0 && r.stop <= length(a)) || error("out of bounds") - @inbounds for i=length(r):-1:2 + @inbounds for i = length(r):-1:2 j = rand(1:i) ii = i + r.start - 1 jj = j + r.start - 1 - a[ii],a[jj] = a[jj],a[ii] + a[ii], a[jj] = a[jj], a[ii] end end @@ -78,7 +78,7 @@ end Return the label with greatest frequency. """ function vote!(g::AbstractGraph, m::Vector, c::NeighComm, u::Integer) - @inbounds for i=1:c.neigh_last-1 + @inbounds for i = 1:c.neigh_last - 1 c.neigh_cnt[c.neigh_pos[i]] = -1 end c.neigh_last = 1 @@ -86,7 +86,7 @@ function vote!(g::AbstractGraph, m::Vector, c::NeighComm, u::Integer) c.neigh_cnt[c.neigh_pos[1]] = 0 c.neigh_last = 2 max_cnt = 0 - for neigh in out_neighbors(g,u) + for neigh in out_neighbors(g, u) neigh_comm = m[neigh] if c.neigh_cnt[neigh_comm] < 0 c.neigh_cnt[neigh_comm] = 0 @@ -99,7 +99,7 @@ function vote!(g::AbstractGraph, m::Vector, c::NeighComm, u::Integer) end end # ties breaking randomly - range_shuffle!(1:c.neigh_last-1, c.neigh_pos) + range_shuffle!(1:c.neigh_last - 1, c.neigh_pos) for lbl in c.neigh_pos if c.neigh_cnt[lbl] == max_cnt return lbl @@ -111,7 +111,7 @@ function renumber_labels!(membership::Vector, label_counters::Vector{Int}) N = length(membership) (maximum(membership) > N || minimum(membership) < 1) && error("Label must between 1 and |V|") j = 1 - @inbounds for i=1:length(membership) + @inbounds for i = 1:length(membership) k = membership[i] if k >= 1 if label_counters[k] == 0 diff --git a/src/community/modularity.jl b/src/community/modularity.jl index b14d13046..0323b4984 100644 --- a/src/community/modularity.jl +++ b/src/community/modularity.jl @@ -6,13 +6,13 @@ Return a value representing Newman's modularity `Q` for the undirected graph """ function modularity end @traitfn function modularity(g::::(!IsDirected), c::Vector) - m = 2*ne(g) + m = 2 * ne(g) m == 0 && return 0. nc = maximum(c) - a = zeros(Int,nc) + a = zeros(Int, nc) Q = 0 for u in vertices(g) - for v in neighbors(g,u) + for v in neighbors(g, u) if u <= v c1 = c[u] c2 = c[v] @@ -24,9 +24,9 @@ function modularity end end end end - Q = Q*m - @inbounds for i=1:nc - Q -= a[i]*a[i] + Q = Q * m + @inbounds for i = 1:nc + Q -= a[i] * a[i] end - return Q/m/m + return Q / m / m end diff --git a/src/connectivity.jl b/src/connectivity.jl index 12fba3998..78af4fb6c 100644 --- a/src/connectivity.jl +++ b/src/connectivity.jl @@ -42,7 +42,7 @@ and each value containing the vertices associated with that component. """ function components_dict(labels::Vector{T}) where T<:Integer d = Dict{T,Vector{T}}() - for (v,l) in enumerate(labels) + for (v, l) in enumerate(labels) vec = get(d, l, Vector{T}()) push!(vec, v) d[l] = vec @@ -57,10 +57,10 @@ Given a vector of component labels, return a vector of vectors representing the with a given component id. """ function components(labels::Vector{T}) where T<:Integer - d = Dict{T, T}() + d = Dict{T,T}() c = Vector{Vector{T}}() i = one(T) - for (v,l) in enumerate(labels) + for (v, l) in enumerate(labels) index = get!(d, l, i) if length(c) >= index push!(c[index], v) @@ -98,7 +98,7 @@ Return `true` if graph `g` is connected. For directed graphs, use [`is_weakly_connected`](@ref) or [`is_strongly_connected`](@ref). """ function is_connected end -@traitfn is_connected(g::::(!IsDirected)) = ne(g)+1 >= nv(g) && length(connected_components(g)) == 1 +@traitfn is_connected(g::::(!IsDirected)) = ne(g) + 1 >= nv(g) && length(connected_components(g)) == 1 """ weakly_connected_components(g) @@ -207,16 +207,16 @@ function period end # First check if there's a self loop has_self_loops(g) && return 1 - g_bfs_tree = bfs_tree(g,1) - levels = gdistances(g_bfs_tree,1) - tree_diff = difference(g,g_bfs_tree) + g_bfs_tree = bfs_tree(g, 1) + levels = gdistances(g_bfs_tree, 1) + tree_diff = difference(g, g_bfs_tree) edge_values = Vector{T}() divisor = 0 for e in edges(tree_diff) @inbounds value = levels[src(e)] - levels[dst(e)] + 1 - divisor = gcd(divisor,value) - isequal(divisor,1) && return 1 + divisor = gcd(divisor, value) + isequal(divisor, 1) && return 1 end return divisor @@ -235,19 +235,19 @@ function condensation end component = Vector{T}(nv(g)) - for (i,s) in enumerate(scc) + for (i, s) in enumerate(scc) @inbounds component[s] = i end @inbounds for e in edges(g) s, d = component[src(e)], component[dst(e)] if (s != d) - add_edge!(h,s,d) + add_edge!(h, s, d) end end return h end -@traitfn condensation(g::::IsDirected) = condensation(g,strongly_connected_components(g)) +@traitfn condensation(g::::IsDirected) = condensation(g, strongly_connected_components(g)) """ attracting_components(g) @@ -262,13 +262,13 @@ function attracting_components end @traitfn function attracting_components(g::::IsDirected) T = eltype(g) scc = strongly_connected_components(g) - cond = condensation(g,scc) + cond = condensation(g, scc) attracting = Vector{T}() for v in vertices(cond) - if outdegree(cond,v) == 0 - push!(attracting,v) + if outdegree(cond, v) == 0 + push!(attracting, v) end end return scc[attracting] @@ -322,8 +322,8 @@ Return true if the degree sequence `degs` is graphical, according to function isgraphical(degs::Vector{Int}) iseven(sum(degs)) || return false n = length(degs) - for r=1:n-1 - cond = sum(i->degs[i], 1:r) <= r*(r-1) + sum(i->min(r,degs[i]), r+1:n) + for r = 1:(n - 1) + cond = sum(i -> degs[i], 1:r) <= r * (r - 1) + sum(i -> min(r, degs[i]), (r + 1):n) cond || return false end return true diff --git a/src/core.jl b/src/core.jl index cdabc3deb..bce665b5b 100644 --- a/src/core.jl +++ b/src/core.jl @@ -16,7 +16,7 @@ is_ordered(e::AbstractEdge) = src(e) <= dst(e) Add `n` new vertices to the graph `g`. Return `true` if all vertices were added successfully, `false` otherwise. """ -add_vertices!(g::AbstractGraph, n::Integer) = all([add_vertex!(g) for i=1:n]) +add_vertices!(g::AbstractGraph, n::Integer) = all([add_vertex!(g) for i = 1:n]) """ indegree(g[, v]) @@ -25,7 +25,7 @@ Return a vector corresponding to the number of edges which end at each vertex in graph `g`. If `v` is specified, only return degrees for vertices in `v`. """ indegree(g::AbstractGraph, v::Integer) = length(in_neighbors(g, v)) -indegree(g::AbstractGraph, v::AbstractVector = vertices(g)) = [indegree(g,x) for x in v] +indegree(g::AbstractGraph, v::AbstractVector = vertices(g)) = [indegree(g, x) for x in v] """ outdegree(g[, v]) @@ -34,7 +34,7 @@ Return a vector corresponding to the number of edges which start at each vertex graph `g`. If `v` is specified, only return degrees for vertices in `v`. """ outdegree(g::AbstractGraph, v::Integer) = length(out_neighbors(g, v)) -outdegree(g::AbstractGraph, v::AbstractVector = vertices(g)) = [outdegree(g,x) for x in v] +outdegree(g::AbstractGraph, v::AbstractVector = vertices(g)) = [outdegree(g, x) for x in v] """ degree(g[, v]) @@ -54,40 +54,40 @@ degree(g::AbstractGraph, v::AbstractVector = vertices(g)) = [degree(g, x) for x Return the maximum [`outdegree`](@ref) of vertices in `g`. """ -Δout(g) = noallocextreme(outdegree,(>), typemin(Int), g) +Δout(g) = noallocextreme(outdegree, (>), typemin(Int), g) """ δout(g) Return the minimum [`outdegree`](@ref) of vertices in `g`. """ -δout(g) = noallocextreme(outdegree,(<), typemax(Int), g) +δout(g) = noallocextreme(outdegree, (<), typemax(Int), g) """ Δin(g) Return the maximum [`indegree`](@ref) of vertices in `g`. """ -Δin(g) = noallocextreme(indegree,(>), typemin(Int), g) +Δin(g) = noallocextreme(indegree, (>), typemin(Int), g) """ δin(g) Return the minimum [`indegree`](ref) of vertices in `g`. """ -δin(g) = noallocextreme(indegree,(<), typemax(Int), g) +δin(g) = noallocextreme(indegree, (<), typemax(Int), g) """ Δ(g) Return the maximum [`degree`](@ref) of vertices in `g`. """ -Δ(g) = noallocextreme(degree,(>), typemin(Int), g) +Δ(g) = noallocextreme(degree, (>), typemin(Int), g) """ δ(g) Return the minimum [`degree`](@ref) of vertices in `g`. """ -δ(g) = noallocextreme(degree,(<), typemax(Int), g) +δ(g) = noallocextreme(degree, (<), typemax(Int), g) """ @@ -115,7 +115,7 @@ Degree function (for example, `indegree` or `outdegree`) may be specified by overriding `degfn`. """ function degree_histogram(g::AbstractGraph, degfn=degree) - hist = Dict{eltype(g), Int}() + hist = Dict{eltype(g),Int}() for v in vertices(g) # minimize allocations by for d in degfn(g, v) # iterating over vertices hist[d] = get(hist, d, 0) + 1 @@ -169,14 +169,14 @@ common_neighbors(g::AbstractGraph, u::Integer, v::Integer) = Return true if `g` has any self loops. """ -has_self_loops(g::AbstractGraph) = nv(g) == 0? false : any(v->has_edge(g, v, v), vertices(g)) +has_self_loops(g::AbstractGraph) = nv(g) == 0 ? false : any(v -> has_edge(g, v, v), vertices(g)) """ num_self_loops(g) Return the number of self loops in `g`. """ -num_self_loops(g::AbstractGraph) = nv(g) == 0 ? 0 : sum(v->has_edge(g, v, v), vertices(g)) +num_self_loops(g::AbstractGraph) = nv(g) == 0 ? 0 : sum(v -> has_edge(g, v, v), vertices(g)) @doc_str """ density(g) @@ -187,9 +187,9 @@ number of possible edges (``|V|×(|V|-1)`` for directed graphs and """ function density end @traitfn density(g::::IsDirected) = -ne(g) / (nv(g) * (nv(g)-1)) +ne(g) / (nv(g) * (nv(g) - 1)) @traitfn density(g::::(!IsDirected)) = -(2*ne(g)) / (nv(g) * (nv(g)-1)) +(2 * ne(g)) / (nv(g) * (nv(g) - 1)) """ @@ -199,7 +199,7 @@ Return a copy of a graph with the smallest practical type that can accommodate all vertices. """ function squash(g::AbstractGraph) - gtype = is_directed(g)? DiGraph : Graph + gtype = is_directed(g) ? DiGraph : Graph validtypes = [UInt8, UInt16, UInt32, UInt64, Int] nvg = nv(g) for T in validtypes diff --git a/src/degeneracy.jl b/src/degeneracy.jl index 018b11aad..3973b1b5a 100644 --- a/src/degeneracy.jl +++ b/src/degeneracy.jl @@ -26,8 +26,8 @@ function core_number(g::AbstractGraph) curr_degree = 0 for (i, v) in enumerate(vs) if degrees[v] > curr_degree - append!(bin_boundaries, repmat([i], (degrees[v]-curr_degree))) - curr_degree=degrees[v] + append!(bin_boundaries, repmat([i], (degrees[v] - curr_degree))) + curr_degree = degrees[v] end end vertex_pos = sortperm(vs) @@ -39,11 +39,11 @@ function core_number(g::AbstractGraph) if core[u] > core[v] pop!(nbrs[u], v) pos = vertex_pos[u] - bin_start = bin_boundaries[core[u]+1] + bin_start = bin_boundaries[core[u] + 1] vertex_pos[u] = bin_start vertex_pos[vs[bin_start]] = pos vs[bin_start], vs[pos] = vs[pos], vs[bin_start] - bin_boundaries[core[u]+1] += 1 + bin_boundaries[core[u] + 1] += 1 core[u] -= 1 end end @@ -72,7 +72,7 @@ function k_core(g::AbstractGraph, k=-1; corenum=core_number(g)) k = maximum(corenum) # max core end - return find(x->x>=k, corenum) + return find(x -> x >= k, corenum) end """ @@ -126,9 +126,9 @@ Not implemented for graphs with self loops. """ function k_crust(g, k=-1; corenum=core_number(g)) if k == -1 - k=maximum(corenum) - 1 + k = maximum(corenum) - 1 end - return find(x-> x <= k, corenum) + return find(x -> x <= k, corenum) end """ @@ -151,7 +151,7 @@ Not implemented for graphs with parallel edges or self loops. http://link.aps.org/doi/10.1103/PhysRevE.73.056101 """ function k_corona(g::AbstractGraph, k; corenum=core_number(g)) - kcore = k_core(g,k) + kcore = k_core(g, k) kcoreg = g[kcore] kcoredeg = degree(kcoreg) diff --git a/src/digraph/cycles/hadwick-james.jl b/src/digraph/cycles/hadwick-james.jl index 96ec93662..b3a1f104f 100644 --- a/src/digraph/cycles/hadwick-james.jl +++ b/src/digraph/cycles/hadwick-james.jl @@ -86,7 +86,7 @@ function unblock!(v::T, blocked::BitArray, B::Vector{Vector{T}}) where T Bv = B[v] while wPos <= length(Bv) w = Bv[wPos] - wPos += 1 - (length(Bv) - length(filter!(v->v == w, Bv))) + wPos += 1 - (length(Bv) - length(filter!(v -> v == w, Bv))) if blocked[w] unblock!(w, blocked, B) end diff --git a/src/digraph/cycles/johnson.jl b/src/digraph/cycles/johnson.jl index 3af3f1964..c6dd30ce3 100644 --- a/src/digraph/cycles/johnson.jl +++ b/src/digraph/cycles/johnson.jl @@ -6,8 +6,8 @@ abstract type Visitor{T<:Integer} end Compute the theoretical maximum number of cycles of size `i` in a directed graph of `n` vertices. """ -ncycles_n_i(n::Integer, i::Integer) = binomial(big(n), big(n-i+1)) * factorial(big(n-i)) - +ncycles_n_i(n::Integer, i::Integer) = + binomial(big(n), big(n - i + 1)) * factorial(big(n - i)) """ maxsimplecycles(n::Integer) @@ -19,8 +19,7 @@ The formula is coming from [Johnson, 1973](Johnson). ### References - [Johnson](http://epubs.siam.org/doi/abs/10.1137/0204007). """ - -maxsimplecycles(n::Integer) = sum(x -> ncycles_n_i(n, x), 1:(n-1)) +maxsimplecycles(n::Integer) = sum(x -> ncycles_n_i(n, x), 1:(n - 1)) @doc_str """ @@ -81,9 +80,8 @@ end Constructor of the visitor, using the directed graph information. """ -JohnsonVisitor{T<:Integer}(dg::DiGraph{T}) = JohnsonVisitor(Vector{T}(), - falses(vertices(dg)), - [Set{T}() for i in vertices(dg)]) +JohnsonVisitor(dg::DiGraph{T}) where T<:Integer = + JohnsonVisitor(Vector{T}(), falses(vertices(dg)), [Set{T}() for i in vertices(dg)]) """ unblock!{T<:Integer}(v::T, blocked::BitArray, B::Vector{Set{T}}) @@ -94,7 +92,7 @@ Unblock the vertices recursively. not and `B` is the map that tells if the unblocking of one vertex should unblock other vertices. """ -function unblock!{T<:Integer}(v::T, blocked::BitArray, B::Vector{Set{T}}) +function unblock!(v::T, blocked::BitArray, B::Vector{Set{T}}) where T<:Integer blocked[v] = false for w in B[v] delete!(B[v], w) @@ -134,7 +132,7 @@ allcycles::Vector{Vector{T}}, vmap::Vector{T}, startnode::T = v) done = false push!(vis.stack, v) vis.blocked[v] = true - for w in out_neighbors(dg,v) + for w in out_neighbors(dg, v) if w == startnode push!(allcycles, vmap[vis.stack]) done = true @@ -175,7 +173,7 @@ function simplecycles end sccs = strongly_connected_components(dg) cycles = Vector{Vector{Int}}() # Pas très cohérent : devrait être du type de dg. for scc in sccs - for i in 1:(length(scc)-1) + for i in 1:(length(scc) - 1) wdg, vmap = induced_subgraph(dg, scc[i:end]) visitor = JohnsonVisitor(wdg) circuit(1, wdg, visitor, cycles, vmap) # 1 is the startnode. @@ -287,7 +285,7 @@ Returns the minimum of the ceiling and the number of cycles. function simplecyclescount end @traitfn function simplecyclescount(dg::::IsDirected, ceiling = 10^6) len = 0 - for cycle in Iterators.take(Channel(c->itercycles(dg,c)), ceiling) + for cycle in Iterators.take(Channel(c -> itercycles(dg, c)), ceiling) len += 1 end return len @@ -312,7 +310,8 @@ To get an idea of the possible number of cycles, using function - [Johnson](http://epubs.siam.org/doi/abs/10.1137/0204007) """ function simplecycles_iter end -@traitfn simplecycles_iter(dg::::IsDirected, ceiling = 10^6) = collect(Iterators.take(Channel(c->itercycles(dg,c)), ceiling)) +@traitfn simplecycles_iter(dg::::IsDirected, ceiling = 10^6) = + collect(Iterators.take(Channel(c -> itercycles(dg, c)), ceiling)) @doc_str """ simplecycleslength(dg::DiGraph, ceiling = 10^6) @@ -336,8 +335,8 @@ function simplecycleslength end @traitfn function simplecycleslength(dg::::IsDirected, ceiling = 10^6) ncycles = 0 cyclelength = zeros(Int, nv(dg)) - for cycle in Iterators.take(Channel(c->itercycles(dg,c)), ceiling) - cyclelength[length(cycle)] +=1 + for cycle in Iterators.take(Channel(c -> itercycles(dg, c)), ceiling) + cyclelength[length(cycle)] += 1 ncycles += 1 end return cyclelength, ncycles diff --git a/src/digraph/transitivity.jl b/src/digraph/transitivity.jl index bcea8fb73..1a12641cb 100644 --- a/src/digraph/transitivity.jl +++ b/src/digraph/transitivity.jl @@ -18,7 +18,7 @@ function transitiveclosure! end for j in vertices(g) j == k && continue if (has_edge(g, i, k) && has_edge(g, k, j)) - if ( i != j || selflooped ) + if (i != j || selflooped) add_edge!(g, i, j) end end diff --git a/src/distance.jl b/src/distance.jl index c81d58f39..e45c00c83 100644 --- a/src/distance.jl +++ b/src/distance.jl @@ -46,7 +46,7 @@ function eccentricity( v::Integer, distmx::AbstractMatrix{T} = weights(g) ) where T - e = maximum(dijkstra_shortest_paths(g,v,distmx).dists) + e = maximum(dijkstra_shortest_paths(g, v, distmx).dists) e == typemax(T) && error("Infinite path length detected") return e @@ -56,7 +56,7 @@ eccentricity( g::AbstractGraph, vs::AbstractVector = vertices(g), distmx::AbstractMatrix = weights(g) -) = [eccentricity(g,v,distmx) for v in vs] +) = [eccentricity(g, v, distmx) for v in vs] eccentricity(g::AbstractGraph, distmx::AbstractMatrix) = eccentricity(g, vertices(g), distmx) @@ -69,7 +69,7 @@ Given a graph and optional distance matrix, or a vector of precomputed eccentricities, return the maximum eccentricity of the graph. """ diameter(eccentricities::Vector) = maximum(eccentricities) -diameter(g::AbstractGraph, distmx::AbstractMatrix = weights(g))= +diameter(g::AbstractGraph, distmx::AbstractMatrix = weights(g)) = maximum(eccentricity(g, distmx)) """ @@ -83,7 +83,7 @@ largest eccentricity). """ function periphery(eccentricities::Vector) diam = maximum(eccentricities) - return filter((x)->eccentricities[x] == diam, 1:length(eccentricities)) + return filter(x -> eccentricities[x] == diam, 1:length(eccentricities)) end periphery(g::AbstractGraph, distmx::AbstractMatrix = weights(g)) = @@ -110,7 +110,7 @@ to the graph's radius (that is, the set of vertices with the smallest eccentrici """ function center(eccentricities::Vector) rad = radius(eccentricities) - return filter((x)->eccentricities[x] == rad, 1:length(eccentricities)) + return filter(x -> eccentricities[x] == rad, 1:length(eccentricities)) end center(g::AbstractGraph, distmx::AbstractMatrix = weights(g)) = diff --git a/src/edit_distance.jl b/src/edit_distance.jl index d20746048..1401f6955 100644 --- a/src/edit_distance.jl +++ b/src/edit_distance.jl @@ -41,9 +41,9 @@ if involved costs are equivalent. - Júlio Hoffimann Mendes (juliohm@stanford.edu) """ function edit_distance(G₁::AbstractGraph, G₂::AbstractGraph; - insert_cost::Function=v->1.0, - delete_cost::Function=u->1.0, - subst_cost::Function=(u,v)->0.5, + insert_cost::Function = v -> 1.0, + delete_cost::Function = u -> 1.0, + subst_cost::Function= (u, v) -> 0.5, heuristic::Function=DefaultEditHeuristic) # A* search heuristic @@ -52,9 +52,9 @@ function edit_distance(G₁::AbstractGraph, G₂::AbstractGraph; # initialize open set OPEN = PriorityQueue(Vector{Tuple}, Float64) for v in 1:nv(G₂) - enqueue!(OPEN, [(1,v)], subst_cost(1,v) + h([(1,v)])) + enqueue!(OPEN, [(1, v)], subst_cost(1, v) + h([(1, v)])) end - enqueue!(OPEN, [(1,0)], delete_cost(1) + h([(1,0)])) + enqueue!(OPEN, [(1, 0)], delete_cost(1) + h([(1, 0)])) while true # minimum (partial) edit path @@ -65,18 +65,18 @@ function edit_distance(G₁::AbstractGraph, G₂::AbstractGraph; return cost, λ else k, _ = λ[end] - vs = setdiff(1:nv(G₂), [v for (u,v) in λ]) + vs = setdiff(1:nv(G₂), [v for (u, v) in λ]) if k < nv(G₁) # there are still vertices to process in G₁? for v in vs - λ⁺ = [λ; (k+1,v)] - enqueue!(OPEN, λ⁺, cost + subst_cost(k+1,v) + h(λ⁺) - h(λ)) + λ⁺ = [λ; (k + 1, v)] + enqueue!(OPEN, λ⁺, cost + subst_cost(k + 1, v) + h(λ⁺) - h(λ)) end - λ⁺ = [λ; (k+1,0)] - enqueue!(OPEN, λ⁺, cost + delete_cost(k+1) + h(λ⁺) - h(λ)) + λ⁺ = [λ; (k + 1, 0)] + enqueue!(OPEN, λ⁺, cost + delete_cost(k + 1) + h(λ⁺) - h(λ)) else # add remaining vertices of G₂ to the path - λ⁺ = [λ; [(0,v) for v in vs]] + λ⁺ = [λ; [(0, v) for v in vs]] total_insert_cost = sum(insert_cost, vs) enqueue!(OPEN, λ⁺, cost + total_insert_cost + h(λ⁺) - h(λ)) end @@ -86,7 +86,7 @@ end function is_complete_path(λ, G₁, G₂) us = Set(); vs = Set() - for (u,v) in λ + for (u, v) in λ push!(us, u) push!(vs, v) end @@ -97,7 +97,7 @@ function is_complete_path(λ, G₁, G₂) end function DefaultEditHeuristic(λ, G₁::AbstractGraph, G₂::AbstractGraph) - vs = Set([v for (u,v) in λ]) + vs = Set([v for (u, v) in λ]) delete!(vs, 0) return nv(G₂) - length(vs) @@ -119,7 +119,7 @@ vertex v ∈ G₂. `p=1`: the p value for p-norm calculation. """ function MinkowskiCost(μ₁::AbstractVector, μ₂::AbstractVector; p::Real=1) - (u,v) -> norm(μ₁[u] - μ₂[v], p) + (u, v) -> norm(μ₁[u] - μ₂[v], p) end """ @@ -132,5 +132,5 @@ Return value similar to `MinkowskiCost`, but ensure costs smaller than 2τ. `τ=1`: value specifying half of the upper limit of the Minkowski cost. """ function BoundedMinkowskiCost(μ₁::AbstractVector, μ₂::AbstractVector; p::Real=1, τ::Real=1) - (u,v) -> 1 / (1/(2τ) + exp(-norm(μ₁[u] - μ₂[v], p))) + (u, v) -> 1 / (1 / (2τ) + exp(-norm(μ₁[u] - μ₂[v], p))) end diff --git a/src/flow/boykov_kolmogorov.jl b/src/flow/boykov_kolmogorov.jl index c42772758..49ce3db46 100644 --- a/src/flow/boykov_kolmogorov.jl +++ b/src/flow/boykov_kolmogorov.jl @@ -36,7 +36,7 @@ function boykov_kolmogorov_impl end PARENT = zeros(U, n) - A = [source,target] + A = [source, target] O = Vector{U}() while true @@ -66,12 +66,12 @@ end A::Vector # active set ) T = eltype(residual_graph) - tree_cap(p,q) = TREE[p] == one(T) ? capacity_matrix[p,q] - flow_matrix[p,q] : - capacity_matrix[q,p] - flow_matrix[q,p] + tree_cap(p, q) = TREE[p] == one(T) ? capacity_matrix[p, q] - flow_matrix[p, q] : + capacity_matrix[q, p] - flow_matrix[q, p] while !isempty(A) p = last(A) for q in neighbors(residual_graph, p) - if tree_cap(p,q) > 0 + if tree_cap(p, q) > 0 if TREE[q] == zero(T) TREE[q] = TREE[p] PARENT[q] = p @@ -121,20 +121,20 @@ function augment!( T = eltype(path) # bottleneck capacity Δ = Inf - for i=1:length(path)-1 - p, q = path[i:i+1] - cap = capacity_matrix[p,q] - flow_matrix[p,q] + for i = 1:(length(path) - 1) + p, q = path[i:(i + 1)] + cap = capacity_matrix[p, q] - flow_matrix[p, q] cap < Δ && (Δ = cap) end # update residual graph - for i=1:length(path)-1 - p, q = path[i:i+1] - flow_matrix[p,q] += Δ - flow_matrix[q,p] -= Δ + for i = 1:(length(path) - 1) + p, q = path[i:(i + 1)] + flow_matrix[p, q] += Δ + flow_matrix[q, p] -= Δ # create orphans - if flow_matrix[p,q] == capacity_matrix[p,q] + if flow_matrix[p, q] == capacity_matrix[p, q] if TREE[p] == TREE[q] == one(T) PARENT[q] = zero(T) unshift!(O, q) @@ -162,14 +162,14 @@ end ) T = eltype(residual_graph) - tree_cap(p,q) = TREE[p] == 1 ? capacity_matrix[p,q] - flow_matrix[p,q] : - capacity_matrix[q,p] - flow_matrix[q,p] + tree_cap(p, q) = TREE[p] == 1 ? capacity_matrix[p, q] - flow_matrix[p, q] : + capacity_matrix[q, p] - flow_matrix[q, p] while !isempty(O) p = pop!(O) # try to find parent that is not an orphan parent_found = false for q in neighbors(residual_graph, p) - if TREE[q] == TREE[p] && tree_cap(q,p) > 0 + if TREE[q] == TREE[p] && tree_cap(q, p) > 0 # check if "origin" is either source or target o = q while PARENT[o] ≠ 0 @@ -187,7 +187,7 @@ end # scan all neighbors and make the orphan a free node for q in neighbors(residual_graph, p) if TREE[q] == TREE[p] - if tree_cap(q,p) > 0 + if tree_cap(q, p) > 0 unshift!(A, q) end if PARENT[q] == p diff --git a/src/flow/dinic.jl b/src/flow/dinic.jl index c57d75e54..53220c2f9 100644 --- a/src/flow/dinic.jl +++ b/src/flow/dinic.jl @@ -56,7 +56,7 @@ function blocking_flow! end while length(Q) > 0 # Construct the Level Graph using BFS u = pop!(Q) for v in out_neighbors(residual_graph, u) - if P[v] == -1 && capacity_matrix[u,v] > flow_matrix[u,v] + if P[v] == -1 && capacity_matrix[u, v] > flow_matrix[u, v] P[v] = u unshift!(Q, v) end @@ -76,7 +76,7 @@ function blocking_flow! end flow = 0 break else - flow = min(flow, capacity_matrix[u,v] - flow_matrix[u,v]) + flow = min(flow, capacity_matrix[u, v] - flow_matrix[u, v]) v = u u = P[u] end @@ -87,8 +87,8 @@ function blocking_flow! end v = target u = bv while v != source # Augment flow along path - flow_matrix[u,v] += flow - flow_matrix[v,u] -= flow + flow_matrix[u, v] += flow + flow_matrix[v, u] -= flow v = u u = P[u] end diff --git a/src/flow/edmonds_karp.jl b/src/flow/edmonds_karp.jl index 7160324b7..67ca87438 100644 --- a/src/flow/edmonds_karp.jl +++ b/src/flow/edmonds_karp.jl @@ -22,7 +22,7 @@ function edmonds_karp_impl end while true fill!(P, -1) fill!(S, -1) - v, P, S, flag = fetch_path!(residual_graph, source, target, flow_matrix, capacity_matrix, P,S) + v, P, S, flag = fetch_path!(residual_graph, source, target, flow_matrix, capacity_matrix, P, S) if flag != 0 # no more valid paths break @@ -31,14 +31,14 @@ function edmonds_karp_impl end sizehint!(path, n) u = v - while u!=source # trace path from v to source + while u != source # trace path from v to source u = P[u] push!(path, u) end reverse!(path) u = v # trace path from v to target - while u!=target + while u != target u = S[u] push!(path, Int(u)) end @@ -63,17 +63,17 @@ function augment_path!( ) T = eltype(flow_matrix) augment = typemax(T) # initialize augment - for i in 1:length(path)-1 # calculate min capacity along path + for i in 1:(length(path) - 1) # calculate min capacity along path u = path[i] - v = path[i+1] - augment = min(augment,capacity_matrix[u,v] - flow_matrix[u,v]) + v = path[i + 1] + augment = min(augment, capacity_matrix[u, v] - flow_matrix[u, v]) end - for i in 1:length(path)-1 # augment flow along path + for i in 1:(length(path) - 1) # augment flow along path u = path[i] - v = path[i+1] - flow_matrix[u,v] += augment - flow_matrix[v,u] -= augment + v = path[i + 1] + flow_matrix[u, v] += augment + flow_matrix[v, u] -= augment end return augment @@ -110,7 +110,7 @@ function fetch_path! end if length(Q_f) <= length(Q_r) u = pop!(Q_f) for v in out_neighbors(residual_graph, u) - if capacity_matrix[u,v] - flow_matrix[u,v] > 0 && P[v] == -1 + if capacity_matrix[u, v] - flow_matrix[u, v] > 0 && P[v] == -1 P[v] = u if S[v] == -1 unshift!(Q_f, v) @@ -124,9 +124,9 @@ function fetch_path! end else v = pop!(Q_r) for u in in_neighbors(residual_graph, v) - if capacity_matrix[u,v] - flow_matrix[u,v] > 0 && S[u] == -1 + if capacity_matrix[u, v] - flow_matrix[u, v] > 0 && S[u] == -1 S[u] = v - P[u] != -1 && return u, P, S, 0 # 0 indicates success + P[u] != -1 && return u, P, S, 0 # 0 indicates success unshift!(Q_r, u) end diff --git a/src/flow/ext_multiroute_flow.jl b/src/flow/ext_multiroute_flow.jl index 93ad5d24f..f71a9deaa 100644 --- a/src/flow/ext_multiroute_flow.jl +++ b/src/flow/ext_multiroute_flow.jl @@ -114,7 +114,7 @@ function breakingPoints end λ = length(auxpoints) - 1 left_index = 1 T = eltype(capacity_matrix) - breakingpoints = Vector{Tuple{T, T, Int}}() + breakingpoints = Vector{Tuple{T,T,Int}}() for (id, point) in enumerate(auxpoints) if id == 1 @@ -124,7 +124,7 @@ function breakingPoints end if point[1] != 0 x, y = intersection(pleft[1], pleft[2], pleft[3], point[1], point[2], λ + 1 - id) - push!(breakingpoints,(x, y, λ + 1 - id)) + push!(breakingpoints, (x, y, λ + 1 - id)) left_index += 1 end end @@ -224,7 +224,7 @@ Return the intersection of a set of line segments and a line of slope `k` passing by the origin. Segments are defined as a triple (x, y, slope). """ function intersection( - points::Vector{Tuple{T, T, I}}, # vector of breaking points + points::Vector{Tuple{T,T,I}}, # vector of breaking points k::R # number of routes (slope of the line) ) where T<:AbstractFloat where I<:Integer where R<:Real λ = points[1][1] # Connectivity @@ -250,5 +250,5 @@ Return true if each element in the tuple is approximately equal to its counterpa ### Implementation Notes: This is a separate function because we don't want to hijack isapprox for tuples. """ -approximately_equal(a::Tuple{T, T}, b::Tuple{T, T}) where T <: AbstractFloat = +approximately_equal(a::Tuple{T,T}, b::Tuple{T,T}) where T <: AbstractFloat = a[1] ≈ b[1] && a[2] ≈ b[2] diff --git a/src/flow/maximum_flow.jl b/src/flow/maximum_flow.jl index 9dc5ef931..76fc003ce 100644 --- a/src/flow/maximum_flow.jl +++ b/src/flow/maximum_flow.jl @@ -44,7 +44,7 @@ end @traitfn DefaultCapacity(flow_graph::::IsDirected) = DefaultCapacity(DiGraph(flow_graph), nv(flow_graph)) -getindex(d::DefaultCapacity{T}, s::Integer, t::Integer) where T = if has_edge(d.flow_graph, s , t) one(T) else zero(T) end +getindex(d::DefaultCapacity{T}, s::Integer, t::Integer) where T = if has_edge(d.flow_graph, s, t) one(T) else zero(T) end # isassigned{T<:Integer}(d::DefaultCapacity{T}, u::T, v::T) = (u in 1:d.nv) && (v in 1:d.nv) size(d::DefaultCapacity) = (Int(d.nv), Int(d.nv)) transpose(d::DefaultCapacity) = DefaultCapacity(reverse(d.flow_graph)) diff --git a/src/flow/multiroute_flow.jl b/src/flow/multiroute_flow.jl index 90449150b..66023b2ab 100644 --- a/src/flow/multiroute_flow.jl +++ b/src/flow/multiroute_flow.jl @@ -54,7 +54,7 @@ end ## Methods for Extended Multiroute Flow Algorithm #1 When the breaking points are not already known @traitfn function multiroute_flow( - flow_graph::::IsDirected, # the input graph + flow_graph::::IsDirected, # the input graph source::Integer, # the source vertex target::Integer, # the target vertex capacity_matrix::AbstractMatrix, # edge flow capacities @@ -67,14 +67,14 @@ end #2 When the breaking points are already known #2-a Output: flow value (paired with the associated restriction) multiroute_flow( - breakingpoints::Vector{Tuple{T, T, Int}}, # vector of breaking points + breakingpoints::Vector{Tuple{T,T,Int}}, # vector of breaking points routes::R # keyword argument for routes ) where T<:Real where R<:Real = intersection(breakingpoints, routes) #2-b Output: flow value, flows(, labels) function multiroute_flow( - breakingpoints::AbstractVector{Tuple{T1, T1, Int}}, # vector of breaking points + breakingpoints::AbstractVector{Tuple{T1,T1,Int}}, # vector of breaking points routes::R, # keyword argument for routes flow_graph::AbstractGraph, # the input graph source::Integer, # the source vertex diff --git a/src/flow/push_relabel.jl b/src/flow/push_relabel.jl index 803af8f98..44071d2f8 100644 --- a/src/flow/push_relabel.jl +++ b/src/flow/push_relabel.jl @@ -22,9 +22,9 @@ function push_relabel end height = zeros(Int, n) height[source] = n - count = zeros(Int, 2*n+1) - count[0+1] = n-1 - count[n+1] = 1 + count = zeros(Int, 2 * n + 1) + count[0 + 1] = n - 1 + count[n + 1] = 1 excess = zeros(T, n) excess[source] = typemax(T) @@ -47,7 +47,7 @@ function push_relabel end discharge!(residual_graph, v, capacity_matrix, flow_matrix, excess, height, active, count, Q) end - return sum([flow_matrix[v,target] for v in in_neighbors(residual_graph, target) ]), flow_matrix + return sum([flow_matrix[v, target] for v in in_neighbors(residual_graph, target)]), flow_matrix end """ @@ -89,13 +89,13 @@ function push_flow! end active::AbstractVector{Bool}, Q::AbstractVector ) - flow = min(excess[u], capacity_matrix[u,v] - flow_matrix[u,v]) + flow = min(excess[u], capacity_matrix[u, v] - flow_matrix[u, v]) flow == 0 && return nothing height[u] <= height[v] && return nothing - flow_matrix[u,v] += flow - flow_matrix[v,u] -= flow + flow_matrix[u, v] += flow + flow_matrix[v, u] -= flow excess[u] -= flow excess[v] += flow @@ -133,9 +133,9 @@ function gap! end n = nv(residual_graph) for v in vertices(residual_graph) height[v] < h && continue - count[height[v]+1] -= 1 + count[height[v] + 1] -= 1 height[v] = max(height[v], n + 1) - count[height[v]+1] += 1 + count[height[v] + 1] += 1 enqueue_vertex!(Q, v, active, excess) end nothing @@ -159,14 +159,14 @@ function relabel! end Q::AbstractVector ) n = nv(residual_graph) - count[height[v]+1] -= 1 - height[v] = 2*n + count[height[v] + 1] -= 1 + height[v] = 2 * n for to in out_neighbors(residual_graph, v) - if capacity_matrix[v,to] > flow_matrix[v,to] - height[v] = min(height[v], height[to]+1) + if capacity_matrix[v, to] > flow_matrix[v, to] + height[v] = min(height[v], height[to] + 1) end end - count[height[v]+1] += 1 + count[height[v] + 1] += 1 enqueue_vertex!(Q, v, active, excess) nothing end @@ -196,7 +196,7 @@ function discharge! end end if excess[v] > 0 - if count[height[v]+1] == 1 + if count[height[v] + 1] == 1 gap!(residual_graph, height[v], excess, height, active, count, Q) else relabel!(residual_graph, v, capacity_matrix, flow_matrix, excess, height, active, count, Q) diff --git a/src/generators/euclideangraphs.jl b/src/generators/euclideangraphs.jl index 58e12adbe..c0787e3d0 100644 --- a/src/generators/euclideangraphs.jl +++ b/src/generators/euclideangraphs.jl @@ -35,23 +35,23 @@ function euclidean_graph(points::Matrix; d, N = size(points) g = Graph(N) weights = Dict{Edge,Float64}() - cutoff < 0. && (cutoff=typemax(Float64)) + cutoff < 0. && (cutoff = typemax(Float64)) if bc == :periodic - maximum(points) > L && error("Some points are outside the box of size $L.") + maximum(points) > L && error("Some points are outside the box of size $L.") end - for i=1:N - for j=i+1:N + for i = 1:N + for j = (i + 1):N if bc == :open - Δ = points[:,i]-points[:,j] + Δ = points[:, i] - points[:, j] elseif bc == :periodic - Δ = abs.(points[:,i]-points[:,j]) + Δ = abs.(points[:, i] - points[:, j]) Δ = min.(L - Δ, Δ) else error("Not a valid boundary condition.") end dist = norm(Δ, p) if dist < cutoff - e = Edge(i,j) + e = Edge(i, j) add_edge!(g, e) weights[e] = dist end diff --git a/src/generators/randgraphs.jl b/src/generators/randgraphs.jl index ab2779b15..bc876da96 100644 --- a/src/generators/randgraphs.jl +++ b/src/generators/randgraphs.jl @@ -1,8 +1,8 @@ function Graph{T}(nv::Integer, ne::Integer; seed::Int = -1) where T <: Integer tnv = T(nv) - maxe = div(Int(nv) * (nv-1), 2) + maxe = div(Int(nv) * (nv - 1), 2) @assert(ne <= maxe, "Maximum number of edges for this graph is $maxe") - ne > 2/3 * maxe && return complement(Graph(nv, maxe-ne)) + ne > (2 / 3) * maxe && return complement(Graph(nv, maxe - ne)) rng = getRNG(seed) g = Graph(tnv) @@ -20,16 +20,16 @@ Graph(nv::T, ne::Integer; seed::Int = -1) where T<: Integer = function DiGraph{T}(nv::Integer, ne::Integer; seed::Int = -1) where T<:Integer tnv = T(nv) - maxe = Int(nv) * (nv-1) + maxe = Int(nv) * (nv - 1) @assert(ne <= maxe, "Maximum number of edges for this graph is $maxe") - ne > 2/3 * maxe && return complement(DiGraph{T}(nv, maxe-ne)) + ne > (2 / 3) * maxe && return complement(DiGraph{T}(nv, maxe - ne)) rng = getRNG(seed) g = DiGraph(tnv) while g.ne < ne source = rand(rng, one(T):tnv) dest = rand(rng, one(T):tnv) - source != dest && add_edge!(g,source,dest) + source != dest && add_edge!(g, source, dest) end return g end @@ -71,7 +71,7 @@ probability `p`. - `seed=-1`: set the RNG seed. """ function erdos_renyi(n::Integer, p::Real; is_directed=false, seed::Integer=-1) - m = is_directed ? n*(n-1) : div(n*(n-1),2) + m = is_directed ? n * (n - 1) : div(n * (n - 1), 2) ne = randbn(m, p, seed) return is_directed ? DiGraph(n, ne, seed=seed) : Graph(n, ne, seed=seed) end @@ -103,7 +103,7 @@ randomized per the model based on probability `β`. - `seed=-1`: set the RNG seed. """ function watts_strogatz(n::Integer, k::Integer, β::Real; is_directed=false, seed::Int = -1) - @assert k < n/2 + @assert k < n / 2 if is_directed g = DiGraph(n) else @@ -111,7 +111,7 @@ function watts_strogatz(n::Integer, k::Integer, β::Real; is_directed=false, see end rng = getRNG(seed) for s in 1:n - for i in 1:(floor(Integer, k/2)) + for i in 1:(floor(Integer, k / 2)) target = ((s + i - 1) % n) + 1 if rand(rng) > β && !has_edge(g, s, target) # TODO: optimize this based on return of add_edge! add_edge!(g, s, target) @@ -119,7 +119,7 @@ function watts_strogatz(n::Integer, k::Integer, β::Real; is_directed=false, see while true d = target while d == target - d = rand(rng, 1:n-1) + d = rand(rng, 1:(n - 1)) if s < d d += 1 end @@ -134,7 +134,7 @@ function watts_strogatz(n::Integer, k::Integer, β::Real; is_directed=false, see return g end -function _suitable(edges::Set{Edge}, potential_edges::Dict{T, T}) where T<:Integer +function _suitable(edges::Set{Edge}, potential_edges::Dict{T,T}) where T<:Integer isempty(potential_edges) && return true list = keys(potential_edges) for s1 in list, s2 in list @@ -144,25 +144,25 @@ function _suitable(edges::Set{Edge}, potential_edges::Dict{T, T}) where T<:Integ return false end -_try_creation(n::Integer, k::Integer, rng::AbstractRNG) = _try_creation(n, fill(k,n), rng) +_try_creation(n::Integer, k::Integer, rng::AbstractRNG) = _try_creation(n, fill(k, n), rng) function _try_creation(n::T, k::Vector{T}, rng::AbstractRNG) where T<:Integer edges = Set{Edge}() m = 0 stubs = zeros(T, sum(k)) - for i=one(T):n + for i = one(T):n for j = one(T):k[i] m += 1 stubs[m] = i end end - # stubs = vcat([fill(i, k[i]) for i=1:n]...) # slower + # stubs = vcat([fill(i, k[i]) for i = 1:n]...) # slower while !isempty(stubs) potential_edges = Dict{T,T}() shuffle!(rng, stubs) for i in 1:2:length(stubs) - s1,s2 = stubs[i:i+1] + s1, s2 = stubs[i:(i + 1)] if (s1 > s2) s1, s2 = s2, s1 end @@ -261,19 +261,19 @@ function barabasi_albert!(g::AbstractGraph, n::Integer, k::Integer; seed::Int=-1 n0 += 1 # add edges to k existing vertices - for target in sample!(collect(1:n0-1), k) + for target in sample!(collect(1:(n0 - 1)), k) add_edge!(g, n0, target) end end # vector of weighted vertices (each node is repeated once for each adjacent edge) - weightedVs = Vector{Int}(2*(n-n0)*k + 2*ne(g)) + weightedVs = Vector{Int}(2 * (n - n0) * k + 2 * ne(g)) # initialize vector of weighted vertices offset = 0 for e in edges(g) - weightedVs[offset+=1] = src(e) - weightedVs[offset+=1] = dst(e) + weightedVs[offset += 1] = src(e) + weightedVs[offset += 1] = dst(e) end # array to record if a node is picked @@ -282,14 +282,14 @@ function barabasi_albert!(g::AbstractGraph, n::Integer, k::Integer; seed::Int=-1 # vector of targets targets = Vector{Int}(k) - for source in n0+1:n + for source in (n0 + 1):n # choose k targets from the existing vertices # pick uniformly from weightedVs (preferential attachement) i = 0 while i < k target = weightedVs[rand(1:offset)] if !picked[target] - targets[i+=1] = target + targets[i += 1] = target picked[target] = true end end @@ -298,12 +298,11 @@ function barabasi_albert!(g::AbstractGraph, n::Integer, k::Integer; seed::Int=-1 for target in targets add_edge!(g, source, target) - weightedVs[offset+=1] = source - weightedVs[offset+=1] = target + weightedVs[offset += 1] = source + weightedVs[offset += 1] = target picked[target] = false end end - return g end @@ -335,7 +334,7 @@ function static_fitness_model(m::Integer, fitness::Vector{T}; seed::Int=-1) wher f > zero(T) && (nvs += 1) end # avoid getting into an infinite loop when too many edges are requested - max_no_of_edges = div(nvs*(nvs-1), 2) + max_no_of_edges = div(nvs * (nvs - 1), 2) @assert(m <= max_no_of_edges, "too many edges requested") # calculate the cumulative fitness scores cum_fitness = cumsum(fitness) @@ -367,14 +366,14 @@ function static_fitness_model(m::Integer, fitness_out::Vector{T}, fitness_in::Ve m == 0 && return DiGraph(n) # avoid getting into an infinite loop when too many edges are requested noutvs = ninvs = nvs = 0 - @inbounds for i=1:n + @inbounds for i = 1:n # sanity check for the fitness (fitness_out[i] < zero(T) || fitness_in[i] < zero(S)) && error("fitness scores must be non-negative") fitness_out[i] > zero(T) && (noutvs += 1) fitness_in[i] > zero(S) && (ninvs += 1) (fitness_out[i] > zero(T) && fitness_in[i] > zero(S)) && (nvs += 1) end - max_no_of_edges = noutvs*ninvs - nvs + max_no_of_edges = noutvs * ninvs - nvs @assert(m <= max_no_of_edges, "too many edges requested") # calculate the cumulative fitness scores cum_fitness_out = cumsum(fitness_out) @@ -389,8 +388,8 @@ function _create_static_fitness_graph!(g::AbstractGraph, m::Integer, cum_fitness max_out = cum_fitness_out[end] max_in = cum_fitness_in[end] while m > 0 - source = searchsortedfirst(cum_fitness_out, rand(rng)*max_out) - target = searchsortedfirst(cum_fitness_in, rand(rng)*max_in) + source = searchsortedfirst(cum_fitness_out, rand(rng) * max_out) + target = searchsortedfirst(cum_fitness_in, rand(rng) * max_in) # skip if loop edge (source == target) && continue edge = Edge(source, target) @@ -459,16 +458,16 @@ function static_scale_free(n::Integer, m::Integer, α_out::Real, α_in::Float64; end function _construct_fitness(n::Integer, α::Real, finite_size_correction::Bool) - α = -1/(α-1) + α = -1 / (α - 1) fitness = zeros(n) j = float(n) if finite_size_correction && α < -0.5 # See the Cho et al paper, first page first column + footnote 7 - j += n^(1+1/2α) * (10sqrt(2)*(1+α)) ^ (-1/α) - 1 + j += n^(1 + 1 / 2α) * (10sqrt(2) * (1 + α))^(-1 / α) - 1 end j = max(j, n) - @inbounds for i=1:n - fitness[i] = j ^ α + @inbounds for i = 1:n + fitness[i] = j^α j -= 1 end return fitness @@ -492,13 +491,13 @@ Allocates an array of `nk` `Int`s, and . For ``k > \\frac{n}{2}``, generates a g ``n-k-1`` and returns its complement. """ function random_regular_graph(n::Integer, k::Integer; seed::Int=-1) - @assert(iseven(n*k), "n * k must be even") + @assert(iseven(n * k), "n * k must be even") @assert(0 <= k < n, "the 0 <= k < n inequality must be satisfied") if k == 0 return Graph(n) end - if (k > n/2) && iseven(n * (n-k-1)) - return complement(random_regular_graph(n, n-k-1, seed=seed)) + if (k > n / 2) && iseven(n * (n - k - 1)) + return complement(random_regular_graph(n, n - k - 1, seed=seed)) end rng = getRNG(seed) @@ -578,17 +577,17 @@ function random_regular_digraph(n::Integer, k::Integer; dir::Symbol=:out, seed:: if k == 0 return DiGraph(n) end - if (k > n/2) && iseven(n * (n-k-1)) - return complement(random_regular_digraph(n, n-k-1, dir=dir, seed=seed)) + if (k > n / 2) && iseven(n * (n - k - 1)) + return complement(random_regular_digraph(n, n - k - 1, dir=dir, seed=seed)) end rng = getRNG(seed) cs = collect(2:n) i = 1 - I = Vector{Int}(n*k) - J = Vector{Int}(n*k) - V = fill(true, n*k) + I = Vector{Int}(n * k) + J = Vector{Int}(n * k) + V = fill(true, n * k) for r in 1:n - l = (r-1)*k+1 : r*k + l = ((r - 1) * k + 1):(r * k) I[l] = r J[l] = sample!(rng, cs, k, exclude = r) end @@ -617,25 +616,25 @@ For a dynamic version of the SBM see the [`StochasticBlockModel`](@ref) type and related functions. """ function stochastic_block_model(c::Matrix{T}, n::Vector{U}; seed::Int = -1) where T<:Real where U<:Integer - @assert size(c,1) == length(n) - @assert size(c,2) == length(n) + @assert size(c, 1) == length(n) + @assert size(c, 2) == length(n) # init dsfmt generator without altering GLOBAL_RNG rng = getRNG(seed) N = sum(n) K = length(n) - nedg = zeros(Int,K, K) + nedg = zeros(Int, K, K) g = Graph(N) - cum = [sum(n[1:a]) for a=0:K] - for a=1:K - ra = cum[a]+1:cum[a+1] - for b=a:K - @assert a==b? c[a,b] <= n[b]-1 : c[a,b] <= n[b] "Mean degree cannot be greater than available neighbors in the block." - - m = a==b ? div(n[a]*(n[a]-1),2) : n[a]*n[b] - p = a==b ? n[a]*c[a,b] / (2m) : n[a]*c[a,b]/m + cum = [sum(n[1:a]) for a = 0:K] + for a = 1:K + ra = (cum[a] + 1):cum[a + 1] + for b = a:K + @assert a == b ? c[a, b] <= n[b] - 1 : c[a, b] <= n[b] "Mean degree cannot be greater than available neighbors in the block." + + m = a == b ? div(n[a] * (n[a] - 1), 2) : n[a] * n[b] + p = a == b ? n[a] * c[a, b] / (2m) : n[a] * c[a, b] / m nedg = randbn(m, p, seed) - rb = cum[b]+1:cum[b+1] - i=0 + rb = (cum[b] + 1):cum[b + 1] + i = 0 while i < nedg source = rand(rng, ra) dest = rand(rng, rb) @@ -658,7 +657,7 @@ from an SBM with ``c_{a,a}=cint``, and ``c_{a,b}=cext``. """ function stochastic_block_model(cint::T, cext::T, n::Vector{U}; seed::Int=-1) where T<:Real where U<:Integer K = length(n) - c = [ifelse(a==b, cint, cext) for a=1:K,b=1:K] + c = [ifelse(a == b, cint, cext) for a = 1:K, b = 1:K] stochastic_block_model(c, n, seed=seed) end @@ -699,7 +698,7 @@ function StochasticBlockModel(sizes::AbstractVector, affinities::AbstractMatrix; nodemap = zeros(Int, csum[end]) for i in 1:csum[end] if i > csum[j] - j+=1 + j += 1 end nodemap[i] = j end @@ -717,7 +716,7 @@ and external probabilities `externalp`. function sbmaffinity(internalp::Vector{T}, externalp::Real, sizes::Vector{U}) where T<:Real where U<:Integer numblocks = length(sizes) numblocks == length(internalp) || error("Inconsistent input dimensions: internalp, sizes") - B = diagm(internalp) + externalp*(ones(numblocks, numblocks)-I) + B = diagm(internalp) + externalp * (ones(numblocks, numblocks) - I) return B end @@ -731,14 +730,14 @@ function StochasticBlockModel(internalp::Real, StochasticBlockModel(sizes, B, seed=seed) end -function StochasticBlockModel(internalp::Vector{T}, externalp::Real - , sizes::Vector{U}; seed::Int = -1) where T<:Real where U<:Integer +function StochasticBlockModel(internalp::Vector{T}, externalp::Real, + sizes::Vector{U}; seed::Int = -1) where T<:Real where U<:Integer B = sbmaffinity(internalp, externalp, sizes) return StochasticBlockModel(sizes, B, seed=seed) end -const biclique = ones(2,2) - eye(2) +const biclique = ones(2, 2) - eye(2) #TODO: this documentation needs work. sbromberger 20170326 @doc_str """ @@ -754,7 +753,7 @@ The blocks are connected with probability `between`. """ function nearbipartiteaffinity(sizes::Vector{T}, between::Real, intra::Real) where T<:Integer numblocks = div(length(sizes), 2) - return kron(between*eye(numblocks), biclique) + eye(2numblocks)*intra + return kron(between * eye(numblocks), biclique) + eye(2numblocks) * intra end #Return a generator for edges from a stochastic block model near-bipartite graph. @@ -795,9 +794,7 @@ function make_edgestream(sbm::StochasticBlockModel) edges(ch) = begin for e in pairs i, j = Tuple(e) - if i == j - continue - end + i == j && continue p = sbm.affinities[sbm.nodemap[i], sbm.nodemap[j]] if rand(sbm.rng) < p put!(ch, e) @@ -833,10 +830,10 @@ function blockcounts(sbm::StochasticBlockModel, A::AbstractMatrix) I = collect(1:sbm.n) J = [sbm.nodemap[i] for i in 1:sbm.n] V = ones(sbm.n) - Q = sparse(I,J,V) + Q = sparse(I, J, V) # Q = Q / Q'Q # @show Q'Q# < 1e-6 - return (Q'A)*(Q) + return (Q'A) * Q end @@ -844,7 +841,7 @@ function blockcounts(sbm::StochasticBlockModel, g::AbstractGraph) return blockcounts(sbm, adjacency_matrix(g)) end -function blockfractions(sbm::StochasticBlockModel, g::Union{AbstractGraph, AbstractMatrix}) +function blockfractions(sbm::StochasticBlockModel, g::Union{AbstractGraph,AbstractMatrix}) bc = blockcounts(sbm, g) bp = bc ./ sum(bc) return bp @@ -865,13 +862,13 @@ function kronecker(SCALE, edgefactor, A=0.57, B=0.19, C=0.19) M = edgefactor * N ij = ones(Int, M, 2) ab = A + B - c_norm = C/(1 - (A + B)) - a_norm = A/(A + B) + c_norm = C / (1 - (A + B)) + a_norm = A / (A + B) for ib = 1:SCALE - ii_bit = rand(M).>(ab) # bitarray - jj_bit = rand(M).> ( c_norm.*(ii_bit) + a_norm.*.!(ii_bit) ) - ij .+= 2^(ib-1).*(hcat(ii_bit, jj_bit)) + ii_bit = rand(M) .> (ab) # bitarray + jj_bit = rand(M) .> (c_norm .* (ii_bit) + a_norm .* .!(ii_bit)) + ij .+= 2^(ib - 1) .* (hcat(ii_bit, jj_bit)) end p = randperm(N) @@ -881,7 +878,7 @@ function kronecker(SCALE, edgefactor, A=0.57, B=0.19, C=0.19) ij = ij[p, :] g = DiGraph(N) - for (s,d) in zip(@view(ij[:,1]), @view(ij[:,2])) + for (s, d) in zip(@view(ij[:, 1]), @view(ij[:, 2])) add_edge!(g, s, d) end return g diff --git a/src/generators/smallgraphs.jl b/src/generators/smallgraphs.jl index d1865e2a6..e5b690e45 100644 --- a/src/generators/smallgraphs.jl +++ b/src/generators/smallgraphs.jl @@ -4,16 +4,16 @@ function _make_simple_undirected_graph(n::T, edgelist::Vector{Tuple{T,T}}) where T<:Integer g = Graph(n) - for (s,d) in edgelist - add_edge!(g, Edge(s,d)) + for (s, d) in edgelist + add_edge!(g, Edge(s, d)) end return g end function _make_simple_directed_graph(n::T, edgelist::Vector{Tuple{T,T}}) where T<:Integer g = DiGraph(n) - for (s,d) in edgelist - add_edge!(g, Edge(s,d)) + for (s, d) in edgelist + add_edge!(g, Edge(s, d)) end return g end @@ -92,11 +92,11 @@ end DiamondGraph() = -_make_simple_undirected_graph(4, [(1,2), (1,3), (2,3), (2,4), (3,4)]) +_make_simple_undirected_graph(4, [(1, 2), (1, 3), (2, 3), (2, 4), (3, 4)]) BullGraph() = -_make_simple_undirected_graph(5, [(1,2), (1,3), (2,3), (2,4), (3,5)]) +_make_simple_undirected_graph(5, [(1, 2), (1, 3), (2, 3), (2, 4), (3, 5)]) function ChvatalGraph() @@ -112,7 +112,7 @@ function ChvatalGraph() (9, 11), (10, 11), (10, 12) ] - return _make_simple_undirected_graph(12,e) + return _make_simple_undirected_graph(12, e) end @@ -125,7 +125,7 @@ function CubicalGraph() (6, 7), (7, 8) ] - return _make_simple_undirected_graph(8,e) + return _make_simple_undirected_graph(8, e) end @@ -151,7 +151,7 @@ function DesarguesGraph() (18, 19), (19, 20) ] - return _make_simple_undirected_graph(20,e) + return _make_simple_undirected_graph(20, e) end @@ -177,7 +177,7 @@ function DodecahedralGraph() (18, 19), (19, 20) ] - return _make_simple_undirected_graph(20,e) + return _make_simple_undirected_graph(20, e) end @@ -194,7 +194,7 @@ function FruchtGraph() (9, 10), (9, 12), (11, 12) ] - return _make_simple_undirected_graph(20,e) + return _make_simple_undirected_graph(20, e) end @@ -214,13 +214,13 @@ function HeawoodGraph() (12, 13), (13, 14) ] - return _make_simple_undirected_graph(14,e) + return _make_simple_undirected_graph(14, e) end function HouseGraph() - e = [ (1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (4, 5) ] - return _make_simple_undirected_graph(5,e) + e = [(1, 2), (1, 3), (2, 4), (3, 4), (3, 5), (4, 5)] + return _make_simple_undirected_graph(5, e) end @@ -260,7 +260,7 @@ function KrackhardtKiteGraph() (8, 9), (9, 10) ] - return _make_simple_undirected_graph(10,e) + return _make_simple_undirected_graph(10, e) end @@ -282,7 +282,7 @@ function MoebiusKantorGraph() (14, 15), (15, 16) ] - return _make_simple_undirected_graph(16,e) + return _make_simple_undirected_graph(16, e) end @@ -294,7 +294,7 @@ function OctahedralGraph() (4, 5), (4, 6), (5, 6) ] - return _make_simple_undirected_graph(6,e) + return _make_simple_undirected_graph(6, e) end @@ -318,7 +318,7 @@ function PappusGraph() (16, 17), (17, 18) ] - return _make_simple_undirected_graph(18,e) + return _make_simple_undirected_graph(18, e) end @@ -333,7 +333,7 @@ function PetersenGraph() (7, 9), (7, 10), (8, 10) ] - return _make_simple_undirected_graph(10,e) + return _make_simple_undirected_graph(10, e) end function SedgewickMazeGraph() @@ -345,7 +345,7 @@ function SedgewickMazeGraph() (4, 5), (4, 6), (5, 6), (5, 7), (5, 8) ] - return _make_simple_undirected_graph(8,e) + return _make_simple_undirected_graph(8, e) end @@ -378,88 +378,88 @@ function TruncatedCubeGraph() (22, 23), (23, 24) ] - return _make_simple_undirected_graph(24,e) + return _make_simple_undirected_graph(24, e) end function TruncatedTetrahedronGraph() e = [ - (1, 2),(1, 3),(1, 10), - (2, 3),(2, 7), + (1, 2), (1, 3), (1, 10), + (2, 3), (2, 7), (3, 4), - (4, 5),(4, 12), - (5, 6),(5, 12), - (6, 7),(6, 8), + (4, 5), (4, 12), + (5, 6), (5, 12), + (6, 7), (6, 8), (7, 8), (8, 9), - (9, 10),(9, 11), + (9, 10), (9, 11), (10, 11), (11, 12) ] - return _make_simple_undirected_graph(12,e) + return _make_simple_undirected_graph(12, e) end function TruncatedTetrahedronDiGraph() e = [ - (1, 2),(1, 3),(1, 10), - (2, 3),(2, 7), + (1, 2), (1, 3), (1, 10), + (2, 3), (2, 7), (3, 4), - (4, 5),(4, 12), - (5, 6),(5, 12), - (6, 7),(6, 8), + (4, 5), (4, 12), + (5, 6), (5, 12), + (6, 7), (6, 8), (7, 8), (8, 9), - (9, 10),(9, 11), + (9, 10), (9, 11), (10, 11), (11, 12) ] - return _make_simple_directed_graph(12,e) + return _make_simple_directed_graph(12, e) end function TutteGraph() e = [ - (1, 2),(1, 3),(1, 4), - (2, 5),(2, 27), - (3, 11),(3, 12), - (4, 19),(4, 20), - (5, 6),(5, 34), - (6, 7),(6, 30), - (7, 8),(7, 28), - (8, 9),(8, 15), - (9, 10),(9, 39), - (10, 11),(10, 38), + (1, 2), (1, 3), (1, 4), + (2, 5), (2, 27), + (3, 11), (3, 12), + (4, 19), (4, 20), + (5, 6), (5, 34), + (6, 7), (6, 30), + (7, 8), (7, 28), + (8, 9), (8, 15), + (9, 10), (9, 39), + (10, 11), (10, 38), (11, 40), - (12, 13),(12, 40), - (13, 14),(13, 36), - (14, 15),(14, 16), + (12, 13), (12, 40), + (13, 14), (13, 36), + (14, 15), (14, 16), (15, 35), - (16, 17),(16, 23), - (17, 18),(17, 45), - (18, 19),(18, 44), + (16, 17), (16, 23), + (17, 18), (17, 45), + (18, 19), (18, 44), (19, 46), - (20, 21),(20, 46), - (21, 22),(21, 42), - (22, 23),(22, 24), + (20, 21), (20, 46), + (21, 22), (21, 42), + (22, 23), (22, 24), (23, 41), - (24, 25),(24, 28), - (25, 26),(25, 33), - (26, 27),(26, 32), + (24, 25), (24, 28), + (25, 26), (25, 33), + (26, 27), (26, 32), (27, 34), (28, 29), - (29, 30),(29, 33), + (29, 30), (29, 33), (30, 31), - (31, 32),(31, 34), + (31, 32), (31, 34), (32, 33), - (35, 36),(35, 39), + (35, 36), (35, 39), (36, 37), - (37, 38),(37, 40), + (37, 38), (37, 40), (38, 39), - (41, 42),(41, 45), + (41, 42), (41, 45), (42, 43), - (43, 44),(43, 46), + (43, 44), (43, 46), (44, 45) ] - return _make_simple_undirected_graph(46,e) + return _make_simple_undirected_graph(46, e) end diff --git a/src/generators/staticgraphs.jl b/src/generators/staticgraphs.jl index 40bebcaf8..90cc0de7d 100644 --- a/src/generators/staticgraphs.jl +++ b/src/generators/staticgraphs.jl @@ -9,9 +9,9 @@ with `n` vertices. """ function CompleteGraph(n::Integer) g = Graph(n) - for i = 1:n, j=1:n + for i = 1:n, j = 1:n if i < j - add_edge!(g, Edge(i,j)) + add_edge!(g, Edge(i, j)) end end return g @@ -25,9 +25,9 @@ Create an undirected [complete bipartite graph](https://en.wikipedia.org/wiki/Co with `n1 + n2` vertices. """ function CompleteBipartiteGraph(n1::Integer, n2::Integer) - g = Graph(n1+n2) - for i = 1:n1, j=n1+1:n1+n2 - add_edge!(g, Edge(i,j)) + g = Graph(n1 + n2) + for i = 1:n1, j = (n1 + 1):(n1 + n2) + add_edge!(g, Edge(i, j)) end return g end @@ -40,9 +40,9 @@ with `n` vertices. """ function CompleteDiGraph(n::Integer) g = DiGraph(n) - for i = 1:n, j=1:n + for i = 1:n, j = 1:n if i != j - add_edge!(g, Edge(i,j)) + add_edge!(g, Edge(i, j)) end end return g @@ -57,7 +57,7 @@ with `n` vertices. function StarGraph(n::Integer) g = Graph(n) for i = 2:n - add_edge!(g, Edge(1,i)) + add_edge!(g, Edge(1, i)) end return g end @@ -71,7 +71,7 @@ with `n` vertices. function StarDiGraph(n::Integer) g = DiGraph(n) for i = 2:n - add_edge!(g, Edge(1,i)) + add_edge!(g, Edge(1, i)) end return g end @@ -85,7 +85,7 @@ with `n` vertices. function PathGraph(n::Integer) g = Graph(n) for i = 2:n - add_edge!(g, Edge(i-1, i)) + add_edge!(g, Edge(i - 1, i)) end return g end @@ -99,7 +99,7 @@ with `n` vertices. function PathDiGraph(n::Integer) g = DiGraph(n) for i = 2:n - add_edge!(g, Edge(i-1, i)) + add_edge!(g, Edge(i - 1, i)) end return g end @@ -112,8 +112,8 @@ with `n` vertices. """ function CycleGraph(n::Integer) g = Graph(n) - for i = 1:n-1 - add_edge!(g, Edge(i, i+1)) + for i = 1:(n - 1) + add_edge!(g, Edge(i, i + 1)) end add_edge!(g, Edge(n, 1)) return g @@ -127,8 +127,8 @@ with `n` vertices. """ function CycleDiGraph(n::Integer) g = DiGraph(n) - for i = 1:n-1 - add_edge!(g, Edge(i, i+1)) + for i = 1:(n - 1) + add_edge!(g, Edge(i, i + 1)) end add_edge!(g, Edge(n, 1)) return g @@ -144,7 +144,7 @@ with `n` vertices. function WheelGraph(n::Integer) g = StarGraph(n) for i = 3:n - add_edge!(g, Edge(i-1, i)) + add_edge!(g, Edge(i - 1, i)) end if n != 2 add_edge!(g, Edge(n, 2)) @@ -161,7 +161,7 @@ with `n` vertices. function WheelDiGraph(n::Integer) g = StarDiGraph(n) for i = 3:n - add_edge!(g, Edge(i-1, i)) + add_edge!(g, Edge(i - 1, i)) end if n != 2 add_edge!(g, Edge(n, 2)) @@ -202,11 +202,11 @@ of depth `k`. """ function BinaryTree(k::Integer) - g = Graph(Int(2^k-1)) - for i in 0:k-2 - for j in 2^i:2^(i+1)-1 + g = Graph(Int(2^k - 1)) + for i in 0:(k - 2) + for j in (2^i):(2^(i + 1) - 1) add_edge!(g, j, 2j) - add_edge!(g, j, 2j+1) + add_edge!(g, j, 2j + 1) end end return g @@ -224,7 +224,7 @@ function DoubleBinaryTree(k::Integer) gl = BinaryTree(k) gr = BinaryTree(k) g = blkdiag(gl, gr) - add_edge!(g,1, nv(gl)+1) + add_edge!(g, 1, nv(gl) + 1) return g end @@ -241,10 +241,10 @@ function RoachGraph(k::Integer) dipole = CompleteGraph(2) nopole = Graph(2) antannae = crosspath(k, nopole) - body = crosspath(k,dipole) + body = crosspath(k, dipole) roach = blkdiag(antannae, body) - add_edge!(roach, nv(antannae)-1, nv(antannae)+1) - add_edge!(roach, nv(antannae), nv(antannae)+2) + add_edge!(roach, nv(antannae) - 1, nv(antannae) + 1) + add_edge!(roach, nv(antannae), nv(antannae) + 2) return roach end @@ -255,15 +255,15 @@ end Create a graph consisting of `n` connected `k`-cliques. """ function CliqueGraph(k::Integer, n::Integer) - g = Graph(k*n) - for c=1:n - for i=(c-1)*k+1:c*k-1, j=i+1:c*k + g = Graph(k * n) + for c = 1:n + for i = ((c - 1) * k + 1):(c * k - 1), j = (i + 1):(c * k) add_edge!(g, i, j) end end - for i=1:n-1 - add_edge!(g, (i-1)*k+1, i*k+1) + for i = 1:(n - 1) + add_edge!(g, (i - 1) * k + 1, i * k + 1) end - add_edge!(g, 1, (n-1)*k+1) + add_edge!(g, 1, (n - 1) * k + 1) return g end diff --git a/src/graphtypes/simplegraphs/SimpleGraphs.jl b/src/graphtypes/simplegraphs/SimpleGraphs.jl index 36f1a9134..34c731b4b 100644 --- a/src/graphtypes/simplegraphs/SimpleGraphs.jl +++ b/src/graphtypes/simplegraphs/SimpleGraphs.jl @@ -61,8 +61,8 @@ add_edge!(g::AbstractSimpleGraph, x) = add_edge!(g, edgetype(g)(x)) has_edge(g::AbstractSimpleGraph, x, y) = has_edge(g, edgetype(g)(x, y)) add_edge!(g::AbstractSimpleGraph, x, y) = add_edge!(g, edgetype(g)(x, y)) -in_neighbors(g::AbstractSimpleGraph, v::Integer) = badj(g,v) -out_neighbors(g::AbstractSimpleGraph, v::Integer) = fadj(g,v) +in_neighbors(g::AbstractSimpleGraph, v::Integer) = badj(g, v) +out_neighbors(g::AbstractSimpleGraph, v::Integer) = fadj(g, v) function issubset(g::T, h::T) where T<:AbstractSimpleGraph (gmin, gmax) = extrema(vertices(g)) diff --git a/src/graphtypes/simplegraphs/simpledigraph.jl b/src/graphtypes/simplegraphs/simpledigraph.jl index 69a595ba8..069e8fdda 100644 --- a/src/graphtypes/simplegraphs/simpledigraph.jl +++ b/src/graphtypes/simplegraphs/simpledigraph.jl @@ -37,16 +37,16 @@ SimpleDiGraph(::Type{T}) where T<:Integer = SimpleDiGraph{T}(zero(T)) # sparse adjacency matrix constructor: DiGraph(adjmx) function (::Type{SimpleDiGraph{T}})(adjmx::SparseMatrixCSC{U}) where T<:Integer where U<:Real dima, dimb = size(adjmx) - isequal(dima,dimb) || error("Adjacency / distance matrices must be square") + isequal(dima, dimb) || error("Adjacency / distance matrices must be square") g = SimpleDiGraph(T(dima)) maxc = length(adjmx.colptr) - for c = 1:(maxc-1) - for rind = adjmx.colptr[c]:adjmx.colptr[c+1]-1 + for c = 1:(maxc - 1) + for rind = adjmx.colptr[c]:(adjmx.colptr[c + 1] - 1) isnz = (adjmx.nzval[rind] != zero(U)) if isnz r = adjmx.rowval[rind] - add_edge!(g,r,c) + add_edge!(g, r, c) end end end @@ -55,13 +55,13 @@ end # dense adjacency matrix constructor: DiGraph{UInt8}(adjmx) function (::Type{SimpleDiGraph{T}})(adjmx::AbstractMatrix) where T<:Integer - dima,dimb = size(adjmx) - isequal(dima,dimb) || error("Adjacency / distance matrices must be square") + dima, dimb = size(adjmx) + isequal(dima, dimb) || error("Adjacency / distance matrices must be square") g = SimpleDiGraph(T(dima)) for i in find(adjmx) - ind = ind2sub((dima,dimb),i) - add_edge!(g,ind...) + ind = ind2sub((dima, dimb), i) + add_edge!(g, ind...) end return g end @@ -120,7 +120,7 @@ end function rem_edge!(g::SimpleDiGraph, e::SimpleDiGraphEdge) - has_edge(g,e) || return false + has_edge(g, e) || return false i = searchsorted(g.fadjlist[src(e)], dst(e))[1] deleteat!(g.fadjlist[src(e)], i) i = searchsorted(g.badjlist[dst(e)], src(e))[1] @@ -143,9 +143,9 @@ end function has_edge(g::SimpleDiGraph, e::SimpleDiGraphEdge) u, v = Tuple(e) (u > nv(g) || v > nv(g)) && return false - if degree(g,u) < degree(g,v) - return length(searchsorted(fadj(g,u), v)) > 0 + if degree(g, u) < degree(g, v) + return length(searchsorted(fadj(g, u), v)) > 0 else - return length(searchsorted(badj(g,v), u)) > 0 + return length(searchsorted(badj(g, v), u)) > 0 end end diff --git a/src/graphtypes/simplegraphs/simpleedge.jl b/src/graphtypes/simplegraphs/simpleedge.jl index fd6f48aeb..489c58728 100644 --- a/src/graphtypes/simplegraphs/simpleedge.jl +++ b/src/graphtypes/simplegraphs/simpleedge.jl @@ -13,7 +13,7 @@ SimpleEdge(p::Pair) = SimpleEdge(p.first, p.second) SimpleEdge{T}(p::Pair) where T<:Integer = SimpleEdge(T(p.first), T(p.second)) SimpleEdge{T}(t::Tuple) where T<:Integer = SimpleEdge(T(t[1]), T(t[2])) -eltype(e::T) where T<:AbstractSimpleEdge= eltype(src(e)) +eltype(e::T) where T<:AbstractSimpleEdge = eltype(src(e)) # Accessors src(e::AbstractSimpleEdge) = e.src @@ -26,7 +26,7 @@ show(io::IO, e::AbstractSimpleEdge) = print(io, "Edge $(e.src) => $(e.dst)") Pair(e::AbstractSimpleEdge) = Pair(src(e), dst(e)) Tuple(e::AbstractSimpleEdge) = (src(e), dst(e)) -(::Type{SimpleEdge{T}}){T<:Integer}(e::AbstractSimpleEdge) = SimpleEdge{T}(T(e.src), T(e.dst)) +(::Type{SimpleEdge{T}})(e::AbstractSimpleEdge) where T <: Integer = SimpleEdge{T}(T(e.src), T(e.dst)) # Convenience functions reverse(e::T) where T<:AbstractSimpleEdge = T(dst(e), src(e)) diff --git a/src/graphtypes/simplegraphs/simpleedgeiter.jl b/src/graphtypes/simplegraphs/simpleedgeiter.jl index e7a2e3e23..77232b23a 100644 --- a/src/graphtypes/simplegraphs/simpleedgeiter.jl +++ b/src/graphtypes/simplegraphs/simpleedgeiter.jl @@ -18,7 +18,7 @@ SimpleEdgeIter(g::SimpleDiGraph) = SimpleEdgeIter(ne(g), g.fadjlist, true) function _next( eit::SimpleEdgeIter{T}, - state::SimpleEdgeIterState{T} = SimpleEdgeIterState(one(T),1,false), + state::SimpleEdgeIterState{T} = SimpleEdgeIterState(one(T), 1, false), first::Bool = true) where T <: Integer s = state.s di = state.di @@ -55,7 +55,7 @@ function _isequal(e1::SimpleEdgeIter, e2) s, d = Tuple(e) found = length(searchsorted(e1.adj[s], d)) > 0 if !e1.directed - found = found || length(searchsorted(e1.adj[d],s)) > 0 + found = found || length(searchsorted(e1.adj[d], s)) > 0 end !found && return false end diff --git a/src/graphtypes/simplegraphs/simplegraph.jl b/src/graphtypes/simplegraphs/simplegraph.jl index 684113934..e7420950a 100644 --- a/src/graphtypes/simplegraphs/simplegraph.jl +++ b/src/graphtypes/simplegraphs/simplegraph.jl @@ -34,14 +34,14 @@ SimpleGraph(::Type{T}) where T<:Integer = SimpleGraph{T}(zero(T)) # Graph{UInt8}(adjmx) function (::Type{SimpleGraph{T}})(adjmx::AbstractMatrix) where T<:Integer - dima,dimb = size(adjmx) - isequal(dima,dimb) || error("Adjacency / distance matrices must be square") + dima, dimb = size(adjmx) + isequal(dima, dimb) || error("Adjacency / distance matrices must be square") issymmetric(adjmx) || error("Adjacency / distance matrices must be symmetric") g = SimpleGraph(T(dima)) for i in find(triu(adjmx)) - ind = ind2sub((dima,dimb),i) - add_edge!(g,ind...) + ind = ind2sub((dima, dimb), i) + add_edge!(g, ind...) end return g end @@ -62,7 +62,7 @@ function SimpleGraph(g::SimpleDiGraph) edgect = 0 newfadj = deepcopy(g.fadjlist) for i in vertices(g) - for j in badj(g,i) + for j in badj(g, i) if (_insert_and_dedup!(newfadj[i], j)) edgect += 2 # this is a new edge only in badjlist else @@ -124,10 +124,10 @@ is_directed(g::SimpleGraph) = false function has_edge(g::SimpleGraph, e::SimpleGraphEdge) u, v = Tuple(e) (u > nv(g) || v > nv(g)) && return false - if degree(g,u) > degree(g,v) + if degree(g, u) > degree(g, v) u, v = v, u end - return length(searchsorted(fadj(g,u), v)) > 0 + return length(searchsorted(fadj(g, u), v)) > 0 end function add_edge!(g::SimpleGraph, e::SimpleGraphEdge) diff --git a/src/interface.jl b/src/interface.jl index c7f8f799e..94f339fd4 100644 --- a/src/interface.jl +++ b/src/interface.jl @@ -119,7 +119,7 @@ edges(g) = _NI("edges") Return true if the graph is a directed graph; false otherwise. """ is_directed(g) = _NI("is_directed") -is_directed{T}(::Type{T}) = _NI("is_directed") +is_directed(::Type{T}) where T = _NI("is_directed") """ add_vertex!(g) diff --git a/src/linalg/graphmatrices.jl b/src/linalg/graphmatrices.jl index cf24eb783..bd931f532 100644 --- a/src/linalg/graphmatrices.jl +++ b/src/linalg/graphmatrices.jl @@ -2,27 +2,27 @@ __precompile__(true) import Base: convert, sparse, size, diag, eltype, ndims, ==, *, .*, issymmetric, A_mul_B!, length, Diagonal -export convert, - SparseMatrix, - GraphMatrix, - Adjacency, - adjacency, - Laplacian, - CombinatorialAdjacency, - CombinatorialLaplacian, - NormalizedAdjacency, - NormalizedLaplacian, - StochasticAdjacency, - StochasticLaplacian, - AveragingAdjacency, - AveragingLaplacian, - PunchedAdjacency, - Noop, - diag, - degrees, - symmetrize, - prescalefactor, - postscalefactor +export convert, + SparseMatrix, + GraphMatrix, + Adjacency, + adjacency, + Laplacian, + CombinatorialAdjacency, + CombinatorialLaplacian, + NormalizedAdjacency, + NormalizedLaplacian, + StochasticAdjacency, + StochasticLaplacian, + AveragingAdjacency, + AveragingLaplacian, + PunchedAdjacency, + Noop, + diag, + degrees, + symmetrize, + prescalefactor, + postscalefactor @@ -63,8 +63,8 @@ struct CombinatorialAdjacency{T,S,V} <: Adjacency{T} end function CombinatorialAdjacency(A::SparseMatrix{T}) where T - D = vec(sum(A,1)) - return CombinatorialAdjacency{T,SparseMatrix{T},typeof(D)}(A,D) + D = vec(sum(A, 1)) + return CombinatorialAdjacency{T,SparseMatrix{T},typeof(D)}(A, D) end @@ -80,7 +80,7 @@ struct NormalizedAdjacency{T} <: Adjacency{T} scalefactor::Vector{T} end function NormalizedAdjacency(adjmat::CombinatorialAdjacency) - sf = adjmat.D.^(-1/2) + sf = adjmat.D.^(-1 / 2) return NormalizedAdjacency(adjmat, sf) end @@ -113,14 +113,14 @@ function AveragingAdjacency(adjmat::CombinatorialAdjacency) return AveragingAdjacency(adjmat, sf) end -perron(adjmat::NormalizedAdjacency) = sqrt.(adjmat.A.D)/norm(sqrt.(adjmat.A.D)) +perron(adjmat::NormalizedAdjacency) = sqrt.(adjmat.A.D) / norm(sqrt.(adjmat.A.D)) struct PunchedAdjacency{T} <: Adjacency{T} A::NormalizedAdjacency{T} perron::Vector{T} end function PunchedAdjacency(adjmat::CombinatorialAdjacency) - perron=sqrt.(adjmat.D)/norm(sqrt.(adjmat.D)) + perron = sqrt.(adjmat.D) / norm(sqrt.(adjmat.D)) return PunchedAdjacency(NormalizedAdjacency(adjmat), perron) end @@ -144,7 +144,7 @@ Diagonal(::Noop) = Noop() ==(g::GraphMatrix, h::GraphMatrix) = typeof(g) == typeof(h) && (g.A == h.A) -postscalefactor(::Adjacency)= Noop() +postscalefactor(::Adjacency) = Noop() postscalefactor(adjmat::NormalizedAdjacency) = adjmat.scalefactor @@ -256,16 +256,16 @@ diag(lapl::Laplacian) = ones(size(lapl)[2]) postscalefactor(adjmat) .* (adjmat.A * (prescalefactor(adjmat) .* x)) -*(adjmat::CombinatorialAdjacency{T}, x::AbstractVector{T}) where T<:Number= +*(adjmat::CombinatorialAdjacency{T}, x::AbstractVector{T}) where T<:Number = adjmat.A * x -*(lapl::Laplacian{T}, x::AbstractVector{T}) where T<:Number= - (diag(lapl) .* x) - (adjacency(lapl)*x) +*(lapl::Laplacian{T}, x::AbstractVector{T}) where T<:Number = + (diag(lapl) .* x) - (adjacency(lapl) * x) function *(adjmat::PunchedAdjacency{T}, x::AbstractVector{T}) where T<:Number - y=adjmat.A*x - return y - dot(adjmat.perron, y)*adjmat.perron + y = adjmat.A * x + return y - dot(adjmat.perron, y) * adjmat.perron end function A_mul_B!(Y, A::Adjacency, B) @@ -292,16 +292,16 @@ function A_mul_B!(Y, A::StochasticAdjacency, B) end function A_mul_B!(Y, adjmat::PunchedAdjacency, x) - y = adjmat.A*x - Y[:] = y - dot(adjmat.perron, y)*adjmat.perron + y = adjmat.A * x + Y[:] = y - dot(adjmat.perron, y) * adjmat.perron return Y end function A_mul_B!(Y, lapl::Laplacian, B) - A_mul_B!(Y, lapl.A, B) - z = diag(lapl) .* B - Y[:] = z - Y[:] - return Y + A_mul_B!(Y, lapl.A, B) + z = diag(lapl) .* B + Y[:] = z - Y[:] + return Y end @@ -312,23 +312,23 @@ Return a symmetric version of graph (represented by sparse matrix `A`) as a spar `which` may be one of `:triu`, `:tril`, `:sum`, or `:or`. Use `:sum` for weighted graphs. """ function symmetrize(A::SparseMatrix, which=:or) - if which==:or - M = A + A' - M.nzval[M.nzval .== 2] = 1 - return M + if which == :or + M = A + A' + M.nzval[M.nzval .== 2] = 1 + return M end - T = A - if which==:triu - T = triu(A) - elseif which==:tril - T = tril(A) - elseif which==:sum - T = A + T = A + if which == :triu + T = triu(A) + elseif which == :tril + T = tril(A) + elseif which == :sum + T = A else error("$which is not a supported method of symmetrizing a matrix") end - M = T + T' - return M + M = T + T' + return M end """ diff --git a/src/linalg/nonbacktracking.jl b/src/linalg/nonbacktracking.jl index 131b4c513..aede657a8 100644 --- a/src/linalg/nonbacktracking.jl +++ b/src/linalg/nonbacktracking.jl @@ -15,8 +15,8 @@ non-backtraking matrix ``B`` is defined as ``B_{A_{i j}, A_{k l}} = δ_{j k} * (1 - δ_{i l})`` """ function non_backtracking_matrix(g::AbstractGraph) - # idedgemap = Dict{Int, Edge}() - edgeidmap = Dict{Edge, Int}() + # idedgemap = Dict{Int,Edge}() + edgeidmap = Dict{Edge,Int}() m = 0 for e in edges(g) m += 1 @@ -32,9 +32,9 @@ function non_backtracking_matrix(g::AbstractGraph) B = zeros(Float64, m, m) - for (e,u) in edgeidmap + for (e, u) in edgeidmap i, j = src(e), dst(e) - for k in in_neighbors(g,i) + for k in in_neighbors(g, i) k == j && continue v = edgeidmap[Edge(k, i)] B[v, u] = 1 @@ -72,7 +72,7 @@ struct Nonbacktracking{G<:AbstractGraph} end function Nonbacktracking(g::AbstractGraph) - edgeidmap = Dict{Edge, Int}() + edgeidmap = Dict{Edge,Int}() m = 0 for e in edges(g) m += 1 @@ -87,16 +87,16 @@ function Nonbacktracking(g::AbstractGraph) return Nonbacktracking(g, edgeidmap, m) end -size(nbt::Nonbacktracking) = (nbt.m,nbt.m) +size(nbt::Nonbacktracking) = (nbt.m, nbt.m) eltype(nbt::Nonbacktracking) = Float64 issymmetric(nbt::Nonbacktracking) = false function *(nbt::Nonbacktracking, x::Vector{T}) where T<:Number length(x) == nbt.m || error("dimension mismatch") y = zeros(T, length(x)) - for (e,u) in nbt.edgeidmap + for (e, u) in nbt.edgeidmap i, j = src(e), dst(e) - for k in in_neighbors(nbt.g,i) + for k in in_neighbors(nbt.g, i) k == j && continue v = nbt.edgeidmap[Edge(k, i)] y[v] += x[u] @@ -105,9 +105,9 @@ function *(nbt::Nonbacktracking, x::Vector{T}) where T<:Number return y end function A_mul_B!(C, nbt::Nonbacktracking, B) - # computs C = A*B - for i in 1:size(B,2) - C[:,i] = nbt*B[:,i] + # computs C = A * B + for i in 1:size(B, 2) + C[:, i] = nbt * B[:, i] end return C end @@ -115,10 +115,10 @@ end function coo_sparse(nbt::Nonbacktracking) m = nbt.m #= I,J = zeros(Int, m), zeros(Int, m) =# - I,J = zeros(Int, 0), zeros(Int, 0) - for (e,u) in nbt.edgeidmap + I, J = zeros(Int, 0), zeros(Int, 0) + for (e, u) in nbt.edgeidmap i, j = src(e), dst(e) - for k in in_neighbors(nbt.g,i) + for k in in_neighbors(nbt.g, i) k == j && continue v = nbt.edgeidmap[Edge(k, i)] #= J[u] = v =# @@ -127,15 +127,15 @@ function coo_sparse(nbt::Nonbacktracking) push!(J, u) end end - return I,J,1.0 + return I, J, 1.0 end -sparse(nbt::Nonbacktracking) = sparse(coo_sparse(nbt)..., nbt.m,nbt.m) +sparse(nbt::Nonbacktracking) = sparse(coo_sparse(nbt)..., nbt.m, nbt.m) function *(nbt::Nonbacktracking, x::AbstractMatrix) y = zeros(x) for i in 1:nbt.m - y[:,i] = nbt * x[:,i] + y[:, i] = nbt * x[:, i] end return y end @@ -148,7 +148,7 @@ The mutating version of `contract(nbt, edgespace)`. Modifies `vertexspace`. function contract!(vertexspace::Vector, nbt::Nonbacktracking, edgespace::Vector) T = eltype(nbt.g) for i = one(T):nv(nbt.g), j in neighbors(nbt.g, i) - u = nbt.edgeidmap[i > j ? Edge(j,i) : Edge(i,j)] + u = nbt.edgeidmap[i > j ? Edge(j, i) : Edge(i, j)] vertexspace[i] += edgespace[u] end end @@ -161,6 +161,6 @@ Integrate out the edges by summing over the edges incident to each vertex. """ function contract(nbt::Nonbacktracking, edgespace::Vector) y = zeros(eltype(edgespace), nv(nbt.g)) - contract!(y,nbt,edgespace) + contract!(y, nbt, edgespace) return y end diff --git a/src/linalg/spectral.jl b/src/linalg/spectral.jl index 45d23cdc1..3e6ffd8c0 100644 --- a/src/linalg/spectral.jl +++ b/src/linalg/spectral.jl @@ -20,7 +20,7 @@ This function is optimized for speed and directly manipulates CSC sparse matrix """ function adjacency_matrix(g::AbstractGraph, dir::Symbol=:out, T::DataType=Int) n_v = nv(g) - nz = ne(g) * (is_directed(g)? 1 : 2) + nz = ne(g) * (is_directed(g) ? 1 : 2) colpt = ones(Int, n_v + 1) # see below - we iterate over columns. That's why we take the @@ -43,14 +43,14 @@ function adjacency_matrix(g::AbstractGraph, dir::Symbol=:out, T::DataType=Int) rowval = sizehint!(Vector{Int}(), nz) selfloops = Vector{Int}() for j in 1:n_v # this is by column, not by row. - if has_edge(g,j,j) + if has_edge(g, j, j) push!(selfloops, j) end dsts = neighborfn(g, j) - colpt[j+1] = colpt[j] + length(dsts) + colpt[j + 1] = colpt[j] + length(dsts) append!(rowval, sort!(dsts)) end - spmx = SparseMatrixCSC(n_v,n_v,colpt,rowval,ones(T,nz)) + spmx = SparseMatrixCSC(n_v, n_v, colpt, rowval, ones(T, nz)) # this is inefficient. There should be a better way of doing this. # the issue is that adjacency matrix entries for self-loops are 2, @@ -58,7 +58,7 @@ function adjacency_matrix(g::AbstractGraph, dir::Symbol=:out, T::DataType=Int) if !is_directed(g) for i in selfloops if !(T <: Bool) - spmx[i,i] += one(T) + spmx[i, i] += one(T) end end end @@ -77,10 +77,10 @@ defaults to `Int` for both graph types. """ function laplacian_matrix(g::AbstractGraph, dir::Symbol=:unspec, T::DataType=Int) if dir == :unspec - dir = is_directed(g)? :both : :out + dir = is_directed(g) ? :both : :out end A = adjacency_matrix(g, dir, T) - D = spdiagm(sum(A,2)[:]) + D = spdiagm(sum(A, 2)[:]) return D - A end @@ -114,7 +114,7 @@ eigenvalues/eigenvectors. """ function adjacency_spectrum(g::AbstractGraph, dir::Symbol=:unspec, T::DataType=Int) if dir == :unspec - dir = is_directed(g)? :both : :out + dir = is_directed(g) ? :both : :out end return eigvals(full(adjacency_matrix(g, dir, T))) end @@ -149,14 +149,14 @@ function incidence_matrix(g::AbstractGraph, T::DataType=Int; oriented=false) for u in vertices(g) for v in out_neighbors(g, u) if isdir || u < v # add every edge only once - rowval[2*i - 1] = u - rowval[2*i] = v + rowval[2 * i - 1] = u + rowval[2 * i] = v i += 1 end end end - spmx = SparseMatrixCSC(n_v,n_e,colpt,rowval,nzval) + spmx = SparseMatrixCSC(n_v, n_e, colpt, rowval, nzval) return spmx end @@ -177,8 +177,8 @@ function spectral_distance end A₁ = adjacency_matrix(G₁) A₂ = adjacency_matrix(G₂) - λ₁ = k < nv(G₁)-1 ? eigs(A₁, nev=k, which=:LR)[1] : eigvals(full(A₁))[end:-1:end-(k-1)] - λ₂ = k < nv(G₂)-1 ? eigs(A₂, nev=k, which=:LR)[1] : eigvals(full(A₂))[end:-1:end-(k-1)] + λ₁ = k < nv(G₁) - 1 ? eigs(A₁, nev=k, which=:LR)[1] : eigvals(full(A₁))[end:-1:(end - (k - 1))] + λ₂ = k < nv(G₂) - 1 ? eigs(A₂, nev=k, which=:LR)[1] : eigvals(full(A₂))[end:-1:(end - (k - 1))] return sum(abs, (λ₁ - λ₂)) end diff --git a/src/operators.jl b/src/operators.jl index 2936426cc..e31407306 100644 --- a/src/operators.jl +++ b/src/operators.jl @@ -10,10 +10,10 @@ Preserves the eltype of the input graph. function complement(g::Graph) gnv = nv(g) h = Graph(gnv) - for i=1:gnv - for j=i+1:gnv + for i = 1:gnv + for j = (i + 1):gnv if !has_edge(g, i, j) - add_edge!(h,i,j) + add_edge!(h, i, j) end end end @@ -24,8 +24,8 @@ function complement(g::DiGraph) gnv = nv(g) h = DiGraph(gnv) for i in vertices(g), j in vertices(g) - if i != j && !has_edge(g,i,j) - add_edge!(h,i,j) + if i != j && !has_edge(g, i, j) + add_edge!(h, i, j) end end return h @@ -79,7 +79,7 @@ function blkdiag(g::T, h::T) where T<:AbstractGraph add_edge!(r, e) end for e in edges(h) - add_edge!(r, gnv+src(e), gnv+dst(e)) + add_edge!(r, gnv + src(e), gnv + dst(e)) end return r end @@ -98,8 +98,8 @@ function intersect(g::T, h::T) where T<:AbstractGraph hnv = nv(h) r = T(min(gnv, hnv)) - for e in intersect(edges(g),edges(h)) - add_edge!(r,e) + for e in intersect(edges(g), edges(h)) + add_edge!(r, e) end return r end @@ -119,7 +119,7 @@ function difference(g::T, h::T) where T<:AbstractGraph r = T(gnv) for e in edges(g) - !has_edge(h, e) && add_edge!(r,e) + !has_edge(h, e) && add_edge!(r, e) end return r end @@ -191,7 +191,7 @@ in the generated graph exceeds the eltype. function join(g::T, h::T) where T<:AbstractGraph r = blkdiag(g, h) for i in vertices(g) - for j=nv(g)+1:nv(g)+nv(h) + for j = (nv(g) + 1):(nv(g) + nv(h)) add_edge!(r, i, j) end end @@ -262,7 +262,7 @@ size(g::AbstractGraph) = (nv(g), nv(g)) Return the number of vertices in `g` if `i`=1 or `i`=2, or `1` otherwise. """ -size(g::Graph,dim::Int) = (dim == 1 || dim == 2)? nv(g) : 1 +size(g::Graph, dim::Int) = (dim == 1 || dim == 2) ? nv(g) : 1 """ sum(g) @@ -280,7 +280,7 @@ sparse(g::AbstractGraph) = adjacency_matrix(g) #arrayfunctions = (:eltype, :length, :ndims, :size, :strides, :issymmetric) # eltype(g::AbstractGraph) = Float64 -length(g::AbstractGraph) = nv(g)*nv(g) +length(g::AbstractGraph) = nv(g) * nv(g) ndims(g::AbstractGraph) = 2 issymmetric(g::AbstractGraph) = !is_directed(g) @@ -295,19 +295,19 @@ Preserves the eltype of the input graph. Will error if the number of vertices in the generated graph exceeds the eltype. """ function cartesian_product(g::G, h::G) where G<:AbstractGraph - z = G(nv(g)*nv(h)) - id(i, j) = (i-1)*nv(h) + j + z = G(nv(g) * nv(h)) + id(i, j) = (i - 1) * nv(h) + j for e in edges(g) i1, i2 = Tuple(e) - for j=1:nv(h) - add_edge!(z, id(i1,j), id(i2,j)) + for j = 1:nv(h) + add_edge!(z, id(i1, j), id(i2, j)) end end for e in edges(h) j1, j2 = Tuple(e) for i in vertices(g) - add_edge!(z, id(i,j1), id(i,j2)) + add_edge!(z, id(i, j1), id(i, j2)) end end return z @@ -324,8 +324,8 @@ Preserves the eltype of the input graph. Will error if the number of vertices in the generated graph exceeds the eltype. """ function tensor_product(g::G, h::G) where G<:AbstractGraph - z = G(nv(g)*nv(h)) - id(i, j) = (i-1)*nv(h) + j + z = G(nv(g) * nv(h)) + id(i, j) = (i - 1) * nv(h) + j for e1 in edges(g) i1, i2 = Tuple(e1) for e2 in edges(h) @@ -379,9 +379,9 @@ julia> @assert sg == g[elist] function induced_subgraph(g::T, vlist::AbstractVector{U}) where T<:AbstractGraph where U<:Integer allunique(vlist) || error("Vertices in subgraph list must be unique") h = T(length(vlist)) - newvid = Dict{U, U}() - vmap =Vector{U}(length(vlist)) - for (i,v) in enumerate(vlist) + newvid = Dict{U,U}() + vmap = Vector{U}(length(vlist)) + for (i, v) in enumerate(vlist) newvid[v] = U(i) vmap[i] = v end @@ -403,12 +403,12 @@ end function induced_subgraph(g::T, elist::AbstractVector{U}) where T<:AbstractGraph where U<:AbstractEdge h = zero(g) et = eltype(h) - newvid = Dict{et, et}() + newvid = Dict{et,et}() vmap = Vector{et}() for e in elist u, v = Tuple(e) - for i in (u,v) + for i in (u, v) if !haskey(newvid, i) add_vertex!(h) newvid[i] = nv(h) diff --git a/src/persistence/common.jl b/src/persistence/common.jl index 184264b37..7214b75a8 100644 --- a/src/persistence/common.jl +++ b/src/persistence/common.jl @@ -11,7 +11,7 @@ multiple graphs; if the file format does not support multiple graphs, this value is ignored. The default value may change in the future. """ function loadgraph(fn::AbstractString, gname::AbstractString, format::AbstractGraphFormat) - GZip.open(fn,"r") do io + GZip.open(fn, "r") do io loadgraph(io, gname, format) end end @@ -73,9 +73,9 @@ Return the number of graphs written. ### Implementation Notes Will only work if the file format supports multiple graph types. """ -function savegraph(fn::AbstractString, d::Dict{T, U}, +function savegraph(fn::AbstractString, d::Dict{T,U}, format::AbstractGraphFormat; compress=true) where T<:AbstractString where U<:AbstractGraph - openfn = compress? GZip.open : open + openfn = compress ? GZip.open : open retval = -1 openfn(fn, "w") do io retval = savegraph(io, d, format) diff --git a/src/persistence/lg.jl b/src/persistence/lg.jl index 9a11fc93b..dcdf0b956 100644 --- a/src/persistence/lg.jl +++ b/src/persistence/lg.jl @@ -22,7 +22,7 @@ function _lg_read_one_graph(f::IO, n_v::Integer, n_e::Integer, directed::Bool) for i = 1:n_e line = chomp(readline(f)) if length(line) > 0 - src_s, dst_s = split(line,r"\s*,\s*") + src_s, dst_s = split(line, r"\s*,\s*") src = parse(Int, src_s) dst = parse(Int, dst_s) add_edge!(g, src, dst) @@ -43,10 +43,10 @@ end Return a dictionary of (name=>graph) loaded from IO stream `io`. """ function loadlg_mult(io::IO) - graphs = Dict{String, AbstractGraph}() + graphs = Dict{String,AbstractGraph}() while !eof(io) line = strip(chomp(readline(io))) - if startswith(line,"#") || line == "" + if startswith(line, "#") || line == "" next else nvstr, nestr, dirundir, graphname = split(line, r"s*,s*", limit=4) @@ -66,7 +66,7 @@ end function loadlg(io::IO, gname::String) while !eof(io) line = strip(chomp(readline(io))) - (startswith(line,"#") || line == "") && continue + (startswith(line, "#") || line == "") && continue nvstr, nestr, dirundir, graphname = split(line, r"s*,s*", limit=4) n_v = parse(Int, nvstr) n_e = parse(Int, nestr) @@ -90,7 +90,7 @@ to the IO stream designated by `io`. Return 1 (number of graphs written). """ function savelg(io::IO, g::AbstractGraph, gname::String) # write header line - dir = is_directed(g)? "d" : "u" + dir = is_directed(g) ? "d" : "u" line = join([nv(g), ne(g), dir, gname], ",") write(io, "$line\n") # write edges diff --git a/src/shortestpaths/astar.jl b/src/shortestpaths/astar.jl index a829e9b03..950ca9025 100644 --- a/src/shortestpaths/astar.jl +++ b/src/shortestpaths/astar.jl @@ -23,7 +23,7 @@ function a_star_impl!( if colormap[v] < 2 dist = distmx[u, v] colormap[v] = 1 - new_path = cat(1, path, Edge(u,v)) + new_path = cat(1, path, Edge(u, v)) path_cost = cost_so_far + dist enqueue!(frontier, (path_cost, new_path, v), @@ -54,7 +54,7 @@ function a_star( ) where T # heuristic (under)estimating distance to target U = eltype(g) - frontier = PriorityQueue(Tuple{T,Vector{Edge},U},T) + frontier = PriorityQueue(Tuple{T,Vector{Edge},U}, T) frontier[(zero(T), Vector{Edge}(), s)] = zero(T) colormap = zeros(Int, nv(g)) colormap[s] = 1 diff --git a/src/shortestpaths/bellman-ford.jl b/src/shortestpaths/bellman-ford.jl index 4bb0139ad..82997cc08 100644 --- a/src/shortestpaths/bellman-ford.jl +++ b/src/shortestpaths/bellman-ford.jl @@ -17,7 +17,7 @@ struct NegativeCycleError <: Exception end An `AbstractPathState` designed for Bellman-Ford shortest-paths calculations. """ -struct BellmanFordState{T<:Number, U<:Integer}<:AbstractPathState +struct BellmanFordState{T<:Number,U<:Integer} <: AbstractPathState parents::Vector{U} dists::Vector{T} end @@ -70,10 +70,10 @@ Return a [`BellmanFordState`](@ref) with relevant traversal information. function bellman_ford_shortest_paths( graph::AbstractGraph, sources::AbstractVector{U}, - distmx::AbstractMatrix{T} = weights(g) + distmx::AbstractMatrix{T} = weights(graph) ) where T where U<:Integer nvg = nv(graph) - state = BellmanFordState(zeros(U,nvg), fill(typemax(T), nvg)) + state = BellmanFordState(zeros(U, nvg), fill(typemax(T), nvg)) bellman_ford_shortest_paths!(graph, sources, distmx, state) end @@ -99,7 +99,7 @@ function enumerate_paths(state::AbstractPathState, vs::Vector{T}) where T<:Integ num_vs = length(vs) all_paths = Vector{Vector{T}}(num_vs) - for i=1:num_vs + for i = 1:num_vs all_paths[i] = Vector{T}() index = vs[i] if parents[index] != 0 || parents[index] == index diff --git a/src/shortestpaths/dijkstra.jl b/src/shortestpaths/dijkstra.jl index 4d8c1e9e2..61a18addb 100644 --- a/src/shortestpaths/dijkstra.jl +++ b/src/shortestpaths/dijkstra.jl @@ -1,4 +1,4 @@ -struct DijkstraHeapEntry{T, U<:Integer} +struct DijkstraHeapEntry{T,U<:Integer} vertex::U dist::T end @@ -10,7 +10,7 @@ isless(e1::DijkstraHeapEntry, e2::DijkstraHeapEntry) = e1.dist < e2.dist An [`AbstractPathState`](@ref) designed for Dijkstra shortest-paths calculations. """ -struct DijkstraState{T, U<:Integer}<: AbstractPathState +struct DijkstraState{T,U<:Integer} <: AbstractPathState parents::Vector{U} dists::Vector{T} predecessors::Vector{Vector{U}} @@ -40,10 +40,10 @@ function dijkstra_shortest_paths( nvg = nv(g) dists = fill(typemax(T), nvg) parents = zeros(U, nvg) - preds = fill(Vector{U}(),nvg) + preds = fill(Vector{U}(), nvg) visited = zeros(Bool, nvg) pathcounts = zeros(Int, nvg) - H = Vector{DijkstraHeapEntry{T, U}}() # this should be Vector{T}() in 0.4, I think. + H = Vector{DijkstraHeapEntry{T,U}}() # this should be Vector{T}() in 0.4, I think. dists[srcs] = zero(T) pathcounts[srcs] = 1 closest_vertices = Vector{U}() # Maintains vertices in order of distances from source @@ -52,7 +52,7 @@ function dijkstra_shortest_paths( sizehint!(closest_vertices, nvg) for v in srcs - heappush!(H, DijkstraHeapEntry{T, U}(v, dists[v])) + heappush!(H, DijkstraHeapEntry{T,U}(v, dists[v])) visited[v] = true end @@ -65,8 +65,8 @@ function dijkstra_shortest_paths( push!(closest_vertices, u) end - for v in out_neighbors(g,u) - alt = (dists[u] == typemax(T))? typemax(T) : dists[u] + distmx[u,v] + for v in out_neighbors(g, u) + alt = (dists[u] == typemax(T)) ? typemax(T) : dists[u] + distmx[u, v] if !visited[v] dists[v] = alt @@ -76,7 +76,7 @@ function dijkstra_shortest_paths( if allpaths preds[v] = [u;] end - heappush!(H, DijkstraHeapEntry{T, U}(v, alt)) + heappush!(H, DijkstraHeapEntry{T,U}(v, alt)) # info("Pushed $v") else if alt < dists[v] @@ -85,7 +85,7 @@ function dijkstra_shortest_paths( #615 pathcounts[v] = 0 preds[v] = [] - heappush!(H, DijkstraHeapEntry{T, U}(v, alt)) + heappush!(H, DijkstraHeapEntry{T,U}(v, alt)) end if alt == dists[v] pathcounts[v] += pathcounts[u] @@ -100,7 +100,7 @@ function dijkstra_shortest_paths( if trackvertices for s in vertices(g) if !visited[s] - push!(closest_vertices,s) + push!(closest_vertices, s) end end end @@ -111,7 +111,7 @@ function dijkstra_shortest_paths( preds[src] = [] end - return DijkstraState{T, U}(parents, dists, preds, pathcounts, closest_vertices) + return DijkstraState{T,U}(parents, dists, preds, pathcounts, closest_vertices) end dijkstra_shortest_paths(g::AbstractGraph, src::Integer, distmx::AbstractMatrix = weights(g); allpaths=false, trackvertices=false) = @@ -122,7 +122,7 @@ dijkstra_shortest_paths(g, [src;], distmx; allpaths=allpaths, trackvertices=trac An [`AbstractPathState`](@ref) designed for multisource_dijkstra_shortest_paths calculation. """ -struct MultipleDijkstraState{T, U<:Integer}<:AbstractPathState +struct MultipleDijkstraState{T,U<:Integer} <: AbstractPathState dists::Matrix{T} parents::Matrix{U} end @@ -136,25 +136,25 @@ an optional distance matrix `distmx`. Return a [`MultipleDijkstraState`](@ref) w traversal information. """ -function parallel_multisource_dijkstra_shortest_paths{T}( +function parallel_multisource_dijkstra_shortest_paths( g::AbstractGraph, sources::AbstractVector = vertices(g), distmx::AbstractMatrix{T} = weights(g) - ) + ) where T U = eltype(g) n_v = nv(g) r_v = length(sources) - dists = SharedArray(zeros(T,r_v,n_v)) - parents = SharedArray(zeros(U,r_v,n_v)) + dists = SharedArray(zeros(T, r_v, n_v)) + parents = SharedArray(zeros(U, r_v, n_v)) @sync @parallel for i in 1:r_v - state = dijkstra_shortest_paths(g,sources[i],distmx) - dists[i,:] = state.dists - parents[i,:] = state.parents + state = dijkstra_shortest_paths(g, sources[i], distmx) + dists[i, :] = state.dists + parents[i, :] = state.parents end - result = MultipleDijkstraState(Matrix(dists),Matrix(parents)) + result = MultipleDijkstraState(Matrix(dists), Matrix(parents)) return result end diff --git a/src/shortestpaths/floyd-warshall.jl b/src/shortestpaths/floyd-warshall.jl index 9730bd1c7..8d735212d 100644 --- a/src/shortestpaths/floyd-warshall.jl +++ b/src/shortestpaths/floyd-warshall.jl @@ -7,7 +7,7 @@ An [`AbstractPathState`](@ref) designed for Floyd-Warshall shortest-paths calculations. """ -struct FloydWarshallState{T, U<:Integer}<:AbstractPathState +struct FloydWarshallState{T,U<:Integer} <: AbstractPathState dists::Matrix{T} parents::Matrix{U} end @@ -22,59 +22,59 @@ traversal information. ### Performance Space complexity is on the order of ``\\mathcal{O}(|V|^2)``. """ -function floyd_warshall_shortest_paths{T}( +function floyd_warshall_shortest_paths( g::AbstractGraph, distmx::AbstractMatrix{T} = weights(g) -) +) where T U = eltype(g) n_v = nv(g) - dists = fill(typemax(T), (Int(n_v),Int(n_v))) - parents = zeros(U, (Int(n_v),Int(n_v))) + dists = fill(typemax(T), (Int(n_v), Int(n_v))) + parents = zeros(U, (Int(n_v), Int(n_v))) # fws = FloydWarshallState(Matrix{T}(), Matrix{Int}()) for v in 1:n_v - dists[v,v] = zero(T) + dists[v, v] = zero(T) end undirected = !is_directed(g) for e in edges(g) u = src(e) v = dst(e) - d = distmx[u,v] + d = distmx[u, v] - dists[u,v] = min(d, dists[u,v]) - parents[u,v] = u + dists[u, v] = min(d, dists[u, v]) + parents[u, v] = u if undirected - dists[v,u] = min(d, dists[v,u]) - parents[v,u] = v + dists[v, u] = min(d, dists[v, u]) + parents[v, u] = v end end for w in vertices(g), u in vertices(g), v in vertices(g) - if dists[u,w] == typemax(T) || dists[w,v] == typemax(T) + if dists[u, w] == typemax(T) || dists[w, v] == typemax(T) ans = typemax(T) else - ans = dists[u,w] + dists[w,v] + ans = dists[u, w] + dists[w, v] end - if dists[u,v] > ans - dists[u,v] = dists[u,w] + dists[w,v] - parents[u,v] = parents[w,v] + if dists[u, v] > ans + dists[u, v] = dists[u, w] + dists[w, v] + parents[u, v] = parents[w, v] end end fws = FloydWarshallState(dists, parents) return fws end -function enumerate_paths(s::FloydWarshallState{T, U}, v::Integer) where T where U<:Integer - pathinfo = s.parents[v,:] +function enumerate_paths(s::FloydWarshallState{T,U}, v::Integer) where T where U<:Integer + pathinfo = s.parents[v, :] paths = Vector{Vector{U}}() for i in 1:length(pathinfo) - if (i == v) || (s.dists[v,i] == typemax(T)) + if (i == v) || (s.dists[v, i] == typemax(T)) push!(paths, Vector{U}()) else path = Vector{U}() currpathindex = i while currpathindex != 0 - push!(path,currpathindex) + push!(path, currpathindex) currpathindex = pathinfo[currpathindex] end push!(paths, reverse(path)) @@ -83,5 +83,5 @@ function enumerate_paths(s::FloydWarshallState{T, U}, v::Integer) where T where return paths end -enumerate_paths(s::FloydWarshallState) = [enumerate_paths(s, v) for v in 1:size(s.parents,1)] +enumerate_paths(s::FloydWarshallState) = [enumerate_paths(s, v) for v in 1:size(s.parents, 1)] enumerate_paths(st::FloydWarshallState, s::Integer, d::Integer) = enumerate_paths(st, s)[d] diff --git a/src/shortestpaths/yen.jl b/src/shortestpaths/yen.jl index 5cb367178..a5241ba4b 100644 --- a/src/shortestpaths/yen.jl +++ b/src/shortestpaths/yen.jl @@ -3,7 +3,7 @@ Designed for yen k-shortest-paths calculations. """ -struct YenState{T, U<:Integer}<: AbstractPathState +struct YenState{T,U<:Integer} <: AbstractPathState dists::Vector{T} paths::Vector{Vector{U}} end @@ -22,15 +22,15 @@ function yen_k_shortest_paths( target::U, distmx::AbstractMatrix{T}=weights(g), K::Int=1; - maxdist=Inf) where T <: Real where U<:Integer + maxdist=Inf) where T <: Real where U <: Integer - source == target && return YenState{T, U}([U(0)], [[source]]) + source == target && return YenState{T,U}([U(0)], [[source]]) dj = dijkstra_shortest_paths(g, source, distmx) path = enumerate_paths(dj)[target] - isempty(path) && return YenState{T, U}(Vector{T}(), Vector{Vector{U}}()) + isempty(path) && return YenState{T,U}(Vector{T}(), Vector{Vector{U}}()) - dists = Array{T, 1}() + dists = Array{T,1}() push!(dists, dj.dists[target]) A = [path] B = PriorityQueue() @@ -44,7 +44,7 @@ function yen_k_shortest_paths( rootpath = A[k][1:j] # Store the removed edges - edgesremoved = Array{Tuple{Int, Int}, 1}() + edgesremoved = Array{Tuple{Int,Int},1}() # Remove the links of the previous shortest paths which share the same root path for ppath in A if length(ppath) > j && rootpath == ppath[1:j] @@ -52,7 +52,7 @@ function yen_k_shortest_paths( v = ppath[j + 1] if has_edge(gcopy, u, v) rem_edge!(gcopy, u, v) - push!(edgesremoved,(u, v)) + push!(edgesremoved, (u, v)) end end end @@ -64,7 +64,7 @@ function yen_k_shortest_paths( nei = copy(neighbors(gcopy, u)) for v in nei rem_edge!(gcopy, u, v) - push!(edgesremoved,(u, v)) + push!(edgesremoved, (u, v)) end # Evaluate distante of root path @@ -77,7 +77,7 @@ function yen_k_shortest_paths( spurpath = enumerate_paths(djspur)[target] if !isempty(spurpath) # Entire path is made up of the root path and spur path - pathtotal = [rootpath[1:end-1];spurpath] + pathtotal = [rootpath[1:(end - 1)]; spurpath] distpath = distrootpath + djspur.dists[target] # Add the potential k-shortest path to the heap if !haskey(B, pathtotal) @@ -95,9 +95,9 @@ function yen_k_shortest_paths( mindistB = DataStructures.peek(B)[2] # The path with minimum distance in B is higher than maxdist mindistB > maxdist && break - push!(dists,DataStructures.peek(B)[2]) - push!(A,dequeue!(B)) + push!(dists, DataStructures.peek(B)[2]) + push!(A, dequeue!(B)) end - return YenState{T, U}(dists, A) + return YenState{T,U}(dists, A) end diff --git a/src/traversals/bfs.jl b/src/traversals/bfs.jl index 993da376b..c6d2256b9 100644 --- a/src/traversals/bfs.jl +++ b/src/traversals/bfs.jl @@ -40,7 +40,7 @@ function breadth_first_visit_impl!( for v in fneig(g, u) v_color = get(vertexcolormap, v, 0) - v_edge = Edge(u,v) + v_edge = Edge(u, v) e_color = get(edgecolormap, v_edge, 0) examine_neighbor!(visitor, u, v, u_color, v_color, e_color) || return edgecolormap[v_edge] = 1 @@ -60,7 +60,7 @@ function traverse_graph!( alg::BreadthFirst, source, visitor::AbstractGraphVisitor; - vertexcolormap::AbstractVertexMap = Dict{eltype(g), Int}(), + vertexcolormap::AbstractVertexMap = Dict{eltype(g),Int}(), edgecolormap::AbstractEdgeMap = DummyEdgeMap(), queue = Vector{eltype(g)}(), dir = :out) @@ -71,8 +71,7 @@ function traverse_graph!( push!(queue, s) end - breadth_first_visit_impl!(g, queue, vertexcolormap, edgecolormap - , visitor, dir) + breadth_first_visit_impl!(g, queue, vertexcolormap, edgecolormap, visitor, dir) end @@ -191,7 +190,7 @@ mutable struct BipartiteVisitor <: AbstractGraphVisitor is_bipartite::Bool end -BipartiteVisitor(n::Integer) = BipartiteVisitor(zeros(UInt8,n), true) +BipartiteVisitor(n::Integer) = BipartiteVisitor(zeros(UInt8, n), true) function examine_neighbor!(visitor::BipartiteVisitor, u::Integer, v::Integer, ucolor::Int, vcolor::Int, ecolor::Int) @@ -214,13 +213,13 @@ If a node `v` is specified, only the connected component to which it belongs is function is_bipartite(g::AbstractGraph) T = eltype(g) if !is_directed(g) - cc = filter(x->length(x)>2, connected_components(g)) + cc = filter(x -> length(x) > 2, connected_components(g)) else - cc = filter(x->length(x)>2, weakly_connected_components(g)) + cc = filter(x -> length(x) > 2, weakly_connected_components(g)) end vmap = Dict{T,Int}() for c in cc - _is_bipartite(g,c[1], vmap=vmap) || return false + _is_bipartite(g, c[1], vmap=vmap) || return false end return true end @@ -252,7 +251,7 @@ function bipartite_map(g::AbstractGraph) !all([v.is_bipartite for v in visitors]) && return zeros(Int, 0) m = zeros(Int, nv(g)) for i in vertices(g) - m[i] = any(v->v.bipartitemap[i] == 1, visitors) ? 2 : 1 + m[i] = any(v -> v.bipartitemap[i] == 1, visitors) ? 2 : 1 end m end diff --git a/src/traversals/dfs.jl b/src/traversals/dfs.jl index e6c898da2..303f674f6 100644 --- a/src/traversals/dfs.jl +++ b/src/traversals/dfs.jl @@ -39,7 +39,7 @@ function depth_first_visit_impl!( v, tstate = next(udsts, tstate) u_color = get(vertexcolormap, u, 0) v_color = get(vertexcolormap, v, 0) - v_edge = Edge(u,v) + v_edge = Edge(u, v) e_color = get(edgecolormap, v_edge, 0) examine_neighbor!(visitor, u, v, u_color, v_color, e_color) #no return here @@ -69,7 +69,7 @@ function traverse_graph!( alg::DepthFirst, s::Integer, visitor::AbstractGraphVisitor; - vertexcolormap = Dict{eltype(g), Int}(), + vertexcolormap = Dict{eltype(g),Int}(), edgecolormap = DummyEdgeMap()) T = eltype(g) @@ -174,7 +174,7 @@ mutable struct TreeDFSVisitor{T} <:AbstractGraphVisitor predecessor::Vector{T} end -TreeDFSVisitor(n::T) where T<:Integer = TreeDFSVisitor(DiGraph(n), zeros(T,n)) +TreeDFSVisitor(n::T) where T<:Integer = TreeDFSVisitor(DiGraph(n), zeros(T, n)) function examine_neighbor!(visitor::TreeDFSVisitor, u::Integer, v::Integer, ucolor::Int, vcolor::Int, ecolor::Int) if (vcolor == 0) diff --git a/src/traversals/graphvisit.jl b/src/traversals/graphvisit.jl index 17f1c120a..81cf1a3cd 100644 --- a/src/traversals/graphvisit.jl +++ b/src/traversals/graphvisit.jl @@ -29,7 +29,7 @@ end abstract type AbstractGraphVisitAlgorithm end const AbstractEdgeMap{T} = Associative{Edge,T} -const AbstractVertexMap{T<:Integer, U} = Union{AbstractVector{T},Associative{T, U}} +const AbstractVertexMap{T<:Integer,U} = Union{AbstractVector{T},Associative{T,U}} struct DummyEdgeMap <: AbstractEdgeMap{Int} end diff --git a/src/traversals/maxadjvisit.jl b/src/traversals/maxadjvisit.jl index 6737afff9..634023b84 100644 --- a/src/traversals/maxadjvisit.jl +++ b/src/traversals/maxadjvisit.jl @@ -15,11 +15,11 @@ end abstract type AbstractMASVisitor <: AbstractGraphVisitor end -function maximum_adjacency_visit_impl!{T}( - g::AbstractGraph, # the graph - pq::DataStructures.PriorityQueue{Int, T}, # priority queue - visitor::AbstractMASVisitor, # the visitor - colormap::Vector{Int}) # traversal status +function maximum_adjacency_visit_impl!( + g::AbstractGraph, # the graph + pq::DataStructures.PriorityQueue{Int,T}, # priority queue + visitor::AbstractMASVisitor, # the visitor + colormap::Vector{Int}) where T # traversal status while !isempty(pq) u = DataStructures.dequeue!(pq) @@ -27,7 +27,7 @@ function maximum_adjacency_visit_impl!{T}( for v in out_neighbors(g, u) examine_neighbor!(visitor, u, v, 0, 0, 0) - if haskey(pq,v) + if haskey(pq, v) ed = visitor.distmx[u, v] pq[v] += ed end @@ -46,14 +46,14 @@ function traverse_graph!( colormap::Vector{Int}) - pq = DataStructures.PriorityQueue(Int,T,Base.Order.Reverse) + pq = DataStructures.PriorityQueue(Int, T, Base.Order.Reverse) # Set number of visited neighbors for all vertices to 0 for v in vertices(g) pq[v] = zero(T) end - @assert haskey(pq,s) + @assert haskey(pq, s) @assert nv(g) >= 2 #Give the starting vertex high priority @@ -77,7 +77,7 @@ end # ################################################# -mutable struct MinCutVisitor{T, U<:Integer} <: AbstractMASVisitor +mutable struct MinCutVisitor{T,U<:Integer} <: AbstractMASVisitor graph::AbstractGraph parities::BitVector colormap::Vector{Int} @@ -88,14 +88,14 @@ mutable struct MinCutVisitor{T, U<:Integer} <: AbstractMASVisitor vertices::Vector{U} end -function MinCutVisitor{T}(g::AbstractGraph, distmx::AbstractMatrix{T}) +function MinCutVisitor(g::AbstractGraph, distmx::AbstractMatrix{T}) where T U = eltype(g) n = nv(g) parities = falses(n) return MinCutVisitor( g, falses(n), - zeros(Int,n), + zeros(Int, n), typemax(T), zero(T), zero(Int), @@ -107,7 +107,7 @@ end function discover_vertex!(vis::MinCutVisitor, v::Integer) vis.parities[v] = false vis.colormap[v] = 1 - push!(vis.vertices,v) + push!(vis.vertices, v) return true end @@ -132,7 +132,7 @@ function close_vertex!(vis::MinCutVisitor, v::Integer) if vis.cutweight < vis.bestweight && vis.visited < nv(vis.graph) vis.bestweight = vis.cutweight for u in vertices(vis.graph) - vis.parities[u] = ( vis.colormap[u] == 2) + vis.parities[u] = (vis.colormap[u] == 2) end end return true @@ -144,15 +144,15 @@ end # ################################################# -struct MASVisitor{T, U<:Integer} <: AbstractMASVisitor +struct MASVisitor{T,U<:Integer} <: AbstractMASVisitor io::IO vertices::Vector{U} distmx::AbstractMatrix{T} log::Bool end -function discover_vertex!{T}(visitor::MASVisitor{T}, v::Integer) - push!(visitor.vertices,v) +function discover_vertex!(visitor::MASVisitor{T}, v::Integer) where T + push!(visitor.vertices, v) visitor.log ? println(visitor.io, "discover vertex: $v") : nothing return true end @@ -182,10 +182,10 @@ values that determines the partition in `g` (1 or 2) and `bestcut` is the weight of the cut that makes this partition. An optional `distmx` matrix may be specified; if omitted, edge distances are assumed to be 1. """ -function mincut{T}( +function mincut( g::AbstractGraph, distmx::AbstractMatrix{T}=weights(g) -) +) where T visitor = MinCutVisitor(g, distmx) colormap = zeros(Int, nv(g)) traverse_graph!(g, T, MaximumAdjacency(), 1, visitor, colormap) @@ -202,12 +202,12 @@ be 1. If `log` (default `false`) is `true`, visitor events will be printed to `io`, which defaults to `STDOUT`; otherwise, no event information will be displayed. """ -function maximum_adjacency_visit{T}( +function maximum_adjacency_visit( g::AbstractGraph, distmx::AbstractMatrix{T}, log::Bool, io::IO -) +) where T visitor = MASVisitor(io, Vector{Int}(), distmx, log) traverse_graph!(g, T, MaximumAdjacency(), 1, visitor, zeros(Int, nv(g))) return visitor.vertices diff --git a/src/traversals/parallel_bfs.jl b/src/traversals/parallel_bfs.jl index 0631bba25..c8420dfac 100644 --- a/src/traversals/parallel_bfs.jl +++ b/src/traversals/parallel_bfs.jl @@ -23,7 +23,7 @@ mutable struct LevelSynchronousBFS <: AbstractGraphVisitAlgorithm end A thread safe queue implementation for using as the queue for BFS. """ -struct ThreadQueue{T, N<:Integer} +struct ThreadQueue{T,N<:Integer} data::Vector{T} head::Atomic{N} #Index of the head tail::Atomic{N} #Index of the tail @@ -34,41 +34,41 @@ function ThreadQueue(T::Type, maxlength::N) where N <: Integer return q end -function push!{T, N}(q::ThreadQueue{T, N}, val::T) +function push!(q::ThreadQueue{T,N}, val::T) where T where N # TODO: check that head > tail offset = atomic_add!(q.tail, one(N)) q.data[offset] = val return offset end -function shift!{T, N}(q::ThreadQueue{T, N}) +function shift!(q::ThreadQueue{T,N}) where T where N # TODO: check that head < tail offset = atomic_add!(q.head, one(N)) return q.data[offset] end -function isempty{T, N}(q::ThreadQueue{T, N}) - return ( q.head[] == q.tail[] ) && q.head != one(N) +function isempty(q::ThreadQueue{T,N}) where T where N + return (q.head[] == q.tail[]) && q.head != one(N) end -function getindex{T}(q::ThreadQueue{T}, iter) +function getindex(q::ThreadQueue{T}, iter) where T return q.data[iter] end # Traverses the vertices in the queue and adds newly found successors to the queue. -function bfskernel{T <: Integer}( +function bfskernel( alg::LevelSynchronousBFS, next::ThreadQueue, # Thread safe queue to add vertices to g::AbstractGraph, # The graph parents::Array{Atomic{T}}, # Parents array level::Array{T} # Vertices in the current frontier - ) + ) where T <: Integer @threads for src in level vertexneighbors = neighbors(g, src) # Get the neighbors of the vertex for vertex in vertexneighbors # Atomically check and set parent value if not set yet. parent = atomic_cas!(parents[vertex], zero(T), src) - if parent==0 + if parent == 0 push!(next, vertex) #Push onto queue if newly found end end @@ -93,10 +93,10 @@ function bfs_tree!( source::T, # Source vertex parents::Array{Atomic{T}} # Parents array ) where T<:Integer - parents[source][]=source # Set source to source + parents[source][] = source # Set source to source push!(next, source) # Add source to the queue while !isempty(next) - level = next[next.head[]:next.tail[]-1] # Get vertices in the frontier + level = next[next.head[]:(next.tail[] - 1)] # Get vertices in the frontier next.head[] = next.tail[] # reset the queue bfskernel(alg, next, g, parents, level) # Find new frontier end @@ -116,14 +116,14 @@ environment variable to decide the number of threads to use. Refer `@threads` do for more details. This function is a high level wrapper around [`bfs_tree!`](@ref); use that function for more performance. """ -function bfs_tree{T <: Integer}(alg::LevelSynchronousBFS, g::AbstractGraph, source::T, nv::T) +function bfs_tree(alg::LevelSynchronousBFS, g::AbstractGraph, source::T, nv::T) where T <: Integer next = ThreadQueue(T, nv) # Initialize threadqueue - parents = [Atomic{T}(0) for i=1:nv] # Create parents array + parents = [Atomic{T}(0) for i = 1:nv] # Create parents array bfs_tree!(alg, next, g, source, parents) tree([i[] for i in parents]) end -function bfs_tree{T <: Integer}(alg::LevelSynchronousBFS, g::AbstractGraph, source::T) +function bfs_tree(alg::LevelSynchronousBFS, g::AbstractGraph, source::T) where T <: Integer nvg = nv(g) bfs_tree(alg, g, source, nvg) end diff --git a/src/traversals/randomwalks.jl b/src/traversals/randomwalks.jl index 148512f2e..e34f5dec2 100644 --- a/src/traversals/randomwalks.jl +++ b/src/traversals/randomwalks.jl @@ -14,11 +14,11 @@ function randomwalk(g::AbstractGraph, s::Integer, niter::Integer) while i <= niter push!(visited, currs) i += 1 - nbrs = out_neighbors(g,currs) + nbrs = out_neighbors(g, currs) length(nbrs) == 0 && break currs = rand(nbrs) end - return visited[1:i-1] + return visited[1:(i - 1)] end """ @@ -40,17 +40,17 @@ function non_backtracking_randomwalk end push!(visited, currs) i += 1 - nbrs = out_neighbors(g,currs) - length(nbrs) == 0 && return visited[1:i-1] + nbrs = out_neighbors(g, currs) + length(nbrs) == 0 && return visited[1:(i - 1)] prev = currs currs = rand(nbrs) while i <= niter push!(visited, currs) i += 1 - nbrs = out_neighbors(g,currs) + nbrs = out_neighbors(g, currs) length(nbrs) == 1 && break - idnext = rand(1:length(nbrs)-1) + idnext = rand(1:(length(nbrs) - 1)) next = nbrs[idnext] if next == prev next = nbrs[end] @@ -58,7 +58,7 @@ function non_backtracking_randomwalk end prev = currs currs = next end - return visited[1:i-1] + return visited[1:(i - 1)] end @traitfn function non_backtracking_randomwalk(g::::IsDirected, s::Integer, niter::Integer) @@ -73,12 +73,12 @@ end while i <= niter push!(visited, currs) i += 1 - nbrs = out_neighbors(g,currs) + nbrs = out_neighbors(g, currs) length(nbrs) == 0 && break next = rand(nbrs) if next == prev length(nbrs) == 1 && break - idnext = rand(1:length(nbrs)-1) + idnext = rand(1:(length(nbrs) - 1)) next = nbrs[idnext] if next == prev next = nbrs[end] @@ -87,7 +87,7 @@ end prev = currs currs = next end - return visited[1:i-1] + return visited[1:(i - 1)] end """ @@ -109,9 +109,9 @@ function saw(g::AbstractGraph, s::Integer, niter::Integer) push!(visited, currs) push!(svisited, currs) i += 1 - nbrs = setdiff(Set(out_neighbors(g,currs)),svisited) + nbrs = setdiff(Set(out_neighbors(g, currs)), svisited) length(nbrs) == 0 && break currs = rand(collect(nbrs)) end - return visited[1:i-1] + return visited[1:(i - 1)] end diff --git a/src/utils.jl b/src/utils.jl index 7e5e5c4cc..3f76424d6 100644 --- a/src/utils.jl +++ b/src/utils.jl @@ -16,10 +16,10 @@ function sample!(rng::AbstractRNG, a::AbstractArray, k::Integer; exclude = ()) n = length(a) i = 1 while length(res) < k - r = rand(rng, 1:n-i+1) + r = rand(rng, 1:(n - i + 1)) if !(a[r] in exclude) push!(res, a[r]) - a[r], a[n-i+1] = a[n-i+1], a[r] + a[r], a[n - i + 1] = a[n - i + 1], a[r] i += 1 end end diff --git a/test/biconnectivity/articulation.jl b/test/biconnectivity/articulation.jl index 78a7cdcc8..8716ca0fc 100644 --- a/test/biconnectivity/articulation.jl +++ b/test/biconnectivity/articulation.jl @@ -27,7 +27,7 @@ btree = LightGraphs.BinaryTree(level) for tree in [btree, Graph{UInt8}(btree), Graph{Int16}(btree)] artpts = @inferred(articulation(tree)) - @test artpts == collect(1:(2^(level-1)-1)) + @test artpts == collect(1:(2^(level - 1) - 1)) end end diff --git a/test/biconnectivity/biconnect.jl b/test/biconnectivity/biconnect.jl index 44a021b44..c3e6136a9 100644 --- a/test/biconnectivity/biconnect.jl +++ b/test/biconnectivity/biconnect.jl @@ -41,7 +41,7 @@ gint = blkdiag(g, h) add_edge!(gint, 4, 5) - a = [[Edge(5, 8),Edge(7, 8),Edge(6, 7),Edge(5, 6)], [Edge(4, 5)], [Edge(1, 4),Edge(3, 4),Edge(2, 3),Edge(1, 2)]] + a = [[Edge(5, 8), Edge(7, 8), Edge(6, 7), Edge(5, 6)], [Edge(4, 5)], [Edge(1, 4), Edge(3, 4), Edge(2, 3), Edge(1, 2)]] for g in testgraphs(gint) bcc = @inferred(biconnected_components(g)) diff --git a/test/centrality/betweenness.jl b/test/centrality/betweenness.jl index 713ebda8a..38301f9c0 100644 --- a/test/centrality/betweenness.jl +++ b/test/centrality/betweenness.jl @@ -1,12 +1,12 @@ @testset "Betweenness" begin # self loops s2 = DiGraph(3) - add_edge!(s2,1,2); add_edge!(s2,2,3); add_edge!(s2,3,3) + add_edge!(s2, 1, 2); add_edge!(s2, 2, 3); add_edge!(s2, 3, 3) s1 = Graph(s2) g3 = PathGraph(5) function readcentrality(f::AbstractString) - f = open(f,"r") + f = open(f, "r") c = Vector{Float64}() while !eof(f) line = chomp(readline(f)) @@ -16,28 +16,28 @@ end - gint = loadgraph(joinpath(testdir,"testdata","graph-50-500.jgz"), "graph-50-500") + gint = loadgraph(joinpath(testdir, "testdata", "graph-50-500.jgz"), "graph-50-500") - c = readcentrality(joinpath(testdir,"testdata","graph-50-500-bc.txt")) + c = readcentrality(joinpath(testdir, "testdata", "graph-50-500-bc.txt")) for g in testdigraphs(gint) z = @inferred(betweenness_centrality(g)) zp = @inferred(parallel_betweenness_centrality(g)) - @test all(isapprox.(z,zp)) + @test all(isapprox.(z, zp)) @test map(Float32, z) == map(Float32, c) y = @inferred(betweenness_centrality(g, endpoints=true, normalize=false)) yp = parallel_betweenness_centrality(g, endpoints=true, normalize=false) - @test all(isapprox(y,yp)) - @test round.(y[1:3],4) == + @test all(isapprox(y, yp)) + @test round.(y[1:3], 4) == round.([122.10760591498584, 159.0072453120582, 176.39547945994505], 4) - x = @inferred(betweenness_centrality(g,3)) - xp = parallel_betweenness_centrality(g,3) + x = @inferred(betweenness_centrality(g, 3)) + xp = parallel_betweenness_centrality(g, 3) - x2 = @inferred(betweenness_centrality(g,collect(1:20))) - xp2 = parallel_betweenness_centrality(g,collect(1:20)) + x2 = @inferred(betweenness_centrality(g, collect(1:20))) + xp2 = parallel_betweenness_centrality(g, collect(1:20)) @test length(x) == 50 @test length(xp) == 50 @@ -52,23 +52,23 @@ @test parallel_betweenness_centrality(s2) == [0, 0.5, 0] g = Graph(2) - add_edge!(g,1,2) + add_edge!(g, 1, 2) z = @inferred(betweenness_centrality(g; normalize=true)) zp = parallel_betweenness_centrality(g; normalize=true) - @test all(isapprox(z,zp)) + @test all(isapprox(z, zp)) @test z[1] == z[2] == 0.0 z2 = @inferred(betweenness_centrality(g, vertices(g))) zp2 = parallel_betweenness_centrality(g, vertices(g)) - @test all(isapprox(z2,zp2)) + @test all(isapprox(z2, zp2)) z3 = @inferred(betweenness_centrality(g, [vertices(g);])) zp3 = parallel_betweenness_centrality(g, [vertices(g);]) - @test all(isapprox(z3,zp3)) + @test all(isapprox(z3, zp3)) @test z == z2 == z3 z = @inferred(betweenness_centrality(g3; normalize=false)) zp = parallel_betweenness_centrality(g3; normalize=false) - @test all(isapprox(z,zp)) + @test all(isapprox(z, zp)) @test z[1] == z[5] == 0.0 end diff --git a/test/centrality/closeness.jl b/test/centrality/closeness.jl index e476bed6b..ebcd75467 100644 --- a/test/centrality/closeness.jl +++ b/test/centrality/closeness.jl @@ -1,6 +1,6 @@ @testset "Closeness" begin g5 = DiGraph(4) - add_edge!(g5,1,2); add_edge!(g5,2,3); add_edge!(g5,1,3); add_edge!(g5,3,4) + add_edge!(g5, 1, 2); add_edge!(g5, 2, 3); add_edge!(g5, 1, 3); add_edge!(g5, 3, 4) for g in testdigraphs(g5) y = @inferred(closeness_centrality(g; normalize=false)) @@ -17,19 +17,19 @@ a2 = DiGraph(adjmx2) for g in testdigraphs(a2) distmx2 = [Inf 2.0 Inf; 3.2 Inf 4.2; 5.5 6.1 Inf] - c2 = [0.24390243902439027,0.27027027027027023,0.1724137931034483] - y = @inferred(closeness_centrality(g,distmx2; normalize=false)) - z = @inferred(closeness_centrality(g,distmx2)) - py = @inferred(parallel_closeness_centrality(g,distmx2; normalize=false)) - pz = @inferred(parallel_closeness_centrality(g,distmx2)) - @test isapprox(y,c2) - @test isapprox(z,c2) - @test isapprox(py,c2) - @test isapprox(pz,c2) + c2 = [0.24390243902439027, 0.27027027027027023, 0.1724137931034483] + y = @inferred(closeness_centrality(g, distmx2; normalize=false)) + z = @inferred(closeness_centrality(g, distmx2)) + py = @inferred(parallel_closeness_centrality(g, distmx2; normalize=false)) + pz = @inferred(parallel_closeness_centrality(g, distmx2)) + @test isapprox(y, c2) + @test isapprox(z, c2) + @test isapprox(py, c2) + @test isapprox(pz, c2) end g5 = Graph(5) - add_edge!(g5,1,2) + add_edge!(g5, 1, 2) for g in testgraphs(g5) z = @inferred(closeness_centrality(g)) y = @inferred(parallel_closeness_centrality(g)) @@ -43,14 +43,14 @@ a1 = Graph(adjmx1) for g in testdigraphs(a2) distmx1 = [Inf 2.0 Inf; 2.0 Inf 4.2; Inf 4.2 Inf] - c1 = [0.24390243902439027,0.3225806451612903,0.1923076923076923] - y = @inferred(closeness_centrality(g,distmx1; normalize=false)) - z = @inferred(closeness_centrality(g,distmx1)) - py = @inferred(parallel_closeness_centrality(g,distmx1; normalize=false)) - pz = @inferred(parallel_closeness_centrality(g,distmx1)) - @test isapprox(y,c1) - @test isapprox(z,c1) - @test isapprox(py,c1) - @test isapprox(pz,c1) + c1 = [0.24390243902439027, 0.3225806451612903, 0.1923076923076923] + y = @inferred(closeness_centrality(g, distmx1; normalize=false)) + z = @inferred(closeness_centrality(g, distmx1)) + py = @inferred(parallel_closeness_centrality(g, distmx1; normalize=false)) + pz = @inferred(parallel_closeness_centrality(g, distmx1)) + @test isapprox(y, c1) + @test isapprox(z, c1) + @test isapprox(py, c1) + @test isapprox(pz, c1) end end diff --git a/test/centrality/degree.jl b/test/centrality/degree.jl index 837b847a2..796793c0a 100644 --- a/test/centrality/degree.jl +++ b/test/centrality/degree.jl @@ -1,6 +1,6 @@ @testset "Degree" begin g5 = DiGraph(4) - add_edge!(g5,1,2); add_edge!(g5,2,3); add_edge!(g5,1,3); add_edge!(g5,3,4) + add_edge!(g5, 1, 2); add_edge!(g5, 2, 3); add_edge!(g5, 1, 3); add_edge!(g5, 3, 4) for g in testdigraphs(g5) @test @inferred(degree_centrality(g)) == [0.6666666666666666, 0.6666666666666666, 1.0, 0.3333333333333333] @test @inferred(indegree_centrality(g, normalize=false)) == [0.0, 1.0, 2.0, 1.0] diff --git a/test/centrality/eigenvector.jl b/test/centrality/eigenvector.jl index c9f76600e..86e396c34 100644 --- a/test/centrality/eigenvector.jl +++ b/test/centrality/eigenvector.jl @@ -11,7 +11,6 @@ end for g in testdigraphs(g2) y = @inferred(eigenvector_centrality(g)) - @test round.(y, 3) == round.([ - 0.5, 0.5, 0.5, 0.5 ], 3) + @test round.(y, 3) == round.([0.5, 0.5, 0.5, 0.5], 3) end end diff --git a/test/centrality/katz.jl b/test/centrality/katz.jl index fe83ef29a..dd9b6909e 100644 --- a/test/centrality/katz.jl +++ b/test/centrality/katz.jl @@ -1,6 +1,6 @@ @testset "Katz" begin g5 = DiGraph(4) - add_edge!(g5,1,2); add_edge!(g5,2,3); add_edge!(g5,1,3); add_edge!(g5,3,4) + add_edge!(g5, 1, 2); add_edge!(g5, 2, 3); add_edge!(g5, 1, 3); add_edge!(g5, 3, 4) for g in testdigraphs(g5) z = @inferred(katz_centrality(g, 0.4)) @test round.(z, 2) == [0.32, 0.44, 0.62, 0.56] diff --git a/test/centrality/pagerank.jl b/test/centrality/pagerank.jl index eb9ab7084..1bd7516ef 100644 --- a/test/centrality/pagerank.jl +++ b/test/centrality/pagerank.jl @@ -1,8 +1,8 @@ @testset "Pagerank" begin g5 = DiGraph(4) - add_edge!(g5,1,2); add_edge!(g5,2,3); add_edge!(g5,1,3); add_edge!(g5,3,4) + add_edge!(g5, 1, 2); add_edge!(g5, 2, 3); add_edge!(g5, 1, 3); add_edge!(g5, 3, 4) for g in testdigraphs(g5) - @test pagerank(g)[3] ≈ 0.318 atol=0.001 + @test pagerank(g)[3] ≈ 0.318 atol = 0.001 @test length(@inferred(pagerank(g))) == nv(g) @test_throws ErrorException pagerank(g, 2) @test_throws ErrorException pagerank(g, 0.85, 2) diff --git a/test/community/cliques.jl b/test/community/cliques.jl index 310492756..0bcd9915f 100644 --- a/test/community/cliques.jl +++ b/test/community/cliques.jl @@ -18,11 +18,11 @@ gx = Graph(3) add_edge!(gx, 1, 2) for g in testgraphs(gx) - @test test_cliques(g, Array[[1,2], [3]]) + @test test_cliques(g, Array[[1, 2], [3]]) end add_edge!(gx, 2, 3) for g in testgraphs(gx) - @test test_cliques(g, Array[[1,2], [2,3]]) + @test test_cliques(g, Array[[1, 2], [2, 3]]) end # Test for "pivotdonenbrs not defined" bug h = Graph(6) @@ -42,14 +42,14 @@ # test for extra cliques bug h = Graph(7) - add_edge!(h,1,3) - add_edge!(h,2,6) - add_edge!(h,3,5) - add_edge!(h,3,6) - add_edge!(h,4,5) - add_edge!(h,4,7) - add_edge!(h,5,7) + add_edge!(h, 1, 3) + add_edge!(h, 2, 6) + add_edge!(h, 3, 5) + add_edge!(h, 3, 6) + add_edge!(h, 4, 5) + add_edge!(h, 4, 7) + add_edge!(h, 5, 7) for g in testgraphs(h) - @test test_cliques(h, Array[[7,4,5], [2,6], [3,5], [3,6], [3,1]]) + @test test_cliques(h, Array[[7, 4, 5], [2, 6], [3, 5], [3, 6], [3, 1]]) end end diff --git a/test/community/core-periphery.jl b/test/community/core-periphery.jl index 8dc96fcfe..eb1f2427d 100644 --- a/test/community/core-periphery.jl +++ b/test/community/core-periphery.jl @@ -4,22 +4,22 @@ c = core_periphery_deg(g) @test @inferred(degree(g, 1)) == 9 @test c[1] == 1 - for i=2:10 + for i = 2:10 @test c[i] == 2 end end g10 = StarGraph(10) - g10 = blkdiag(g10,g10) + g10 = blkdiag(g10, g10) add_edge!(g10, 1, 11) for g in testgraphs(g10) c = @inferred(core_periphery_deg(g)) @test c[1] == 1 @test c[11] == 1 - for i=2:10 + for i = 2:10 @test c[i] == 2 end - for i=12:20 + for i = 12:20 @test c[i] == 2 end end diff --git a/test/community/label_propagation.jl b/test/community/label_propagation.jl index 3f6152611..5b5ae1d0d 100644 --- a/test/community/label_propagation.jl +++ b/test/community/label_propagation.jl @@ -1,14 +1,14 @@ @testset "Label propagation" begin - n=10 + n = 10 g10 = CompleteGraph(n) for g in testgraphs(g10) z = copy(g) - for k=2:5 + for k = 2:5 z = blkdiag(z, g) - add_edge!(z, (k-1)*n, k*n) + add_edge!(z, (k - 1) * n, k * n) c, ch = @inferred(label_propagation(z)) - a = collect(n:n:k*n) - a = Int[div(i-1,n)+1 for i=1:k*n] + a = collect(n:n:(k * n)) + a = Int[div(i - 1, n) + 1 for i = 1:(k * n)] # check the number of communities @test length(unique(a)) == length(unique(c)) # check the partition diff --git a/test/community/modularity.jl b/test/community/modularity.jl index 98fe437d6..0b4965672 100644 --- a/test/community/modularity.jl +++ b/test/community/modularity.jl @@ -1,6 +1,6 @@ @testset "Modularity" begin n = 10 - m = n*(n-1)/2 + m = n * (n - 1) / 2 c = ones(Int, n) gint = CompleteGraph(n) for g in testgraphs(gint) diff --git a/test/connectivity.jl b/test/connectivity.jl index 26a5fd4aa..186972d36 100644 --- a/test/connectivity.jl +++ b/test/connectivity.jl @@ -1,72 +1,71 @@ @testset "Connectivity" begin g6 = smallgraph(:house) gx = PathGraph(4) - add_vertices!(gx,10) - add_edge!(gx,5,6) - add_edge!(gx,6,7) - add_edge!(gx,8,9) - add_edge!(gx,10,9) + add_vertices!(gx, 10) + add_edge!(gx, 5, 6) + add_edge!(gx, 6, 7) + add_edge!(gx, 8, 9) + add_edge!(gx, 10, 9) for g in testgraphs(gx) - @test @inferred(!is_connected(g)) - cc = @inferred(connected_components(g)) - label = zeros(eltype(g), nv(g)) - @inferred(LightGraphs.connected_components!(label, g)) - @test label[1:10] == [1,1,1,1,5,5,5,8,8,8] - import LightGraphs: components, components_dict - cclab = @inferred(components_dict(label)) - @test cclab[1] == [1,2,3,4] - @test cclab[5] == [5,6,7] - @test cclab[8] == [8,9,10] - @test length(cc) >= 3 && sort(cc[3]) == [8,9,10] + @test @inferred(!is_connected(g)) + cc = @inferred(connected_components(g)) + label = zeros(eltype(g), nv(g)) + @inferred(LightGraphs.connected_components!(label, g)) + @test label[1:10] == [1, 1, 1, 1, 5, 5, 5, 8, 8, 8] + import LightGraphs: components, components_dict + cclab = @inferred(components_dict(label)) + @test cclab[1] == [1, 2, 3, 4] + @test cclab[5] == [5, 6, 7] + @test cclab[8] == [8, 9, 10] + @test length(cc) >= 3 && sort(cc[3]) == [8, 9, 10] end for g in testgraphs(g6) - @test @inferred(is_connected(g)) + @test @inferred(is_connected(g)) end g10 = DiGraph(4) - add_edge!(g10,1,3) - add_edge!(g10,2,4) + add_edge!(g10, 1, 3) + add_edge!(g10, 2, 4) for g in testdigraphs(g10) - @test @inferred(is_bipartite(g)) + @test @inferred(is_bipartite(g)) end - add_edge!(g10,1,4) + add_edge!(g10, 1, 4) for g in testdigraphs(g10) - @test @inferred(is_bipartite(g)) + @test @inferred(is_bipartite(g)) end g10 = DiGraph(20) for g in testdigraphs(g10) - for m=1:50 - i = rand(1:10) - j = rand(11:20) - if rand() < 0.5 - i, j = j, i + for m = 1:50 + i = rand(1:10) + j = rand(11:20) + if rand() < 0.5 + i, j = j, i + end + if !has_edge(g, i, j) + add_edge!(g, i, j) + @test @inferred(is_bipartite(g)) + end end - if !has_edge(g, i, j) - add_edge!(g, i, j) - @test @inferred(is_bipartite(g)) - end - end end # graph from https://en.wikipedia.org/wiki/Strongly_connected_component h = DiGraph(8) - add_edge!(h,1,2); add_edge!(h,2,3); add_edge!(h,2,5); - add_edge!(h,2,6); add_edge!(h,3,4); add_edge!(h,3,7); - add_edge!(h,4,3); add_edge!(h,4,8); add_edge!(h,5,1); - add_edge!(h,5,6); add_edge!(h,6,7); add_edge!(h,7,6); - add_edge!(h,8,4); add_edge!(h,8,7) + add_edge!(h, 1, 2); add_edge!(h, 2, 3); add_edge!(h, 2, 5); + add_edge!(h, 2, 6); add_edge!(h, 3, 4); add_edge!(h, 3, 7); + add_edge!(h, 4, 3); add_edge!(h, 4, 8); add_edge!(h, 5, 1); + add_edge!(h, 5, 6); add_edge!(h, 6, 7); add_edge!(h, 7, 6); + add_edge!(h, 8, 4); add_edge!(h, 8, 7) for g in testdigraphs(h) - @test @inferred(is_weakly_connected(g)) - scc = @inferred(strongly_connected_components(g)) - wcc = @inferred(weakly_connected_components(g)) - - @test length(scc) == 3 && sort(scc[3]) == [1,2,5] - @test length(wcc) == 1 && length(wcc[1]) == nv(g) + @test @inferred(is_weakly_connected(g)) + scc = @inferred(strongly_connected_components(g)) + wcc = @inferred(weakly_connected_components(g)) + @test length(scc) == 3 && sort(scc[3]) == [1, 2, 5] + @test length(wcc) == 1 && length(wcc[1]) == nv(g) end @@ -89,31 +88,31 @@ end h = DiGraph(6) - add_edge!(h,1,3); add_edge!(h,3,4); add_edge!(h,4,2); add_edge!(h,2,1) - add_edge!(h,3,5); add_edge!(h,5,6); add_edge!(h,6,4) + add_edge!(h, 1, 3); add_edge!(h, 3, 4); add_edge!(h, 4, 2); add_edge!(h, 2, 1) + add_edge!(h, 3, 5); add_edge!(h, 5, 6); add_edge!(h, 6, 4) for g in testdigraphs(h) scc = @inferred(strongly_connected_components(g)) @test length(scc) == 1 && sort(scc[1]) == [1:6;] end # tests from Graphs.jl h = DiGraph(4) - add_edge!(h,1,2); add_edge!(h,2,3); add_edge!(h,3,1); add_edge!(h,4,1) + add_edge!(h, 1, 2); add_edge!(h, 2, 3); add_edge!(h, 3, 1); add_edge!(h, 4, 1) for g in testdigraphs(h) scc = @inferred(strongly_connected_components(g)) @test length(scc) == 2 && sort(scc[1]) == [1:3;] && sort(scc[2]) == [4] end h = DiGraph(12) - add_edge!(h,1,2); add_edge!(h,2,3); add_edge!(h,2,4); add_edge!(h,2,5); - add_edge!(h,3,6); add_edge!(h,4,5); add_edge!(h,4,7); add_edge!(h,5,2); - add_edge!(h,5,6); add_edge!(h,5,7); add_edge!(h,6,3); add_edge!(h,6,8); - add_edge!(h,7,8); add_edge!(h,7,10); add_edge!(h,8,7); add_edge!(h,9,7); - add_edge!(h,10,9); add_edge!(h,10,11); add_edge!(h,11,12); add_edge!(h,12,10) + add_edge!(h, 1, 2); add_edge!(h, 2, 3); add_edge!(h, 2, 4); add_edge!(h, 2, 5); + add_edge!(h, 3, 6); add_edge!(h, 4, 5); add_edge!(h, 4, 7); add_edge!(h, 5, 2); + add_edge!(h, 5, 6); add_edge!(h, 5, 7); add_edge!(h, 6, 3); add_edge!(h, 6, 8); + add_edge!(h, 7, 8); add_edge!(h, 7, 10); add_edge!(h, 8, 7); add_edge!(h, 9, 7); + add_edge!(h, 10, 9); add_edge!(h, 10, 11); add_edge!(h, 11, 12); add_edge!(h, 12, 10) for g in testdigraphs(h) scc = @inferred(strongly_connected_components(g)) @test length(scc) == 4 - @test sort(scc[1]) == [7,8,9,10,11,12] + @test sort(scc[1]) == [7, 8, 9, 10, 11, 12] @test sort(scc[2]) == [3, 6] @test sort(scc[3]) == [2, 4, 5] @test scc[4] == [1] @@ -122,37 +121,37 @@ # Graph-Theoretic Analysis of Finite Markov Chains by J.P. Jarvis & D. R. Shier # figure 1 example - fig1 = spzeros(5,5) - fig1[[3,4,9,10,11,13,18,19,22,24]] = [.5,.4,.1,1.,1.,.2,.3,.2,1.,.3] + fig1 = spzeros(5, 5) + fig1[[3, 4, 9, 10, 11, 13, 18, 19, 22, 24]] = [.5, .4, .1, 1., 1., .2, .3, .2, 1., .3] fig1 = DiGraph(fig1) - scc_fig1 = Vector[[2,5],[1,3,4]] + scc_fig1 = Vector[[2, 5], [1, 3, 4]] # figure 2 example - fig2 = spzeros(5,5) + fig2 = spzeros(5, 5) fig2[[3, 10, 11, 13, 14, 17, 18, 19, 22]] = 1 fig2 = DiGraph(fig2) # figure 3 example - fig3 = spzeros(8,8) - fig3[[1,7,9,13,14,15,18,20,23,27,28,31,33,34,37,45,46,49,57,63,64]] = 1 + fig3 = spzeros(8, 8) + fig3[[1, 7, 9, 13, 14, 15, 18, 20, 23, 27, 28, 31, 33, 34, 37, 45, 46, 49, 57, 63, 64]] = 1 fig3 = DiGraph(fig3) - scc_fig3 = Vector[[3,4],[2,5,6],[8],[1,7]] + scc_fig3 = Vector[[3, 4], [2, 5, 6], [8], [1, 7]] fig3_cond = DiGraph(4); - add_edge!(fig3_cond,4,3); add_edge!(fig3_cond,2,1) - add_edge!(fig3_cond,4,1); add_edge!(fig3_cond,4,2) + add_edge!(fig3_cond, 4, 3); add_edge!(fig3_cond, 2, 1) + add_edge!(fig3_cond, 4, 1); add_edge!(fig3_cond, 4, 2) # construct a n-number edge ring graph (period = n) n = 10 - n_ring_m = spdiagm(ones(n-1),1,n,n); n_ring_m[end,1] = 1 + n_ring_m = spdiagm(ones(n - 1), 1, n, n); n_ring_m[end, 1] = 1 n_ring = DiGraph(n_ring_m) - n_ring_shortcut = copy(n_ring); add_edge!(n_ring_shortcut,1,4) + n_ring_shortcut = copy(n_ring); add_edge!(n_ring_shortcut, 1, 4) # figure 8 example - fig8 = spzeros(6,6) - fig8[[2,10,13,21,24,27,35]] = 1 + fig8 = spzeros(6, 6) + fig8[[2, 10, 13, 21, 24, 27, 35]] = 1 fig8 = DiGraph(fig8) @test Set(@inferred(strongly_connected_components(fig1))) == Set(scc_fig1) @@ -163,12 +162,12 @@ @test @inferred(condensation(fig3)) == fig3_cond - @test @inferred(attracting_components(fig1)) == Vector[[2,5]] - @test @inferred(attracting_components(fig3)) == Vector[[3,4],[8]] + @test @inferred(attracting_components(fig1)) == Vector[[2, 5]] + @test @inferred(attracting_components(fig3)) == Vector[[3, 4], [8]] g10 = StarGraph(10) for g in testgraphs(g10) - @test @inferred(neighborhood(g, 1 , 0)) == [1] + @test @inferred(neighborhood(g, 1, 0)) == [1] @test length(@inferred(neighborhood(g, 1, 1))) == 10 @test length(@inferred(neighborhood(g, 2, 1))) == 2 @test length(@inferred(neighborhood(g, 1, 2))) == 10 @@ -176,18 +175,18 @@ end g10 = StarDiGraph(10) for g in testdigraphs(g10) - @test @inferred(neighborhood(g10, 1 , 0, dir=:out)) == [1] - @test length(@inferred(neighborhood(g, 1, 1, dir=:out))) == 10 - @test length(@inferred(neighborhood(g, 2, 1, dir=:out))) == 1 - @test length(@inferred(neighborhood(g, 1, 2, dir=:out))) == 10 - @test length(@inferred(neighborhood(g, 2, 2, dir=:out))) == 1 - @test @inferred(neighborhood(g, 1 , 0, dir=:in)) == [1] - @test length(@inferred(neighborhood(g, 1, 1, dir=:in))) == 1 - @test length(@inferred(neighborhood(g, 2, 1, dir=:in))) == 2 - @test length(@inferred(neighborhood(g, 1, 2, dir=:in))) == 1 - @test length(@inferred(neighborhood(g, 2, 2, dir=:in))) == 2 + @test @inferred(neighborhood(g10, 1, 0, dir=:out)) == [1] + @test length(@inferred(neighborhood(g, 1, 1, dir=:out))) == 10 + @test length(@inferred(neighborhood(g, 2, 1, dir=:out))) == 1 + @test length(@inferred(neighborhood(g, 1, 2, dir=:out))) == 10 + @test length(@inferred(neighborhood(g, 2, 2, dir=:out))) == 1 + @test @inferred(neighborhood(g, 1, 0, dir=:in)) == [1] + @test length(@inferred(neighborhood(g, 1, 1, dir=:in))) == 1 + @test length(@inferred(neighborhood(g, 2, 1, dir=:in))) == 2 + @test length(@inferred(neighborhood(g, 1, 2, dir=:in))) == 1 + @test length(@inferred(neighborhood(g, 2, 2, dir=:in))) == 2 end - @test @inferred(!isgraphical([1,1,1])) - @test @inferred(isgraphical([2,2,2])) - @test @inferred(isgraphical(fill(3,10))) + @test @inferred(!isgraphical([1, 1, 1])) + @test @inferred(isgraphical([2, 2, 2])) + @test @inferred(isgraphical(fill(3, 10))) end diff --git a/test/core.jl b/test/core.jl index 6e98f3811..7bea597f2 100644 --- a/test/core.jl +++ b/test/core.jl @@ -1,54 +1,54 @@ @testset "Core" begin -e2 = Edge(1,3) -e3 = Edge(1,4) -@test @inferred(is_ordered(e2)) -@test @inferred(!is_ordered(reverse(e3))) - -gx = Graph(10) -for g in testgraphs(gx) - add_vertices!(g, 5) - @test @inferred(nv(g)) == 15 -end - -g5w = WheelGraph(5) -for g in testgraphs(g5w) - @test @inferred(indegree(g,1)) == @inferred(outdegree(g,1)) == @inferred(degree(g,1)) == 4 - @test @inferred(indegree(g)) == @inferred(outdegree(g)) == @inferred(degree(g)) == [4,3,3,3,3] - - @test @inferred(Δout(g)) == @inferred(Δin(g)) == @inferred(Δ(g)) == 4 - @test @inferred(δout(g)) == @inferred(δin(g)) == @inferred(δ(g)) == 3 - @test @inferred(weights(g)) == LightGraphs.DefaultDistance(nv(g)) - z1 = @inferred(degree_histogram(g)) - z2 = @inferred(degree_histogram(g, indegree)) - z3 = @inferred(degree_histogram(g, outdegree)) - - @test z1 == z2 == z3 == Dict(4=>1, 3=>4) - - @test @inferred(neighbors(g, 2)) == @inferred(all_neighbors(g, 2)) == [1,3,5] - @test @inferred(common_neighbors(g, 1, 5)) == [2, 4] - - gsl = copy(g) - add_edge!(gsl, 3, 3) - add_edge!(gsl, 2, 2) - - @test @inferred(!has_self_loops(g)) - @test @inferred(has_self_loops(gsl)) - @test @inferred(num_self_loops(g)) == 0 - @test @inferred(num_self_loops(gsl)) == 2 - - @test @inferred(density(g)) == 0.8 - - @test eltype(squash(g)) == UInt8 + e2 = Edge(1, 3) + e3 = Edge(1, 4) + @test @inferred(is_ordered(e2)) + @test @inferred(!is_ordered(reverse(e3))) + + gx = Graph(10) + for g in testgraphs(gx) + add_vertices!(g, 5) + @test @inferred(nv(g)) == 15 + end + + g5w = WheelGraph(5) + for g in testgraphs(g5w) + @test @inferred(indegree(g, 1)) == @inferred(outdegree(g, 1)) == @inferred(degree(g, 1)) == 4 + @test @inferred(indegree(g)) == @inferred(outdegree(g)) == @inferred(degree(g)) == [4, 3, 3, 3, 3] + + @test @inferred(Δout(g)) == @inferred(Δin(g)) == @inferred(Δ(g)) == 4 + @test @inferred(δout(g)) == @inferred(δin(g)) == @inferred(δ(g)) == 3 + @test @inferred(weights(g)) == LightGraphs.DefaultDistance(nv(g)) + z1 = @inferred(degree_histogram(g)) + z2 = @inferred(degree_histogram(g, indegree)) + z3 = @inferred(degree_histogram(g, outdegree)) + + @test z1 == z2 == z3 == Dict(4 => 1, 3 => 4) + + @test @inferred(neighbors(g, 2)) == @inferred(all_neighbors(g, 2)) == [1, 3, 5] + @test @inferred(common_neighbors(g, 1, 5)) == [2, 4] + + gsl = copy(g) + add_edge!(gsl, 3, 3) + add_edge!(gsl, 2, 2) + + @test @inferred(!has_self_loops(g)) + @test @inferred(has_self_loops(gsl)) + @test @inferred(num_self_loops(g)) == 0 + @test @inferred(num_self_loops(gsl)) == 2 + + @test @inferred(density(g)) == 0.8 + + @test eltype(squash(g)) == UInt8 end g5wd = WheelDiGraph(5) for g in testdigraphs(g5wd) - @test @inferred(indegree(g,2)) == 2 - @test @inferred(outdegree(g,2)) == 1 - @test @inferred(degree(g,2)) == 3 - @test @inferred(indegree(g)) == [0,2,2,2,2] - @test @inferred(outdegree(g)) == [4,1,1,1,1] - @test @inferred(degree(g)) == [4,3,3,3,3] + @test @inferred(indegree(g, 2)) == 2 + @test @inferred(outdegree(g, 2)) == 1 + @test @inferred(degree(g, 2)) == 3 + @test @inferred(indegree(g)) == [0, 2, 2, 2, 2] + @test @inferred(outdegree(g)) == [4, 1, 1, 1, 1] + @test @inferred(degree(g)) == [4, 3, 3, 3, 3] @test @inferred(weights(g)) == LightGraphs.DefaultDistance(nv(g)) @test @inferred(Δout(g)) == @inferred(Δ(g)) == 4 @@ -60,12 +60,12 @@ for g in testgraphs(g5w) z1 = @inferred(degree_histogram(g)) z2 = @inferred(degree_histogram(g, indegree)) z3 = @inferred(degree_histogram(g, outdegree)) - @test z1 == Dict(4=>1, 3=>4) - @test z2 == Dict(0=>1, 2=>4) - @test z3 == Dict(4=>1, 1=>4) + @test z1 == Dict(4 => 1, 3 => 4) + @test z2 == Dict(0 => 1, 2 => 4) + @test z3 == Dict(4 => 1, 1 => 4) @test @inferred(neighbors(g, 2)) == [3] - @test Set(@inferred(all_neighbors(g, 2))) == Set([1,3,5]) + @test Set(@inferred(all_neighbors(g, 2))) == Set([1, 3, 5]) @test @inferred(common_neighbors(g, 1, 5)) == [2] gsl = copy(g) diff --git a/test/degeneracy.jl b/test/degeneracy.jl index 43e5327b2..012030fd5 100644 --- a/test/degeneracy.jl +++ b/test/degeneracy.jl @@ -1,5 +1,5 @@ @testset "Decomposition" begin - d = loadgraph(joinpath(testdir,"testdata","graph-decomposition.jgz")) + d = loadgraph(joinpath(testdir, "testdata", "graph-decomposition.jgz")) for g in testgraphs(d) corenum = @inferred(core_number(g)) diff --git a/test/digraph/cycles/hadwick-james.jl b/test/digraph/cycles/hadwick-james.jl index a02751b66..f3fce6a0d 100644 --- a/test/digraph/cycles/hadwick-james.jl +++ b/test/digraph/cycles/hadwick-james.jl @@ -46,8 +46,8 @@ # Almost fully connected DiGraph ex4 = DiGraph(9) - for (src, dest) in [(1,2),(1,5),(1,7),(1,8),(2,9),(3,4),(3,6), - (4,5),(4,7),(5,6),(6,7),(6,8),(7,9),(8,9)] + for (src, dest) in [(1, 2), (1, 5), (1, 7), (1, 8), (2, 9), (3, 4), (3, 6), + (4, 5), (4, 7), (5, 6), (6, 7), (6, 8), (7, 9), (8, 9)] add_edge!(ex4, src, dest) add_edge!(ex4, dest, src) end diff --git a/test/digraph/cycles/johnson.jl b/test/digraph/cycles/johnson.jl index 589b7ed72..70b72f9fb 100644 --- a/test/digraph/cycles/johnson.jl +++ b/test/digraph/cycles/johnson.jl @@ -1,9 +1,9 @@ @testset "Cycles" begin completedg = CompleteDiGraph(4) pathdg = PathDiGraph(5) - triangle = random_regular_graph(3,2) - quadrangle = random_regular_graph(4,2) - pentagon = random_regular_graph(5,2) + triangle = random_regular_graph(3, 2) + quadrangle = random_regular_graph(4, 2) + pentagon = random_regular_graph(5, 2) @test maxsimplecycles(pathdg) == 0 @test maxsimplecycles(completedg) == 20 @@ -13,7 +13,7 @@ @test length(simplecycles(completedg)) == 20 @test simplecycles(completedg) == @inferred(simplecycles_iter(completedg)) @test simplecyclescount(completedg) == 20 - @test simplecycleslength(completedg) == ([0,6,8,6], 20) + @test simplecycleslength(completedg) == ([0, 6, 8, 6], 20) @test simplecyclescount(pathdg) == 0 @test length(simplecycles(pathdg)) == 0 diff --git a/test/distance.jl b/test/distance.jl index 7946453f1..27487edc4 100644 --- a/test/distance.jl +++ b/test/distance.jl @@ -14,7 +14,7 @@ z = @inferred(eccentricity(g, distmx1)) @test z == [6.2, 4.2, 6.2] @test @inferred(diameter(z)) == diameter(g, distmx1) == 6.2 - @test @inferred(periphery(z)) == periphery(g, distmx1) == [1,3] + @test @inferred(periphery(z)) == periphery(g, distmx1) == [1, 3] @test @inferred(radius(z)) == radius(g, distmx1) == 4.2 @test @inferred(center(z)) == center(g, distmx1) == [2] end @@ -30,7 +30,7 @@ @test size(LightGraphs.DefaultDistance()) == (typemax(Int), typemax(Int)) d = @inferred(LightGraphs.DefaultDistance(3)) @test size(d) == (3, 3) - @test d[1,1] == getindex(d, 1, 1) == 1 + @test d[1, 1] == getindex(d, 1, 1) == 1 @test d[1:2, 1:2] == LightGraphs.DefaultDistance(2) @test d == transpose(d) == ctranspose(d) @test sprint(show, d) == diff --git a/test/edit_distance.jl b/test/edit_distance.jl index e8fe182ea..2e2a528e8 100644 --- a/test/edit_distance.jl +++ b/test/edit_distance.jl @@ -1,31 +1,31 @@ @testset "Edit distance" begin - gtri = random_regular_graph(3,2) - gquad = random_regular_graph(4,2) - gpent = random_regular_graph(5,2) + gtri = random_regular_graph(3, 2) + gquad = random_regular_graph(4, 2) + gpent = random_regular_graph(5, 2) for triangle in testgraphs(gtri), quadrangle in testgraphs(gquad), pentagon in testgraphs(gpent) - d, λ = @inferred(edit_distance(triangle, quadrangle, subst_cost=MinkowskiCost(1:3,1:4))) + d, λ = @inferred(edit_distance(triangle, quadrangle, subst_cost=MinkowskiCost(1:3, 1:4))) @test d == 1.0 - @test λ == Tuple[(1,1),(2,2),(3,3),(0,4)] + @test λ == Tuple[(1, 1), (2, 2), (3, 3), (0, 4)] - d, λ = @inferred(edit_distance(quadrangle, triangle, subst_cost=MinkowskiCost(1:4,1:3))) + d, λ = @inferred(edit_distance(quadrangle, triangle, subst_cost=MinkowskiCost(1:4, 1:3))) @test d == 1.0 - @test λ == Tuple[(1,1),(2,2),(3,3),(4,0)] + @test λ == Tuple[(1, 1), (2, 2), (3, 3), (4, 0)] - d, λ = @inferred(edit_distance(triangle, pentagon, subst_cost=MinkowskiCost(1:3,1:5))) + d, λ = @inferred(edit_distance(triangle, pentagon, subst_cost=MinkowskiCost(1:3, 1:5))) @test d == 2.0 - @test λ == Tuple[(1,1),(2,2),(3,3),(0,4),(0,5)] + @test λ == Tuple[(1, 1), (2, 2), (3, 3), (0, 4), (0, 5)] - d, λ = @inferred(edit_distance(pentagon, triangle, subst_cost=MinkowskiCost(1:5,1:3))) + d, λ = @inferred(edit_distance(pentagon, triangle, subst_cost=MinkowskiCost(1:5, 1:3))) @test d == 2.0 - @test λ == Tuple[(1,1),(2,2),(3,3),(4,0),(5,0)] + @test λ == Tuple[(1, 1), (2, 2), (3, 3), (4, 0), (5, 0)] end - cost = @inferred(MinkowskiCost(1:3,1:3)) - bcost = @inferred(BoundedMinkowskiCost(1:3,1:3)) - for i=1:3 - @test cost(i,i) == 0. - @test bcost(i,i) == 2/3 + cost = @inferred(MinkowskiCost(1:3, 1:3)) + bcost = @inferred(BoundedMinkowskiCost(1:3, 1:3)) + for i = 1:3 + @test cost(i, i) == 0. + @test bcost(i, i) == 2 / 3 end g1c = CompleteGraph(4) @@ -34,6 +34,6 @@ for g1 in testgraphs(g1c), g2 in testgraphs(g2c) d, λ = @inferred(edit_distance(g1, g2)) @test d == 2.0 - @test λ == Tuple[(1,1),(2,2),(3,3),(4,4)] + @test λ == Tuple[(1, 1), (2, 2), (3, 3), (4, 4)] end end diff --git a/test/flow/boykov_kolmogorov.jl b/test/flow/boykov_kolmogorov.jl index 03bfd6403..63ed9f5df 100644 --- a/test/flow/boykov_kolmogorov.jl +++ b/test/flow/boykov_kolmogorov.jl @@ -1,8 +1,8 @@ @testset "Boykov Kolmogorov" begin # construct graph gg = DiGraph(3) - add_edge!(gg,1,2) - add_edge!(gg,2,3) + add_edge!(gg, 1, 2) + add_edge!(gg, 2, 3) # source and sink terminals source, target = 1, 3 @@ -18,13 +18,13 @@ TREE[source] = T(1) TREE[target] = T(2) PARENT = zeros(T, 3) - A = [T(source),T(target)] + A = [T(source), T(target)] # see https://github.com/JuliaLang/julia/issues/21077 # @show("testing $g with eltype $T, residual_graph type is $(eltype(residual_graph)), flow_matrix type is $(eltype(flow_matrix)), capacity_matrix type is $(eltype(capacity_matrix))") path = LightGraphs.find_path!( residual_graph, source, target, flow_matrix, capacity_matrix, PARENT, TREE, A) - @test path == [1,2,3] + @test path == [1, 2, 3] end end diff --git a/test/flow/dinic.jl b/test/flow/dinic.jl index 1165c5769..75f014140 100644 --- a/test/flow/dinic.jl +++ b/test/flow/dinic.jl @@ -4,17 +4,17 @@ # Load custom dataset flow_edges = [ - (1,2,10),(1,3,5),(1,4,15),(2,3,4),(2,5,9), - (2,6,15),(3,4,4),(3,6,8),(4,7,16),(5,6,15), - (5,8,10),(6,7,15),(6,8,10),(7,3,6),(7,8,10) + (1, 2, 10), (1, 3, 5), (1, 4, 15), (2, 3, 4), (2, 5, 9), + (2, 6, 15), (3, 4, 4), (3, 6, 8), (4, 7, 16), (5, 6, 15), + (5, 8, 10), (6, 7, 15), (6, 8, 10), (7, 3, 6), (7, 8, 10) ] - capacity_matrix = zeros(Int ,nv(flow_graph) ,nv(flow_graph)) + capacity_matrix = zeros(Int, nv(flow_graph), nv(flow_graph)) for e in flow_edges - u,v,f = e - add_edge!(flow_graph,u,v) - capacity_matrix[u,v] = f + u, v, f = e + add_edge!(flow_graph, u, v) + capacity_matrix[u, v] = f end # Construct the residual graph @@ -46,11 +46,11 @@ # unreachable vertex (covers the case where a vertex isn't reachable from the source) h = copy(residual_graph) add_vertex!(h) - add_edge!(h, nv(residual_graph)+1, target) - capacity_matrix_ = vcat(hcat(capacity_matrix, zeros(Int, nv(residual_graph))), zeros(Int, 1, nv(residual_graph)+1)) - flow_graph_ = vcat(hcat(flow_matrix, zeros(Int, nv(residual_graph))), zeros(Int, 1, nv(residual_graph)+1)) + add_edge!(h, nv(residual_graph) + 1, target) + capacity_matrix_ = vcat(hcat(capacity_matrix, zeros(Int, nv(residual_graph))), zeros(Int, 1, nv(residual_graph) + 1)) + flow_graph_ = vcat(hcat(flow_matrix, zeros(Int, nv(residual_graph))), zeros(Int, 1, nv(residual_graph) + 1)) - @test @inferred(LightGraphs.blocking_flow(h, source, target, capacity_matrix_, flow_graph_ )) > 0 + @test @inferred(LightGraphs.blocking_flow(h, source, target, capacity_matrix_, flow_graph_)) > 0 #test with connected graph @test @inferred(LightGraphs.blocking_flow(residual_graph, source, target, capacity_matrix, flow_matrix)) > 0 diff --git a/test/flow/edmonds_karp.jl b/test/flow/edmonds_karp.jl index 5cacd1b5c..76f5f271b 100644 --- a/test/flow/edmonds_karp.jl +++ b/test/flow/edmonds_karp.jl @@ -4,60 +4,56 @@ # Load custom dataset flow_edges = [ - (1,2,10),(1,3,5),(1,4,15),(2,3,4),(2,5,9), - (2,6,15),(3,4,4),(3,6,8),(4,7,16),(5,6,15), - (5,8,10),(6,7,15),(6,8,10),(7,3,6),(7,8,10) + (1, 2, 10), (1, 3, 5), (1, 4, 15), (2, 3, 4), (2, 5, 9), + (2, 6, 15), (3, 4, 4), (3, 6, 8), (4, 7, 16), (5, 6, 15), + (5, 8, 10), (6, 7, 15), (6, 8, 10), (7, 3, 6), (7, 8, 10) ] for fg in (flow_graph, DiGraph{UInt8}(flow_graph), DiGraph{Int16}(flow_graph)) - - capacity_matrix = zeros(Int,8,8) - + capacity_matrix = zeros(Int, 8, 8) for e in flow_edges - u,v,f = e - add_edge!(fg,u,v) - capacity_matrix[u,v] = f + u, v, f = e + add_edge!(fg, u, v) + capacity_matrix[u, v] = f end + residual_graph = @inferred(LightGraphs.residual(fg)) - residual_graph = @inferred(LightGraphs.residual(fg)) - - # Test with default distances - @test @inferred(LightGraphs.edmonds_karp_impl(residual_graph, 1, 8, LightGraphs.DefaultCapacity(residual_graph)))[1] == 3 + # Test with default distances + @test @inferred(LightGraphs.edmonds_karp_impl(residual_graph, 1, 8, LightGraphs.DefaultCapacity(residual_graph)))[1] == 3 - # Test with capacity matrix - @test @inferred(LightGraphs.edmonds_karp_impl(residual_graph,1,8,capacity_matrix))[1] == 28 + # Test with capacity matrix + @test @inferred(LightGraphs.edmonds_karp_impl(residual_graph, 1, 8, capacity_matrix))[1] == 28 - # Test the types of the values returned by fetch_path - function test_find_path_types(residual_graph, s, t, flow_matrix, capacity_matrix) - v, P, S, flag = LightGraphs.fetch_path(residual_graph, s, t, flow_matrix, capacity_matrix) - @test typeof(P) == Vector{Int} - @test typeof(S) == Vector{Int} - @test typeof(flag) == Int - @test typeof(v) == eltype(residual_graph) - end - - # Test the value of the flags returned. - function test_find_path_disconnected(residual_graph, s, t, flow_matrix, capacity_matrix) - h = copy(residual_graph) - for dst in collect(neighbors(residual_graph, s)) - rem_edge!(residual_graph, s, dst) - end - v, P, S, flag = LightGraphs.fetch_path(residual_graph, s, t, flow_matrix, capacity_matrix) - @test flag == 1 - for dst in collect(neighbors(h, t)) - rem_edge!(h, t, dst) - end - v, P, S, flag = LightGraphs.fetch_path(h, s, t, flow_matrix, capacity_matrix) - @test flag == 0 - for i in collect(in_neighbors(h, t)) - rem_edge!(h, i, t) - end - v, P, S, flag = LightGraphs.fetch_path(h, s, t, flow_matrix, capacity_matrix) - @test flag == 2 - end + # Test the types of the values returned by fetch_path + function test_find_path_types(residual_graph, s, t, flow_matrix, capacity_matrix) + v, P, S, flag = LightGraphs.fetch_path(residual_graph, s, t, flow_matrix, capacity_matrix) + @test typeof(P) == Vector{Int} + @test typeof(S) == Vector{Int} + @test typeof(flag) == Int + @test typeof(v) == eltype(residual_graph) + end - flow_matrix = zeros(Int, nv(residual_graph), nv(residual_graph)) - test_find_path_types(residual_graph, 1,8, flow_matrix, capacity_matrix) - test_find_path_disconnected(residual_graph, 1, 8, flow_matrix, capacity_matrix) + # Test the value of the flags returned. + function test_find_path_disconnected(residual_graph, s, t, flow_matrix, capacity_matrix) + h = copy(residual_graph) + for dst in collect(neighbors(residual_graph, s)) + rem_edge!(residual_graph, s, dst) + end + v, P, S, flag = LightGraphs.fetch_path(residual_graph, s, t, flow_matrix, capacity_matrix) + @test flag == 1 + for dst in collect(neighbors(h, t)) + rem_edge!(h, t, dst) + end + v, P, S, flag = LightGraphs.fetch_path(h, s, t, flow_matrix, capacity_matrix) + @test flag == 0 + for i in collect(in_neighbors(h, t)) + rem_edge!(h, i, t) + end + v, P, S, flag = LightGraphs.fetch_path(h, s, t, flow_matrix, capacity_matrix) + @test flag == 2 + end + flow_matrix = zeros(Int, nv(residual_graph), nv(residual_graph)) + test_find_path_types(residual_graph, 1, 8, flow_matrix, capacity_matrix) + test_find_path_disconnected(residual_graph, 1, 8, flow_matrix, capacity_matrix) end end diff --git a/test/flow/maximum_flow.jl b/test/flow/maximum_flow.jl index fe7731f89..dd6b6915f 100644 --- a/test/flow/maximum_flow.jl +++ b/test/flow/maximum_flow.jl @@ -4,53 +4,53 @@ # Graph with 8 vertices (8, [ - (1,2,10),(1,3,5),(1,4,15),(2,3,4),(2,5,9), - (2,6,15),(3,4,4),(3,6,8),(4,7,16),(5,6,15), - (5,8,10),(6,7,15),(6,8,10),(7,3,6),(7,8,10) + (1, 2, 10), (1, 3, 5), (1, 4, 15), (2, 3, 4), (2, 5, 9), + (2, 6, 15), (3, 4, 4), (3, 6, 8), (4, 7, 16), (5, 6, 15), + (5, 8, 10), (6, 7, 15), (6, 8, 10), (7, 3, 6), (7, 8, 10) ], - 1,8, # source/target - 3, # answer for default capacity - 28, # answer for custom capacity - 15,5 # answer for restricted capacity/restriction + 1, 8, # source/target + 3, # answer for default capacity + 28, # answer for custom capacity + 15, 5 # answer for restricted capacity/restriction ), # Graph with 6 vertices (6, [ - (1,2,9),(1,3,9),(2,3,10),(2,4,8),(3,4,1), - (3,5,3),(5,4,8),(4,6,10),(5,6,7) + (1, 2, 9), (1, 3, 9), (2, 3, 10), (2, 4, 8), (3, 4, 1), + (3, 5, 3), (5, 4, 8), (4, 6, 10), (5, 6, 7) ], - 1,6, # source/target + 1, 6, # source/target 2, # answer for default capacity 12, # answer for custom capacity - 8,5 # answer for restricted capacity/restriction + 8, 5 # answer for restricted capacity/restriction ) ] - for (nvertices,flow_edges,s,t,fdefault,fcustom,frestrict,caprestrict) in graphs + for (nvertices, flow_edges, s, t, fdefault, fcustom, frestrict, caprestrict) in graphs flow_graph = DiGraph(nvertices) for g in testdigraphs(flow_graph) - capacity_matrix = zeros(Int,nvertices,nvertices) + capacity_matrix = zeros(Int, nvertices, nvertices) for e in flow_edges - u,v,f = e - add_edge!(g,u,v) - capacity_matrix[u,v] = f + u, v, f = e + add_edge!(g, u, v) + capacity_matrix[u, v] = f end # Test DefaultCapacity d = @inferred(LightGraphs.DefaultCapacity(g)) T = eltype(d) @test typeof(d) <: AbstractMatrix{T} - @test d[s,t] == 0 - @test size(d) == (nvertices,nvertices) + @test d[s, t] == 0 + @test size(d) == (nvertices, nvertices) @test typeof(transpose(d)) <: LightGraphs.DefaultCapacity @test typeof(ctranspose(d)) <: LightGraphs.DefaultCapacity # Test all algorithms - type instability in PushRelabel #553 for ALGO in [EdmondsKarpAlgorithm, DinicAlgorithm, BoykovKolmogorovAlgorithm, PushRelabelAlgorithm] - @test maximum_flow(g,s,t,algorithm=ALGO())[1] == fdefault - @test maximum_flow(g,s,t,capacity_matrix,algorithm=ALGO())[1] == fcustom - @test maximum_flow(g,s,t,capacity_matrix,algorithm=ALGO(),restriction=caprestrict)[1] == frestrict + @test maximum_flow(g, s, t, algorithm=ALGO())[1] == fdefault + @test maximum_flow(g, s, t, capacity_matrix, algorithm=ALGO())[1] == fcustom + @test maximum_flow(g, s, t, capacity_matrix, algorithm=ALGO(), restriction=caprestrict)[1] == frestrict end end end diff --git a/test/flow/push_relabel.jl b/test/flow/push_relabel.jl index f9525f94c..ba35d2ea7 100644 --- a/test/flow/push_relabel.jl +++ b/test/flow/push_relabel.jl @@ -4,17 +4,17 @@ # Load custom dataset flow_edges = [ - (1,2,10),(1,3,5),(1,4,15),(2,3,4),(2,5,9), - (2,6,15),(3,4,4),(3,6,8),(4,7,16),(5,6,15), - (5,8,10),(6,7,15),(6,8,10),(7,3,6),(7,8,10) + (1, 2, 10), (1, 3, 5), (1, 4, 15), (2, 3, 4), (2, 5, 9), + (2, 6, 15), (3, 4, 4), (3, 6, 8), (4, 7, 16), (5, 6, 15), + (5, 8, 10), (6, 7, 15), (6, 8, 10), (7, 3, 6), (7, 8, 10) ] - capacity_matrix = zeros(Int,8,8) + capacity_matrix = zeros(Int, 8, 8) for e in flow_edges - u,v,f = e - add_edge!(flow_graph,u,v) - capacity_matrix[u,v] = f + u, v, f = e + add_edge!(flow_graph, u, v) + capacity_matrix[u, v] = f end for g in testdigraphs(flow_graph) residual_graph = @inferred(LightGraphs.residual(g)) @@ -38,10 +38,10 @@ flow_matrix = zeros(Int, 8, 8) @test @inferred(LightGraphs.push_flow!(residual_graph, 1, 2, capacity_matrix, flow_matrix, excess, height, active, Q)) == nothing @test length(Q) == 1 - @test flow_matrix[1,2] == 10 + @test flow_matrix[1, 2] == 10 @test @inferred(LightGraphs.push_flow!(residual_graph, 2, 3, capacity_matrix, flow_matrix, excess, height, active, Q)) == nothing @test length(Q) == 1 - @test flow_matrix[2,3] == 0 + @test flow_matrix[2, 3] == 0 # Test gap Q = Array{Int,1}() @@ -83,12 +83,12 @@ @test LightGraphs.push_relabel(residual_graph, 1, 8, capacity_matrix)[1] == 28 end # Non regression test added for #448 - M448 =[0 1 0 0 1 1 - 1 0 0 0 1 0 - 0 0 0 1 0 0 - 0 0 0 0 0 0 - 1 0 1 0 0 1 - 0 0 0 0 1 0] + M448 = [0 1 0 0 1 1 + 1 0 0 0 1 0 + 0 0 0 1 0 0 + 0 0 0 0 0 0 + 1 0 1 0 0 1 + 0 0 0 0 1 0] g448 = DiGraph(M448) @test maximum_flow(g448, 1, 2, M448, algorithm=PushRelabelAlgorithm())[1] == 1 end diff --git a/test/generators/binomial.jl b/test/generators/binomial.jl index 84799002c..37a741157 100644 --- a/test/generators/binomial.jl +++ b/test/generators/binomial.jl @@ -19,7 +19,7 @@ function -(s::SummaryStats, t::SummaryStats) s.q75 - t.q75, s.max - t.max) end -function binomial_test(n,p,s) +function binomial_test(n, p, s) drand = rand(Binomial(n, p), s) lrand = Int64[randbn(n, p) for i in 1:s] @@ -42,7 +42,7 @@ n = 10000 p = 0.3 s = 100000 -for (n,p,s) in [(100, 0.3, 1000), (1000, 0.8, 1000), (10000, 0.25, 1000)] - binomial_test(n,p,s) +for (n, p, s) in [(100, 0.3, 1000), (1000, 0.8, 1000), (10000, 0.25, 1000)] + binomial_test(n, p, s) end diff --git a/test/generators/euclideangraphs.jl b/test/generators/euclideangraphs.jl index 27be1b6e0..39d66c6f9 100644 --- a/test/generators/euclideangraphs.jl +++ b/test/generators/euclideangraphs.jl @@ -3,16 +3,16 @@ d = 2 g, weights, points = @inferred(euclidean_graph(N, d)) @test nv(g) == N - @test ne(g) == N*(N-1) ÷ 2 - @test (d,N) == size(points) - @test maximum(x->x[2], weights) <= sqrt(d) - @test minimum(x->x[2], weights) >= 0 + @test ne(g) == N * (N - 1) ÷ 2 + @test (d, N) == size(points) + @test maximum(x -> x[2], weights) <= sqrt(d) + @test minimum(x -> x[2], weights) >= 0 @test maximum(points) <= 1 @test minimum(points) >= 0. g, weights, points = @inferred(euclidean_graph(N, d, bc=:periodic)) - @test maximum(x->x[2], weights) <= sqrt(d/2) - @test minimum(x->x[2], weights) >= 0. + @test maximum(x -> x[2], weights) <= sqrt(d / 2) + @test minimum(x -> x[2], weights) >= 0. @test maximum(points) <= 1 @test minimum(points) >= 0. diff --git a/test/generators/staticgraphs.jl b/test/generators/staticgraphs.jl index 2a4836aa8..d8803d81e 100644 --- a/test/generators/staticgraphs.jl +++ b/test/generators/staticgraphs.jl @@ -29,20 +29,20 @@ g = @inferred(WheelGraph(5)) @test nv(g) == 5 && ne(g) == 8 - g = @inferred(Grid([3,3,4])) - @test nv(g) == 3*3*4 + g = @inferred(Grid([3, 3, 4])) + @test nv(g) == 3 * 3 * 4 @test ne(g) == 75 @test Δ(g) == 6 @test δ(g) == 3 - g = @inferred(Grid([3,3,4], periodic=true)) - @test nv(g) == 3*3*4 + g = @inferred(Grid([3, 3, 4], periodic=true)) + @test nv(g) == 3 * 3 * 4 @test ne(g) == 108 @test Δ(g) == 6 @test δ(g) == 6 - g = @inferred(CliqueGraph(3,5)) + g = @inferred(CliqueGraph(3, 5)) @test nv(g) == 15 && ne(g) == 20 @test g[1:3] == CompleteGraph(3) @@ -57,49 +57,49 @@ # [5 7]; # [6 7] # ] - I = [1,1,1,2,2,3,3,4,4,4,4,5,5,5,6,6,6,7,7,7,8,8,9,9] - J = [2,3,4,1,5,1,6,1,5,6,7,2,4,8,3,4,9,4,8,9,5,7,6,7] + I = [1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9] + J = [2, 3, 4, 1, 5, 1, 6, 1, 5, 6, 7, 2, 4, 8, 3, 4, 9, 4, 8, 9, 5, 7, 6, 7] V = ones(Int, length(I)) - Adj = sparse(I,J,V) + Adj = sparse(I, J, V) @test Adj == sparse(g) g = @inferred(DoubleBinaryTree(3)) - # [[3,2,8] - # [4,1,5] - # [1,6,7] + # [[3, 2, 8] + # [4, 1, 5] + # [1, 6, 7] # [2] # [2] # [3] # [3] - # [10,9,1] - # [11,8,12] - # [8,13,14] + # [10, 9, 1] + # [11, 8, 12] + # [8, 13, 14] # [9] # [9] # [10] # [10]] - I = [1,1,1,2,2,2,3,3,3,4,5,6,7,8,8,8,9,9,9,10,10,10,11,12,13,14] - J = [3,2,8,4,1,5,1,6,7,2,2,3,3,10,9,1,11,8,12,8,13,14,9,9,10,10] + I = [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 12, 13, 14] + J = [3, 2, 8, 4, 1, 5, 1, 6, 7, 2, 2, 3, 3, 10, 9, 1, 11, 8, 12, 8, 13, 14, 9, 9, 10, 10] V = ones(Int, length(I)) - Adj = sparse(I,J,V) + Adj = sparse(I, J, V) @test Adj == sparse(g) rg3 = @inferred(RoachGraph(3)) # [3] # [4] - # [1,5] - # [2,6] - # [3,7] - # [4,8] - # [9,8,5] - # [10,7,6] - # [11,10,7] - # [8,9,12] - # [9,12] - # [10,11] - I = [ 1,2,3,3,4,4,5,5,6,6,7,7,7,8,8,8,9,9,9,10,10,10,11,11,12,12 ] - J = [ 3,4,1,5,2,6,3,7,4,8,9,8,5,10,7,6,11,10,7,8,9,12,9,12,10,11 ] + # [1, 5] + # [2, 6] + # [3, 7] + # [4, 8] + # [9, 8, 5] + # [10, 7, 6] + # [11, 10, 7] + # [8, 9, 12] + # [9, 12] + # [10, 11] + I = [1, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10, 11, 11, 12, 12] + J = [3, 4, 1, 5, 2, 6, 3, 7, 4, 8, 9, 8, 5, 10, 7, 6, 11, 10, 7, 8, 9, 12, 9, 12, 10, 11] V = ones(Int, length(I)) - Adj = sparse(I,J,V) + Adj = sparse(I, J, V) @test Adj == sparse(rg3) end diff --git a/test/graphtypes/simplegraphs/simpleedge.jl b/test/graphtypes/simplegraphs/simpleedge.jl index f1c937595..a296a019d 100644 --- a/test/graphtypes/simplegraphs/simpleedge.jl +++ b/test/graphtypes/simplegraphs/simpleedge.jl @@ -1,11 +1,11 @@ import LightGraphs.SimpleGraphs.SimpleEdge @testset "SimpleEdge" begin - e = SimpleEdge(1,2) - re = SimpleEdge(2,1) + e = SimpleEdge(1, 2) + re = SimpleEdge(2, 1) for s in [0x01, UInt16(1), 1] T = typeof(s) - d = s+one(T) + d = s + one(T) p = Pair(s, d) ep1 = SimpleEdge(p) diff --git a/test/graphtypes/simplegraphs/simpleedgeiter.jl b/test/graphtypes/simplegraphs/simpleedgeiter.jl index 5c47bc0ef..fc54ed12e 100644 --- a/test/graphtypes/simplegraphs/simpleedgeiter.jl +++ b/test/graphtypes/simplegraphs/simpleedgeiter.jl @@ -1,10 +1,10 @@ @testset "SimpleEdgeIter" begin - ga = @inferred(SimpleGraph(10,20; seed=1)) - gb = @inferred(SimpleGraph(10,20; seed=1)) - @test sprint(show,edges(ga)) == "SimpleEdgeIter 20" + ga = @inferred(SimpleGraph(10, 20; seed=1)) + gb = @inferred(SimpleGraph(10, 20; seed=1)) + @test sprint(show, edges(ga)) == "SimpleEdgeIter 20" @test sprint(show, start(edges(ga))) == "SimpleEdgeIterState [1, 1, false]" - @test length(collect(edges(Graph(0,0)))) == 0 + @test length(collect(edges(Graph(0, 0)))) == 0 @test @inferred(edges(ga)) == edges(gb) @test @inferred(edges(ga)) == collect(Edge, edges(gb)) @@ -14,8 +14,8 @@ @test @inferred(eltype(edges(ga))) == eltype(typeof(edges(ga))) == SimpleEdge - ga = @inferred(SimpleDiGraph(10,20; seed=1)) - gb = @inferred(SimpleDiGraph(10,20; seed=1)) + ga = @inferred(SimpleDiGraph(10, 20; seed=1)) + gb = @inferred(SimpleDiGraph(10, 20; seed=1)) @test @inferred(edges(ga)) == edges(gb) @test @inferred(edges(ga)) == collect(SimpleEdge, edges(gb)) @test collect(SimpleEdge, edges(gb)) == edges(ga) @@ -34,7 +34,7 @@ @test es.s == 2 @test es.di == 1 - @test [e for e in eit] == [Edge(2, 3), Edge(3, 10), Edge(5,10)] + @test [e for e in eit] == [Edge(2, 3), Edge(3, 10), Edge(5, 10)] ga = SimpleDiGraph(10) add_edge!(ga, 3, 2) @@ -50,6 +50,6 @@ @test [e for e in eit] == [ SimpleEdge(3, 2), SimpleEdge(3, 10), - SimpleEdge(5,10), SimpleEdge(10,3) + SimpleEdge(5, 10), SimpleEdge(10, 3) ] end diff --git a/test/graphtypes/simplegraphs/simplegraphs.jl b/test/graphtypes/simplegraphs/simplegraphs.jl index 16ca31ab2..330134426 100644 --- a/test/graphtypes/simplegraphs/simplegraphs.jl +++ b/test/graphtypes/simplegraphs/simplegraphs.jl @@ -44,10 +44,10 @@ struct DummySimpleGraph <: AbstractSimpleGraph end gx = PathGraph(4) for g in testgraphs(gx) @test @inferred(vertices(g)) == 1:4 - @test Edge(2,3) in edges(g) + @test Edge(2, 3) in edges(g) @test @inferred(nv(g)) == 4 @test @inferred(fadj(g)) == badj(g) == adj(g) == g.fadjlist - @test @inferred(fadj(g,2)) == badj(g,2) == adj(g,2) == g.fadjlist[2] + @test @inferred(fadj(g, 2)) == badj(g, 2) == adj(g, 2) == g.fadjlist[2] @test @inferred(has_edge(g, 2, 3)) @test @inferred(!has_edge(g, 20, 3)) @@ -55,15 +55,15 @@ struct DummySimpleGraph <: AbstractSimpleGraph end @test @inferred(has_edge(g, 3, 2)) gc = copy(g) - @test @inferred(add_edge!(gc, 4=>1)) && gc == CycleGraph(4) - @test @inferred(has_edge(gc, 4=>1)) && has_edge(gc, 0x04=>0x01) + @test @inferred(add_edge!(gc, 4 => 1)) && gc == CycleGraph(4) + @test @inferred(has_edge(gc, 4 => 1)) && has_edge(gc, 0x04 => 0x01) gc = copy(g) - @test @inferred(add_edge!(gc, (4,1))) && gc == CycleGraph(4) - @test @inferred(has_edge(gc, (4,1))) && has_edge(gc, (0x04, 0x01)) + @test @inferred(add_edge!(gc, (4, 1))) && gc == CycleGraph(4) + @test @inferred(has_edge(gc, (4, 1))) && has_edge(gc, (0x04, 0x01)) gc = copy(g) @test add_edge!(gc, 4, 1) && gc == CycleGraph(4) - @test @inferred(in_neighbors(g, 2)) == @inferred(out_neighbors(g, 2)) == @inferred(neighbors(g,2)) == [1,3] + @test @inferred(in_neighbors(g, 2)) == @inferred(out_neighbors(g, 2)) == @inferred(neighbors(g, 2)) == [1, 3] @test @inferred(add_vertex!(gc)) # out of order, but we want it for issubset @test @inferred(g ⊆ gc) @test @inferred(has_vertex(gc, 5)) @@ -79,7 +79,7 @@ struct DummySimpleGraph <: AbstractSimpleGraph end # concrete tests below - @test @inferred(eltype(g)) == eltype(fadj(g,1)) == eltype(nv(g)) + @test @inferred(eltype(g)) == eltype(fadj(g, 1)) == eltype(nv(g)) T = @inferred(eltype(g)) @test @inferred(nv(SimpleGraph{T}(6))) == 6 @@ -105,8 +105,8 @@ struct DummySimpleGraph <: AbstractSimpleGraph end gdx = PathDiGraph(4) for g in testdigraphs(gdx) @test @inferred(vertices(g)) == 1:4 - @test Edge(2,3) in edges(g) - @test !(Edge(3,2) in edges(g)) + @test Edge(2, 3) in edges(g) + @test !(Edge(3, 2) in edges(g)) @test @inferred(nv(g)) == 4 @test @inferred(fadj(g)[2]) == fadj(g, 2) == [3] @test @inferred(badj(g)[2]) == badj(g, 2) == [1] @@ -118,16 +118,16 @@ struct DummySimpleGraph <: AbstractSimpleGraph end @test @inferred(!has_edge(g, 2, 30)) gc = copy(g) - @test @inferred(add_edge!(gc, 4=>1)) && gc == CycleDiGraph(4) - @test @inferred(has_edge(gc, 4=>1)) && has_edge(gc, 0x04=>0x01) + @test @inferred(add_edge!(gc, 4 => 1)) && gc == CycleDiGraph(4) + @test @inferred(has_edge(gc, 4 => 1)) && has_edge(gc, 0x04 => 0x01) gc = copy(g) - @test @inferred(add_edge!(gc, (4,1))) && gc == CycleDiGraph(4) - @test @inferred(has_edge(gc, (4,1))) && has_edge(gc, (0x04, 0x01)) + @test @inferred(add_edge!(gc, (4, 1))) && gc == CycleDiGraph(4) + @test @inferred(has_edge(gc, (4, 1))) && has_edge(gc, (0x04, 0x01)) gc = @inferred(copy(g)) @test @inferred(add_edge!(gc, 4, 1)) && gc == CycleDiGraph(4) @test @inferred(in_neighbors(g, 2)) == [1] - @test @inferred(out_neighbors(g, 2)) == @inferred(neighbors(g,2)) == [3] + @test @inferred(out_neighbors(g, 2)) == @inferred(neighbors(g, 2)) == [3] @test @inferred(add_vertex!(gc)) # out of order, but we want it for issubset @test @inferred(g ⊆ gc) @test @inferred(has_vertex(gc, 5)) @@ -144,7 +144,7 @@ struct DummySimpleGraph <: AbstractSimpleGraph end # concrete tests below - @test @inferred(eltype(g)) == eltype(@inferred(fadj(g,1))) == eltype(nv(g)) + @test @inferred(eltype(g)) == eltype(@inferred(fadj(g, 1))) == eltype(nv(g)) T = @inferred(eltype(g)) @test @inferred(nv(SimpleDiGraph{T}(6))) == 6 diff --git a/test/interface.jl b/test/interface.jl index 3ecf45fbc..28adebcd0 100644 --- a/test/interface.jl +++ b/test/interface.jl @@ -10,29 +10,29 @@ mutable struct DummyEdge <: AbstractEdge end @test_throws ErrorException is_directed(DummyGraph) for edgefun in [src, dst, Pair, Tuple, reverse] - @test_throws ErrorException edgefun(dummyedge) + @test_throws ErrorException edgefun(dummyedge) end - for edgefun2edges in [ == ] - @test_throws ErrorException edgefun2edges(dummyedge, dummyedge) + for edgefun2edges in [==] + @test_throws ErrorException edgefun2edges(dummyedge, dummyedge) end for graphfunbasic in [ - nv, ne, vertices, edges, is_directed, - add_vertex!, edgetype, eltype, zero - ] - @test_throws ErrorException graphfunbasic(dummygraph) + nv, ne, vertices, edges, is_directed, + add_vertex!, edgetype, eltype, zero + ] + @test_throws ErrorException graphfunbasic(dummygraph) end for graphfun1int in [ - rem_vertex!, has_vertex, in_neighbors, out_neighbors - ] - @test_throws ErrorException graphfun1int(dummygraph, 1) + rem_vertex!, has_vertex, in_neighbors, out_neighbors + ] + @test_throws ErrorException graphfun1int(dummygraph, 1) end for graphfunedge in [ - has_edge, add_edge!, rem_edge! + has_edge, add_edge!, rem_edge! ] - @test_throws ErrorException graphfunedge(dummygraph, dummyedge) + @test_throws ErrorException graphfunedge(dummygraph, dummyedge) end end # testset diff --git a/test/linalg/graphmatrices.jl b/test/linalg/graphmatrices.jl index 6d22bc26b..8deaef0ff 100644 --- a/test/linalg/graphmatrices.jl +++ b/test/linalg/graphmatrices.jl @@ -25,9 +25,9 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth @test adjmat.D == vec(sum(mat, 1)) @test adjmat.A == mat @test convert(SparseMatrix{Float64}, adjmat) == sparse(mat) - converttest(SparseMatrix{Float64},stochmat) - converttest(SparseMatrix{Float64},adjhat) - converttest(SparseMatrix{Float64},avgmat) + converttest(SparseMatrix{Float64}, stochmat) + converttest(SparseMatrix{Float64}, adjhat) + converttest(SparseMatrix{Float64}, avgmat) @test isa(CombinatorialAdjacency(adjmat), CombinatorialAdjacency) @test isa(CombinatorialAdjacency(avgmat), CombinatorialAdjacency) @test prescalefactor(adjhat) == postscalefactor(adjhat) @@ -47,18 +47,18 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth @test typeof(AveragingAdjacency(adj)) <: AveragingAdjacency @test typeof(adjacency(lapl)) <: CombinatorialAdjacency - converttest(SparseMatrix{Float64},lapl) + converttest(SparseMatrix{Float64}, lapl) adjmat, stochmat, adjhat, avgmat = constructors(mat) @test typeof(adjacency(lapl)) <: CombinatorialAdjacency stochlapl = StochasticLaplacian(StochasticAdjacency(adjmat)) - @test typeof(adjacency(stochlapl)) <: StochasticAdjacency + @test typeof(adjacency(stochlapl)) <: StochasticAdjacency averaginglapl = AveragingLaplacian(AveragingAdjacency(adjmat)) - @test typeof(adjacency(averaginglapl)) <: AveragingAdjacency + @test typeof(adjacency(averaginglapl)) <: AveragingAdjacency normalizedlapl = NormalizedLaplacian(NormalizedAdjacency(adjmat)) - @test typeof(adjacency(normalizedlapl)) <: NormalizedAdjacency - @test !( typeof(adjacency(normalizedlapl)) <: CombinatorialAdjacency) + @test typeof(adjacency(normalizedlapl)) <: NormalizedAdjacency + @test !(typeof(adjacency(normalizedlapl)) <: CombinatorialAdjacency) #constructors that fail. @test_throws MethodError CombinatorialAdjacency(lapl) @@ -67,7 +67,7 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth @test_throws MethodError AveragingLaplacian(lapl) @test_throws MethodError convert(CombinatorialAdjacency, lapl) L = convert(SparseMatrix{Float64}, lapl) - @test sum(abs, (sum(L,1))) == 0 + @test sum(abs, (sum(L, 1))) == 0 end function test_accessors(mat, n) @@ -80,7 +80,7 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth for m in (adjmat, stochmat, adjhat, avgmat) @test degrees(m) == dv @test eltype(m) == eltype(m.A) - @test size(m) == (n,n) + @test size(m) == (n, n) #@fact length(m) --> length(adjmat.A) end end @@ -89,11 +89,11 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth adjmat, stochmat, adjhat, avgmat = constructors(mat) lapl = CombinatorialLaplacian(adjmat) onevec = ones(Float64, n) - v = adjmat*ones(Float64, n) - @test sum(abs, (adjmat*onevec)) > 0.0 + v = adjmat * ones(Float64, n) + @test sum(abs, (adjmat * onevec)) > 0.0 @test sum(abs, ((stochmat * onevec) / sum(onevec))) ≈ 1.0 - @test sum(abs, (lapl*onevec)) == 0 - g(a) = sum(abs, (sum(sparse(a),1))) + @test sum(abs, (lapl * onevec)) == 0 + g(a) = sum(abs, (sum(sparse(a), 1))) @test g(lapl) == 0 @test g(NormalizedLaplacian(adjhat)) > 1e-13 @test g(StochasticLaplacian(stochmat)) > 1e-13 @@ -107,7 +107,7 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth @test eigs(lhat, which=:LR)[1][1] < 2.0 + 1e-9 end - function test_other(mat, n ) + function test_other(mat, n) adjmat = CombinatorialAdjacency(mat) lapl = CombinatorialLaplacian(CombinatorialAdjacency(mat)) @test size(lapl, 1) == n @@ -133,7 +133,7 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth end end - function test_symmetry(mat,n) + function test_symmetry(mat, n) adjmat = CombinatorialAdjacency(mat) lapl = CombinatorialLaplacian(CombinatorialAdjacency(mat)) @test size(lapl, 1) == n @@ -156,27 +156,27 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth adjmat = CombinatorialAdjacency(mat) ahatp = PunchedAdjacency(adjmat) y = ahatp * perron(ahatp) - @test dot(y, ahatp.perron) ≈ 0.0 atol=1.0e-8 - @test sum(abs, y) ≈ 0.0 atol=1.0e-8 + @test dot(y, ahatp.perron) ≈ 0.0 atol = 1.0e-8 + @test sum(abs, y) ≈ 0.0 atol = 1.0e-8 eval, evecs = eigs(ahatp, which=:LM) - @test eval[1]-1 <= 0 - @test dot(perron(ahatp), evecs[:,1]) ≈ 0.0 atol=1e-8 + @test eval[1] - 1 <= 0 + @test dot(perron(ahatp), evecs[:, 1]) ≈ 0.0 atol = 1e-8 ahat = ahatp.A @test isa(ahat, NormalizedAdjacency) z = ahatp * perron(ahat) - @test norm(z) ≈ 0.0 atol=1e-8 + @test norm(z) ≈ 0.0 atol = 1e-8 end n = 10 - mat = sparse(spones(sprand(n,n,0.3))) + mat = sparse(spones(sprand(n, n, 0.3))) test_adjacency(mat) test_laplacian(mat) test_accessors(mat, n) - mat = symmetrize(sparse(spones(sprand(n,n,0.3)))) + mat = symmetrize(sparse(spones(sprand(n, n, 0.3)))) test_arithmetic(mat, n) test_other(mat, n) test_symmetry(mat, n) @@ -188,8 +188,8 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth function stationarydistribution(R::StochasticAdjacency; kwargs...) er = eigs(R, nev=1, which=:LR; kwargs...) l1 = er[1][1] - abs(l1 -1) < 1e-8 || error("failed to compute stationary distribution") - p = real(er[2][:,1]) + abs(l1 - 1) < 1e-8 || error("failed to compute stationary distribution") + p = real(er[2][:, 1]) if p[1] < 0 for i in 1:length(p) p[i] = -p[i] @@ -205,11 +205,11 @@ export test_adjacency, test_laplacian, test_accessors, test_arithmetic, test_oth # Random walk demo n = 100 - p = 16/n - M = sprand(n,n, p) + p = 16 / n + M = sprand(n, n, p) M.nzval[:] = 1.0 A = CombinatorialAdjacency(M) sd = stationarydistribution(A; ncv=10) - @test all(sd.>=0) + @test all(sd .>= 0) end end diff --git a/test/linalg/spectral.jl b/test/linalg/spectral.jl index 9d1bc3d85..ae5a36e8a 100644 --- a/test/linalg/spectral.jl +++ b/test/linalg/spectral.jl @@ -10,50 +10,50 @@ full(nbt::Nonbacktracking) = full(sparse(nbt)) g5 = DiGraph(4) for g in testgraphs(g3) @test adjacency_matrix(g, Bool) == adjacency_matrix(g, :out, Bool) - @test adjacency_matrix(g)[3,2] == 1 - @test adjacency_matrix(g)[2,4] == 0 - @test laplacian_matrix(g)[3,2] == -1 - @test laplacian_matrix(g)[1,3] == 0 + @test adjacency_matrix(g)[3, 2] == 1 + @test adjacency_matrix(g)[2, 4] == 0 + @test laplacian_matrix(g)[3, 2] == -1 + @test laplacian_matrix(g)[1, 3] == 0 @test laplacian_spectrum(g)[5] == 3.6180339887498945 @test adjacency_spectrum(g)[1] == -1.732050807568878 end - add_edge!(g5,1,2); add_edge!(g5,2,3); add_edge!(g5,1,3); add_edge!(g5,3,4) + add_edge!(g5, 1, 2); add_edge!(g5, 2, 3); add_edge!(g5, 1, 3); add_edge!(g5, 3, 4) for g in testdigraphs(g5) @test adjacency_matrix(g, Bool) == adjacency_matrix(g, :out, Bool) - @test laplacian_spectrum(g)[3] == laplacian_spectrum(g,:both)[3] == 3.0 - @test laplacian_spectrum(g,:in)[3] == 1.0 - @test laplacian_spectrum(g,:out)[3] == 1.0 + @test laplacian_spectrum(g)[3] == laplacian_spectrum(g, :both)[3] == 3.0 + @test laplacian_spectrum(g, :in)[3] == 1.0 + @test laplacian_spectrum(g, :out)[3] == 1.0 end # check adjacency matrices with self loops gx = copy(g3) - add_edge!(gx,1,1) + add_edge!(gx, 1, 1) for g in testgraphs(gx) - @test adjacency_matrix(g)[1,1] == 2 + @test adjacency_matrix(g)[1, 1] == 2 end g = copy(g5) - add_edge!(g,1,1) - @test adjacency_matrix(g)[1,1] == 1 - @test indegree(g) == sum(adjacency_matrix(g), 1)[1,:] - @test outdegree(g) == sum(adjacency_matrix(g), 2)[:,1] + add_edge!(g, 1, 1) + @test adjacency_matrix(g)[1, 1] == 1 + @test indegree(g) == sum(adjacency_matrix(g), 1)[1, :] + @test outdegree(g) == sum(adjacency_matrix(g), 2)[:, 1] g10 = CompleteGraph(10) for g in testgraphs(g10) B, em = non_backtracking_matrix(g) - @test length(em) == 2*ne(g) - @test size(B) == (2*ne(g),2*ne(g)) - for i=1:10 - @test sum(B[:,i]) == 8 - @test sum(B[i,:]) == 8 + @test length(em) == 2 * ne(g) + @test size(B) == (2 * ne(g), 2 * ne(g)) + for i = 1:10 + @test sum(B[:, i]) == 8 + @test sum(B[i, :]) == 8 end @test !issymmetric(B) v = ones(Float64, ne(g)) z = zeros(Float64, nv(g)) n10 = Nonbacktracking(g) - @test size(n10) == (2*ne(g), 2*ne(g)) + @test size(n10) == (2 * ne(g), 2 * ne(g)) @test eltype(n10) == Float64 @test !issymmetric(n10) @@ -61,11 +61,11 @@ full(nbt::Nonbacktracking) = full(sparse(nbt)) zprime = contract(n10, v) @test z == zprime - @test z == 9*ones(Float64, nv(g)) + @test z == 9 * ones(Float64, nv(g)) end for g in testdigraphs(g5) - @test adjacency_spectrum(g)[3] ≈ 0.311 atol=0.001 + @test adjacency_spectrum(g)[3] ≈ 0.311 atol = 0.001 end for g in testgraphs(g3) @@ -92,35 +92,35 @@ full(nbt::Nonbacktracking) = full(sparse(nbt)) for dir in [:in, :out, :both] amat = adjacency_matrix(g, dir, Float64) lmat = laplacian_matrix(g, dir, Float64) - @test isa(amat, SparseMatrixCSC{Float64, Int64}) - @test isa(lmat, SparseMatrixCSC{Float64, Int64}) + @test isa(amat, SparseMatrixCSC{Float64,Int64}) + @test isa(lmat, SparseMatrixCSC{Float64,Int64}) evals = eigvals(full(lmat)) @test all(evals .>= -1e-15) # positive semidefinite - @test (minimum(evals)) ≈ 0 atol=1e-13 + @test (minimum(evals)) ≈ 0 atol = 1e-13 end end for g in testdigraphs(g4) # testing incidence_matrix, first directed graph - @test size(incidence_matrix(g)) == (5,4) - @test incidence_matrix(g)[1,1] == -1 - @test incidence_matrix(g)[2,1] == 1 - @test incidence_matrix(g)[3,1] == 0 + @test size(incidence_matrix(g)) == (5, 4) + @test incidence_matrix(g)[1, 1] == -1 + @test incidence_matrix(g)[2, 1] == 1 + @test incidence_matrix(g)[3, 1] == 0 end for g in testgraphs(g3) # now undirected graph - @test size(incidence_matrix(g)) == (5,4) - @test incidence_matrix(g)[1,1] == 1 - @test incidence_matrix(g)[2,1] == 1 - @test incidence_matrix(g)[3,1] == 0 + @test size(incidence_matrix(g)) == (5, 4) + @test incidence_matrix(g)[1, 1] == 1 + @test incidence_matrix(g)[2, 1] == 1 + @test incidence_matrix(g)[3, 1] == 0 # undirected graph with orientation - @test size(incidence_matrix(g; oriented=true)) == (5,4) - @test incidence_matrix(g; oriented=true)[1,1] == -1 - @test incidence_matrix(g; oriented=true)[2,1] == 1 - @test incidence_matrix(g; oriented=true)[3,1] == 0 + @test size(incidence_matrix(g; oriented=true)) == (5, 4) + @test incidence_matrix(g; oriented=true)[1, 1] == -1 + @test incidence_matrix(g; oriented=true)[2, 1] == 1 + @test incidence_matrix(g; oriented=true)[3, 1] == 0 end # TESTS FOR Nonbacktracking operator. @@ -132,19 +132,19 @@ full(nbt::Nonbacktracking) = full(sparse(nbt)) B, emap = non_backtracking_matrix(g) Bs = sparse(nbt) @test sparse(B) == Bs - @test eigs(nbt, nev=1)[1] ≈ eigs(B, nev=1)[1] atol=1e-5 + @test eigs(nbt, nev=1)[1] ≈ eigs(B, nev=1)[1] atol = 1e-5 # check that matvec works x = ones(Float64, nbt.m) y = nbt * x z = B * x - @test norm(y-z) < 1e-8 + @test norm(y - z) < 1e-8 #check that matmat works and full(nbt) == B - @test norm(nbt*eye(nbt.m) - B) < 1e-8 + @test norm(nbt * eye(nbt.m) - B) < 1e-8 #check that matmat works and full(nbt) == B - @test norm(nbt*eye(nbt.m) - B) < 1e-8 + @test norm(nbt * eye(nbt.m) - B) < 1e-8 #check that we can use the implicit matvec in nonbacktrack_embedding @test size(y) == size(x) @@ -152,7 +152,7 @@ full(nbt::Nonbacktracking) = full(sparse(nbt)) B₁ = Nonbacktracking(g10) @test full(B₁) == full(B) - @test B₁ * ones(size(B₁)[2]) == B*ones(size(B)[2]) + @test B₁ * ones(size(B₁)[2]) == B * ones(size(B)[2]) @test size(B₁) == size(B) # @test norm(eigs(B₁)[1] - eigs(B)[1]) ≈ 0.0 atol=1e-8 @test !issymmetric(B₁) @@ -161,11 +161,11 @@ full(nbt::Nonbacktracking) = full(sparse(nbt)) # END tests for Nonbacktracking # spectral distance checks - for n=3:10 + for n = 3:10 polygon = random_regular_graph(n, 2) for g in testgraphs(polygon) - @test isapprox(spectral_distance(g, g), 0, atol=1e-8) - @test isapprox(spectral_distance(g, g, 1), 0, atol=1e-8) + @test isapprox(spectral_distance(g, g), 0, atol = 1e-8) + @test isapprox(spectral_distance(g, g, 1), 0, atol = 1e-8) end end end diff --git a/test/operators.jl b/test/operators.jl index c193bd845..4473f0008 100644 --- a/test/operators.jl +++ b/test/operators.jl @@ -25,8 +25,8 @@ z = @inferred(difference(h, g)) @test nv(z) == 4 @test ne(z) == 0 - z = @inferred(symmetric_difference(h,g)) - @test z == symmetric_difference(g,h) + z = @inferred(symmetric_difference(h, g)) + @test z == symmetric_difference(g, h) @test nv(z) == 5 @test ne(z) == 1 @@ -96,13 +96,13 @@ px = PathGraph(10) for p in testgraphs(px) - x = @inferred(p*ones(10)) - @test x[1] ==1.0 && all(x[2:end-1].==2.0) && x[end]==1.0 - @test size(p) == (10,10) + x = @inferred(p * ones(10)) + @test x[1] == 1.0 && all(x[2:(end - 1)] .== 2.0) && x[end] == 1.0 + @test size(p) == (10, 10) @test size(p, 1) == size(p, 2) == 10 @test size(p, 3) == 1 - @test sum(p,1) == sum(p,2) - @test_throws ErrorException sum(p,3) + @test sum(p, 1) == sum(p, 2) + @test_throws ErrorException sum(p, 3) @test sparse(p) == adjacency_matrix(p) @test length(p) == 100 @test ndims(p) == 2 @@ -110,7 +110,7 @@ end gx = DiGraph(4) - add_edge!(gx,1,2); add_edge!(gx,2,3); add_edge!(gx,1,3); add_edge!(gx,3,4) + add_edge!(gx, 1, 2); add_edge!(gx, 2, 3); add_edge!(gx, 1, 3); add_edge!(gx, 3, 4) for g in testdigraphs(gx) @test @inferred(g * ones(nv(g))) == [2.0, 1.0, 1.0, 0.0] @test sum(g, 1) == [0, 1, 2, 1] @@ -132,11 +132,11 @@ function crosspath_slow(len, h) g = h m = nv(h) - for i in 1:len-1 + for i in 1:(len - 1) k = nv(g) - g = blkdiag(g,h) + g = blkdiag(g, h) for v in 1:m - add_edge!(g, v+(k-m), v+k) + add_edge!(g, v + (k - m), v + k) end end return g @@ -166,22 +166,22 @@ @test nv(h) == n @test ne(h) == 3 - h = @inferred(g[[1,2,4]]) + h = @inferred(g[[1, 2, 4]]) @test nv(h) == n @test ne(h) == 2 - h = @inferred(g[[1,5]]) + h = @inferred(g[[1, 5]]) @test nv(h) == 2 @test ne(h) == 0 @test typeof(h) == typeof(g) end - gx = DiGraph(100,200) + gx = DiGraph(100, 200) for g in testdigraphs(gx) h = @inferred(g[5:26]) @test nv(h) == 22 @test typeof(h) == typeof(g) - @test_throws ErrorException g[[1,1]] + @test_throws ErrorException g[[1, 1]] r = 5:26 h2, vm = @inferred(induced_subgraph(g, r)) @@ -196,13 +196,13 @@ @test nv(sg) == 4 @test ne(sg) == 6 - sg2, vm = @inferred(induced_subgraph(g, [5,6,7,8])) + sg2, vm = @inferred(induced_subgraph(g, [5, 6, 7, 8])) @test sg2 == sg @test vm[4] == 8 elist = [ SimpleEdge(1, 2), SimpleEdge(2, 3), SimpleEdge(3, 4), - SimpleEdge(4, 5),SimpleEdge(5, 1) + SimpleEdge(4, 5), SimpleEdge(5, 1) ] sg, vm = @inferred(induced_subgraph(g, elist)) @test sg == CycleGraph(5) diff --git a/test/persistence/persistence.jl b/test/persistence/persistence.jl index dd6d0d684..e9d61308a 100644 --- a/test/persistence/persistence.jl +++ b/test/persistence/persistence.jl @@ -1,11 +1,11 @@ @testset "Persistence" begin @test_throws ErrorException LightGraphs._NI("Not implemented") - pdict = loadgraphs(joinpath(testdir,"testdata","tutte-pathdigraph.jgz")) + pdict = loadgraphs(joinpath(testdir, "testdata", "tutte-pathdigraph.jgz")) p1 = pdict["Tutte"] p2 = pdict["pathdigraph"] g3 = PathGraph(5) - (f,fio) = mktemp() + (f, fio) = mktemp() # test :lg @test savegraph(f, p1) == 1 @test savegraph(f, p1; compress=true) == 1 @@ -23,7 +23,7 @@ @test gs == p2 @test_throws ErrorException loadgraph(joinpath(testdir, "testdata", "tutte-pathdigraph.jgz"), "badname") - d = Dict{String, AbstractGraph}("p1"=>p1, "p2"=>p2) + d = Dict{String,AbstractGraph}("p1" => p1, "p2" => p2) @test savegraph(f, d) == 2 diff --git a/test/runtests.jl b/test/runtests.jl index 622595fcc..b2762e1fb 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -103,7 +103,7 @@ tests = [ @testset "LightGraphs" begin for t in tests - tp = joinpath(testdir,"$(t).jl") + tp = joinpath(testdir, "$(t).jl") include(tp) end end diff --git a/test/shortestpaths/astar.jl b/test/shortestpaths/astar.jl index 014fd9773..88fb9550b 100644 --- a/test/shortestpaths/astar.jl +++ b/test/shortestpaths/astar.jl @@ -2,8 +2,8 @@ g3 = PathGraph(5) g4 = PathDiGraph(5) - d1 = float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) - d2 = sparse(float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])) + d1 = float([0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) + d2 = sparse(float([0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])) for g in testgraphs(g3), dg in testdigraphs(g4) @test @inferred(a_star(g, 1, 4, d1)) == @inferred(a_star(dg, 1, 4, d1)) == diff --git a/test/shortestpaths/bellman-ford.jl b/test/shortestpaths/bellman-ford.jl index cdf92dc21..cfd977156 100644 --- a/test/shortestpaths/bellman-ford.jl +++ b/test/shortestpaths/bellman-ford.jl @@ -1,14 +1,14 @@ @testset "Bellman Ford" begin g4 = PathDiGraph(5) - d1 = float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) - d2 = sparse(float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])) + d1 = float([0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) + d2 = sparse(float([0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])) for g in testdigraphs(g4) y = @inferred(bellman_ford_shortest_paths(g, 2, d1)) z = @inferred(bellman_ford_shortest_paths(g, 2, d2)) @test y.dists == z.dists == [Inf, 0, 6, 17, 33] @test @inferred(enumerate_paths(z))[2] == [] - @test @inferred(enumerate_paths(z))[4] == enumerate_paths(z,4) == [2,3,4] + @test @inferred(enumerate_paths(z))[4] == enumerate_paths(z, 4) == [2, 3, 4] @test @inferred(!has_negative_edge_cycle(g)) @test @inferred(!has_negative_edge_cycle(g, d1)) @@ -17,7 +17,7 @@ z = @inferred(bellman_ford_shortest_paths(g, 2, d2)) @test y.dists == z.dists == [Inf, 0, 6, 17, 33] @test @inferred(enumerate_paths(z))[2] == [] - @test @inferred(enumerate_paths(z))[4] == enumerate_paths(z,4) == [2,3,4] + @test @inferred(enumerate_paths(z))[4] == enumerate_paths(z, 4) == [2, 3, 4] @test @inferred(!has_negative_edge_cycle(g)) z = @inferred(bellman_ford_shortest_paths(g, 2)) @test z.dists == [typemax(Int), 0, 1, 2, 3] diff --git a/test/shortestpaths/dijkstra.jl b/test/shortestpaths/dijkstra.jl index 4f6353993..8190d615d 100644 --- a/test/shortestpaths/dijkstra.jl +++ b/test/shortestpaths/dijkstra.jl @@ -1,7 +1,7 @@ @testset "Dijkstra" begin g4 = PathDiGraph(5) - d1 = float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) - d2 = sparse(float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])) + d1 = float([0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) + d2 = sparse(float([0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])) for g in testdigraphs(g4) y = @inferred(dijkstra_shortest_paths(g, 2, d1)) @@ -16,16 +16,16 @@ @test @inferred(enumerate_paths(z)) == enumerate_paths(y) @test @inferred(enumerate_paths(z))[4] == - enumerate_paths(z,4) == - enumerate_paths(y,4) == [2,3,4] + enumerate_paths(z, 4) == + enumerate_paths(y, 4) == [2, 3, 4] end gx = PathGraph(5) - add_edge!(gx,2,4) - d = ones(Int, 5,5) - d[2,3] = 100 + add_edge!(gx, 2, 4) + d = ones(Int, 5, 5) + d[2, 3] = 100 for g in testgraphs(gx) - z = @inferred(dijkstra_shortest_paths(g,1,d)) + z = @inferred(dijkstra_shortest_paths(g, 1, d)) @test z.dists == [0, 1, 3, 2, 3] @test z.parents == [0, 1, 4, 2, 4] end @@ -36,37 +36,37 @@ function spaths(ds, targets, source) shortest_paths = [] for i in targets - push!(shortest_paths,spath(i,ds,source)) + push!(shortest_paths, spath(i, ds, source)) end return shortest_paths end G = LightGraphs.Graph() - add_vertices!(G,4) - add_edge!(G,2,1) - add_edge!(G,2,3) - add_edge!(G,1,4) - add_edge!(G,3,4) - add_edge!(G,2,2) + add_vertices!(G, 4) + add_edge!(G, 2, 1) + add_edge!(G, 2, 3) + add_edge!(G, 1, 4) + add_edge!(G, 3, 4) + add_edge!(G, 2, 2) w = [0. 3. 0. 1.; 3. 0. 2. 0.; 0. 2. 0. 3.; 1. 0. 3. 0.] for g in testgraphs(G) - ds = @inferred(dijkstra_shortest_paths(g,2,w)) + ds = @inferred(dijkstra_shortest_paths(g, 2, w)) # this loop reconstructs the shortest path for vertices 1, 3 and 4 - @test spaths(ds, [1,3,4], 2) == Array[[2 1], + @test spaths(ds, [1, 3, 4], 2) == Array[[2 1], [2 3], [2 1 4]] # here a selflink at source is introduced; it should not change the shortest paths - w[2,2] = 10.0 - ds = @inferred(dijkstra_shortest_paths(g,2,w)) + w[2, 2] = 10.0 + ds = @inferred(dijkstra_shortest_paths(g, 2, w)) shortest_paths = [] # this loop reconstructs the shortest path for vertices 1, 3 and 4 - @test spaths(ds, [1,3,4], 2) == Array[[2 1], + @test spaths(ds, [1, 3, 4], 2) == Array[[2 1], [2 3], [2 1 4]] end @@ -74,50 +74,50 @@ #615 m = [0 2 2 0 0; 2 0 0 0 3; 2 0 0 1 2;0 0 1 0 1;0 3 2 1 0] G = Graph(5) - add_edge!(G,1,2) - add_edge!(G,1,3) - add_edge!(G,2,5) - add_edge!(G,3,5) - add_edge!(G,3,4) - add_edge!(G,4,5) + add_edge!(G, 1, 2) + add_edge!(G, 1, 3) + add_edge!(G, 2, 5) + add_edge!(G, 3, 5) + add_edge!(G, 3, 4) + add_edge!(G, 4, 5) for g in testgraphs(G) - ds = @inferred(dijkstra_shortest_paths(g,1,m;allpaths=true)) + ds = @inferred(dijkstra_shortest_paths(g, 1, m; allpaths=true)) @test ds.pathcounts == [1, 1, 1, 1, 2] - @test ds.predecessors == [[], [1], [1], [3], [3,4]] - @test ds.predecessors == [[], [1], [1], [3], [3,4]] + @test ds.predecessors == [[], [1], [1], [3], [3, 4]] + @test ds.predecessors == [[], [1], [1], [3], [3, 4]] - dm = @inferred(dijkstra_shortest_paths(g,1;allpaths=true,trackvertices=true)) + dm = @inferred(dijkstra_shortest_paths(g, 1; allpaths=true, trackvertices=true)) @test dm.pathcounts == [1, 1, 1, 1, 2] - @test dm.predecessors == [[], [1], [1], [3], [2,3]] - @test dm.closest_vertices == [1,2,3,5,4] + @test dm.predecessors == [[], [1], [1], [3], [2, 3]] + @test dm.closest_vertices == [1, 2, 3, 5, 4] end G = Graph(5) - add_edge!(G,1,2) - add_edge!(G,1,3) - add_edge!(G,4,5) + add_edge!(G, 1, 2) + add_edge!(G, 1, 3) + add_edge!(G, 4, 5) for g in testgraphs(G) - dm = @inferred(dijkstra_shortest_paths(g,1;allpaths=true,trackvertices=true)) - @test dm.closest_vertices == [1,2,3,4,5] + dm = @inferred(dijkstra_shortest_paths(g, 1; allpaths=true, trackvertices=true)) + @test dm.closest_vertices == [1, 2, 3, 4, 5] end #Testing multisource On undirected Graph g3 = PathGraph(5) - d = [ 0 1 2 3 4; 1 0 1 0 1; 2 1 0 11 12; 3 0 11 0 5; 4 1 19 5 0] + d = [0 1 2 3 4; 1 0 1 0 1; 2 1 0 11 12; 3 0 11 0 5; 4 1 19 5 0] for g in testgraphs(g3) z = @inferred(floyd_warshall_shortest_paths(g, d)) zp = @inferred(parallel_multisource_dijkstra_shortest_paths(g, collect(1:5), d)) - @test all(isapprox(z.dists,zp.dists)) + @test all(isapprox(z.dists, zp.dists)) for i in 1:5 - state = dijkstra_shortest_paths(g,i;allpaths=true); + state = dijkstra_shortest_paths(g, i; allpaths=true); for j in 1:5 - if z.parents[i,j]!=0 - @test z.parents[i,j] in state.predecessors[j] + if z.parents[i, j] != 0 + @test z.parents[i, j] in state.predecessors[j] else @test length(state.predecessors[j]) == 0 - @test state.parents[j]==0 + @test state.parents[j] == 0 end end end @@ -127,10 +127,10 @@ @test all(isapprox(z.dists, zp.dists)) for i in 1:5 - state = dijkstra_shortest_paths(g, i;allpaths=true); + state = dijkstra_shortest_paths(g, i; allpaths=true); for j in 1:5 - if z.parents[i,j]!=0 - @test z.parents[i,j] in state.predecessors[j] + if z.parents[i, j] != 0 + @test z.parents[i, j] in state.predecessors[j] else @test length(state.predecessors[j]) == 0 end @@ -138,14 +138,14 @@ end z = @inferred(floyd_warshall_shortest_paths(g)) - zp = @inferred(parallel_multisource_dijkstra_shortest_paths(g, [1,2])) - @test all(isapprox(z.dists[1:2,:], zp.dists)) + zp = @inferred(parallel_multisource_dijkstra_shortest_paths(g, [1, 2])) + @test all(isapprox(z.dists[1:2, :], zp.dists)) for i in 1:2 state = dijkstra_shortest_paths(g, i;allpaths=true); for j in 1:5 - if z.parents[i,j]!=0 - @test z.parents[i,j] in state.predecessors[j] + if z.parents[i, j] != 0 + @test z.parents[i, j] in state.predecessors[j] else @test length(state.predecessors[j]) == 0 end @@ -156,7 +156,7 @@ #Testing multisource On directed Graph g3 = PathDiGraph(5) - d = float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) + d = float([0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) for g in testdigraphs(g3) z = @inferred(floyd_warshall_shortest_paths(g, d)) @@ -164,10 +164,10 @@ @test all(isapprox(z.dists, zp.dists)) for i in 1:5 - state = dijkstra_shortest_paths(g, i;allpaths=true); + state = dijkstra_shortest_paths(g, i; allpaths=true); for j in 1:5 - if z.parents[i,j]!=0 - @test z.parents[i,j] in state.predecessors[j] + if z.parents[i, j] != 0 + @test z.parents[i, j] in state.predecessors[j] else @test length(state.predecessors[j]) == 0 end @@ -179,10 +179,10 @@ @test all(isapprox(z.dists, zp.dists)) for i in 1:5 - state = dijkstra_shortest_paths(g, i;allpaths=true); + state = dijkstra_shortest_paths(g, i; allpaths=true); for j in 1:5 - if z.parents[i,j]!=0 - @test z.parents[i,j] in state.predecessors[j] + if z.parents[i, j] != 0 + @test z.parents[i, j] in state.predecessors[j] else @test length(state.predecessors[j]) == 0 end @@ -190,14 +190,14 @@ end z = @inferred(floyd_warshall_shortest_paths(g)) - zp = @inferred(parallel_multisource_dijkstra_shortest_paths(g, [1,2])) - @test all(isapprox(z.dists[1:2,:], zp.dists)) + zp = @inferred(parallel_multisource_dijkstra_shortest_paths(g, [1, 2])) + @test all(isapprox(z.dists[1:2, :], zp.dists)) for i in 1:2 state = dijkstra_shortest_paths(g, i;allpaths=true); for j in 1:5 - if z.parents[i,j]!=0 - @test z.parents[i,j] in state.predecessors[j] + if z.parents[i, j] != 0 + @test z.parents[i, j] in state.predecessors[j] else @test length(state.predecessors[j]) == 0 end diff --git a/test/shortestpaths/floyd-warshall.jl b/test/shortestpaths/floyd-warshall.jl index 43af1300a..213ec1431 100644 --- a/test/shortestpaths/floyd-warshall.jl +++ b/test/shortestpaths/floyd-warshall.jl @@ -1,20 +1,20 @@ @testset "Floyd Warshall" begin g3 = PathGraph(5) - d = [ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0] + d = [0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0] for g in testgraphs(g3) z = @inferred(floyd_warshall_shortest_paths(g, d)) - @test z.dists[3,:][:] == [7, 6, 0, 11, 27] - @test z.parents[3,:][:] == [2, 3, 0, 3, 4] + @test z.dists[3, :][:] == [7, 6, 0, 11, 27] + @test z.parents[3, :][:] == [2, 3, 0, 3, 4] @test @inferred(enumerate_paths(z))[2][2] == [] - @test @inferred(enumerate_paths(z))[2][4] == enumerate_paths(z,2)[4] == enumerate_paths(z,2,4) == [2,3,4] + @test @inferred(enumerate_paths(z))[2][4] == enumerate_paths(z, 2)[4] == enumerate_paths(z, 2, 4) == [2, 3, 4] end g4 = PathDiGraph(4) - d = ones(4,4) + d = ones(4, 4) for g in testdigraphs(g4) z = @inferred(floyd_warshall_shortest_paths(g, d)) - @test length(enumerate_paths(z,4,3)) == 0 - @test length(enumerate_paths(z,4,1)) == 0 - @test length(enumerate_paths(z,2,3)) == 2 + @test length(enumerate_paths(z, 4, 3)) == 0 + @test length(enumerate_paths(z, 4, 1)) == 0 + @test length(enumerate_paths(z, 2, 3)) == 2 end end diff --git a/test/shortestpaths/yen.jl b/test/shortestpaths/yen.jl index 8f8dead04..ebec4b95f 100644 --- a/test/shortestpaths/yen.jl +++ b/test/shortestpaths/yen.jl @@ -1,94 +1,94 @@ @testset "Yen" begin g4 = PathDiGraph(5) - d1 = float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) - d2 = sparse(float([ 0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])) + d1 = float([0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0]) + d2 = sparse(float([0 1 2 3 4; 5 0 6 7 8; 9 10 0 11 12; 13 14 15 0 16; 17 18 19 20 0])) for g in testdigraphs(g4) - x = @inferred(yen_k_shortest_paths(g,5,5)) + x = @inferred(yen_k_shortest_paths(g, 5, 5)) @test length(x.dists) == length(x.paths) == 1 @test x.dists[1] == 0 @test x.paths[1] == [5] - y = @inferred(yen_k_shortest_paths(g,2,5,d1,1)) - z = @inferred(yen_k_shortest_paths(g,2,5,d2,1)) + y = @inferred(yen_k_shortest_paths(g, 2, 5, d1, 1)) + z = @inferred(yen_k_shortest_paths(g, 2, 5, d2, 1)) @test length(y.dists) == length(z.dists) == 1 @test length(y.paths) == length(z.paths) == 1 @test y.dists == z.dists == [33.0] - @test z.paths == y.paths == [[2,3,4,5]] + @test z.paths == y.paths == [[2, 3, 4, 5]] # Remove edge to test empty paths - rem_edge!(g,1,2) - x = @inferred(yen_k_shortest_paths(g,1,5)) + rem_edge!(g, 1, 2) + x = @inferred(yen_k_shortest_paths(g, 1, 5)) @test length(x.dists) == length(x.paths) == 0 end gx = PathGraph(5) - add_edge!(gx,2,4) - d = ones(Int, 5,5) - d[2,3] = 100 + add_edge!(gx, 2, 4) + d = ones(Int, 5, 5) + d[2, 3] = 100 for g in testgraphs(gx) - z = @inferred(yen_k_shortest_paths(g,1,5,d,1)) + z = @inferred(yen_k_shortest_paths(g, 1, 5, d, 1)) @test length(z.dists) == 1 @test z.dists == [3] - @test z.paths[1] == [1,2,4,5] + @test z.paths[1] == [1, 2, 4, 5] end G = LightGraphs.Graph() - add_vertices!(G,4) - add_edge!(G,2,1) - add_edge!(G,2,3) - add_edge!(G,1,4) - add_edge!(G,3,4) - add_edge!(G,2,2) + add_vertices!(G, 4) + add_edge!(G, 2, 1) + add_edge!(G, 2, 3) + add_edge!(G, 1, 4) + add_edge!(G, 3, 4) + add_edge!(G, 2, 2) w = [0. 3. 0. 1.; 3. 0. 2. 0.; 0. 2. 0. 3.; 1. 0. 3. 0.] for g in testgraphs(G) - ds = @inferred(yen_k_shortest_paths(g,2,4,w)) + ds = @inferred(yen_k_shortest_paths(g, 2, 4, w)) @test ds.paths == [[2, 1, 4]] - ds = @inferred(yen_k_shortest_paths(g,2,1,w)) + ds = @inferred(yen_k_shortest_paths(g, 2, 1, w)) @test ds.paths == [[2, 1]] - ds = @inferred(yen_k_shortest_paths(g,2,3,w)) + ds = @inferred(yen_k_shortest_paths(g, 2, 3, w)) @test ds.paths == [[2, 3]] # Test with multiple paths - ds = @inferred(yen_k_shortest_paths(g,2,4,w,2)) - @test ds.paths == [[2, 1, 4],[2, 3, 4]] + ds = @inferred(yen_k_shortest_paths(g, 2, 4, w, 2)) + @test ds.paths == [[2, 1, 4], [2, 3, 4]] # here a selflink at source is introduced; it should not change the shortest paths - w[2,2] = 10.0 - ds = @inferred(yen_k_shortest_paths(g,2,4,w)) + w[2, 2] = 10.0 + ds = @inferred(yen_k_shortest_paths(g, 2, 4, w)) @test ds.paths == [[2, 1, 4]] - ds = @inferred(yen_k_shortest_paths(g,2,4,w,3)) - @test ds.paths == [[2, 1, 4],[2, 3, 4]] + ds = @inferred(yen_k_shortest_paths(g, 2, 4, w, 3)) + @test ds.paths == [[2, 1, 4], [2, 3, 4]] # Test with new short link - add_edge!(g,2,4) - w[2,4] = 1. - w[4,2] = 1. - ds = @inferred(yen_k_shortest_paths(g,2,4,w,2)) - @test ds.paths == [[2, 4],[2, 1, 4]] - ds = @inferred(yen_k_shortest_paths(g,2,4,w,3)) - @test ds.paths == [[2, 4],[2, 1, 4],[2, 3, 4]] + add_edge!(g, 2, 4) + w[2, 4] = 1. + w[4, 2] = 1. + ds = @inferred(yen_k_shortest_paths(g, 2, 4, w, 2)) + @test ds.paths == [[2, 4], [2, 1, 4]] + ds = @inferred(yen_k_shortest_paths(g, 2, 4, w, 3)) + @test ds.paths == [[2, 4], [2, 1, 4], [2, 3, 4]] end # Testing with the example in https://en.wikipedia.org/wiki/Yen%27s_algorithm G = LightGraphs.DiGraph() - add_vertices!(G,6) - add_edge!(G,1,2) - add_edge!(G,1,3) - add_edge!(G,2,4) - add_edge!(G,3,2) - add_edge!(G,3,4) - add_edge!(G,3,5) - add_edge!(G,4,5) - add_edge!(G,4,6) - add_edge!(G,5,6) + add_vertices!(G, 6) + add_edge!(G, 1, 2) + add_edge!(G, 1, 3) + add_edge!(G, 2, 4) + add_edge!(G, 3, 2) + add_edge!(G, 3, 4) + add_edge!(G, 3, 5) + add_edge!(G, 4, 5) + add_edge!(G, 4, 6) + add_edge!(G, 5, 6) w = [0. 3. 2. 0. 0. 0.; 0. 0. 0. 4. 0. 0.; 0. 1. 0. 2. 3. 0.; @@ -97,21 +97,21 @@ 0. 0. 0. 0. 0. 0.;] for g in testdigraphs(G) - ds = @inferred(yen_k_shortest_paths(g,1,6,w,3)) - @test ds.dists == [5.,7.,8.] - @test ds.paths[1] == [1,3,4,6] - @test ds.paths[2] == [1,3,5,6] + ds = @inferred(yen_k_shortest_paths(g, 1, 6, w, 3)) + @test ds.dists == [5., 7., 8.] + @test ds.paths[1] == [1, 3, 4, 6] + @test ds.paths[2] == [1, 3, 5, 6] end # Test all the paths - add_edge!(G,1,4) - w[1,4] = 3 - w[4,1] = 3 + add_edge!(G, 1, 4) + w[1, 4] = 3 + w[4, 1] = 3 for g in testdigraphs(G) - ds = @inferred(yen_k_shortest_paths(G,1,6,w,100)) - @test ds.dists == [4.0,5.0,7.0,7.0,8.0,8.0,8.0,11.0,11.0] + ds = @inferred(yen_k_shortest_paths(G, 1, 6, w, 100)) + @test ds.dists == [4.0, 5.0, 7.0, 7.0, 8.0, 8.0, 8.0, 11.0, 11.0] - ds = @inferred(yen_k_shortest_paths(G,1,6,w,100,maxdist=7)) - @test ds.dists == [4.0,5.0,7.0,7.0] + ds = @inferred(yen_k_shortest_paths(G, 1, 6, w, 100, maxdist=7)) + @test ds.dists == [4.0, 5.0, 7.0, 7.0] end end diff --git a/test/spanningtrees/kruskal.jl b/test/spanningtrees/kruskal.jl index 7c134290a..d1c799301 100644 --- a/test/spanningtrees/kruskal.jl +++ b/test/spanningtrees/kruskal.jl @@ -2,34 +2,34 @@ g4 = CompleteGraph(4) distmx = [ - 0 1 5 6 - 1 0 4 10 - 5 4 0 3 - 6 10 3 0 + 0 1 5 6 + 1 0 4 10 + 5 4 0 3 + 6 10 3 0 ] vec_mst = Vector{Edge}([Edge(1, 2), Edge(3, 4), Edge(2, 3)]) for g in testgraphs(g4) # Testing Kruskal's algorithm - mst = @inferred(kruskal_mst(g, distmx)) - @test mst == vec_mst + mst = @inferred(kruskal_mst(g, distmx)) + @test mst == vec_mst end - #second test - distmx_sec = [ - 0 0 0.26 0 0.38 0 0.58 0.16 - 0 0 0.36 0.29 0 0.32 0 0.19 - 0.26 0.36 0 0.17 0 0 0.4 0.34 - 0 0.29 0.17 0 0 0 0.52 0 - 0.38 0 0 0 0 0.35 0.93 0.37 - 0 0.32 0 0 0.35 0 0 0.28 - 0.58 0 0.4 0.52 0.93 0 0 0 - 0.16 0.19 0.34 0 0.37 0.28 0 0 - ] + #second test + distmx_sec = [ + 0 0 0.26 0 0.38 0 0.58 0.16 + 0 0 0.36 0.29 0 0.32 0 0.19 + 0.26 0.36 0 0.17 0 0 0.4 0.34 + 0 0.29 0.17 0 0 0 0.52 0 + 0.38 0 0 0 0 0.35 0.93 0.37 + 0 0.32 0 0 0.35 0 0 0.28 + 0.58 0 0.4 0.52 0.93 0 0 0 + 0.16 0.19 0.34 0 0.37 0.28 0 0 + ] gx = Graph(distmx_sec) - vec2 = Vector{Edge}([Edge(1, 8),Edge(3, 4),Edge(2, 8),Edge(1, 3),Edge(6, 8),Edge(5, 6),Edge(3, 7)]) + vec2 = Vector{Edge}([Edge(1, 8), Edge(3, 4), Edge(2, 8), Edge(1, 3), Edge(6, 8), Edge(5, 6), Edge(3, 7)]) for g in testgraphs(gx) - mst2 = @inferred(kruskal_mst(g, distmx_sec)) - @test mst2 == vec2 + mst2 = @inferred(kruskal_mst(g, distmx_sec)) + @test mst2 == vec2 end end diff --git a/test/spanningtrees/prim.jl b/test/spanningtrees/prim.jl index 5363eb529..317bc6ec1 100644 --- a/test/spanningtrees/prim.jl +++ b/test/spanningtrees/prim.jl @@ -10,27 +10,27 @@ vec_mst = Vector{Edge}([Edge(1, 2), Edge(2, 3), Edge(3, 4)]) for g in testgraphs(g4) - # Testing Prim's algorithm - mst = @inferred(prim_mst(g, distmx)) - @test mst == vec_mst + # Testing Prim's algorithm + mst = @inferred(prim_mst(g, distmx)) + @test mst == vec_mst end #second test distmx_sec = [ - 0 0 0.26 0 0.38 0 0.58 0.16 - 0 0 0.36 0.29 0 0.32 0 0.19 - 0.26 0.36 0 0.17 0 0 0.4 0.34 - 0 0.29 0.17 0 0 0 0.52 0 - 0.38 0 0 0 0 0.35 0.93 0.37 - 0 0.32 0 0 0.35 0 0 0.28 - 0.58 0 0.4 0.52 0.93 0 0 0 - 0.16 0.19 0.34 0 0.37 0.28 0 0 - ] + 0 0 0.26 0 0.38 0 0.58 0.16 + 0 0 0.36 0.29 0 0.32 0 0.19 + 0.26 0.36 0 0.17 0 0 0.4 0.34 + 0 0.29 0.17 0 0 0 0.52 0 + 0.38 0 0 0 0 0.35 0.93 0.37 + 0 0.32 0 0 0.35 0 0 0.28 + 0.58 0 0.4 0.52 0.93 0 0 0 + 0.16 0.19 0.34 0 0.37 0.28 0 0 + ] - vec2 = Vector{Edge}([Edge(1, 8),Edge(2, 8),Edge(1, 3),Edge(3, 4),Edge(6, 8),Edge(5, 6),Edge(3, 7)]) + vec2 = Vector{Edge}([Edge(1, 8), Edge(2, 8), Edge(1, 3), Edge(3, 4), Edge(6, 8), Edge(5, 6), Edge(3, 7)]) gx = Graph(distmx_sec) for g in testgraphs(gx) - mst2 = @inferred(prim_mst(g, distmx_sec)) - @test mst2 == vec2 + mst2 = @inferred(prim_mst(g, distmx_sec)) + @test mst2 == vec2 end end diff --git a/test/traversals/bfs.jl b/test/traversals/bfs.jl index 198ca2f78..2dce30a32 100644 --- a/test/traversals/bfs.jl +++ b/test/traversals/bfs.jl @@ -1,29 +1,29 @@ import LightGraphs: TreeBFSVisitorVector, bfs_tree!, tree @testset "BFS" begin g5 = DiGraph(4) - add_edge!(g5,1,2); add_edge!(g5,2,3); add_edge!(g5,1,3); add_edge!(g5,3,4) + add_edge!(g5, 1, 2); add_edge!(g5, 2, 3); add_edge!(g5, 1, 3); add_edge!(g5, 3, 4) g6 = smallgraph(:house) for g in testdigraphs(g5) z = @inferred(bfs_tree(g, 1)) - visitor = LightGraphs.TreeBFSVisitorVector(zeros(eltype(g),nv(g))) + visitor = LightGraphs.TreeBFSVisitorVector(zeros(eltype(g), nv(g))) LightGraphs.bfs_tree!(visitor, g, 1) t = visitor.tree - @test t == [1,1,1,3] + @test t == [1, 1, 1, 3] @test nv(z) == 4 && ne(z) == 3 && !has_edge(z, 2, 3) end for g in testgraphs(g6) @test @inferred(gdistances(g, 2)) == [1, 0, 2, 1, 2] - @test @inferred(gdistances(g, [1,2])) == [0, 0, 1, 1, 2] + @test @inferred(gdistances(g, [1, 2])) == [0, 0, 1, 1, 2] @test @inferred(gdistances(g, [])) == [-1, -1, -1, -1, -1] @test @inferred(!is_bipartite(g)) @test @inferred(!is_bipartite(g, 2)) end gx = Graph(5) - add_edge!(gx,1,2); add_edge!(gx,1,4) - add_edge!(gx,2,3); add_edge!(gx,2,5) - add_edge!(gx,3,4) + add_edge!(gx, 1, 2); add_edge!(gx, 1, 4) + add_edge!(gx, 2, 3); add_edge!(gx, 2, 5) + add_edge!(gx, 3, 4) for g in testgraphs(gx) @test @inferred(is_bipartite(g)) @@ -81,12 +81,12 @@ import LightGraphs: TreeBFSVisitorVector, bfs_tree!, tree @test @inferred(bipartite_map(g)) == Vector{eltype(g)}() end - g10 = CompleteBipartiteGraph(10,10) + g10 = CompleteBipartiteGraph(10, 10) for g in testgraphs(g10) T = eltype(g) - @test @inferred(bipartite_map(g10)) == Vector{T}([ones(T, 10); 2*ones(T, 10)]) + @test @inferred(bipartite_map(g10)) == Vector{T}([ones(T, 10); 2 * ones(T, 10)]) - h = blkdiag(g,g) - @test @inferred(bipartite_map(h)) == Vector{T}([ones(T, 10); 2*ones(T, 10); ones(T, 10); 2*ones(T, 10)]) + h = blkdiag(g, g) + @test @inferred(bipartite_map(h)) == Vector{T}([ones(T, 10); 2 * ones(T, 10); ones(T, 10); 2 * ones(T, 10)]) end end diff --git a/test/traversals/dfs.jl b/test/traversals/dfs.jl index bd96e1b49..817cb984e 100644 --- a/test/traversals/dfs.jl +++ b/test/traversals/dfs.jl @@ -1,8 +1,8 @@ @testset "DFS" begin g5 = DiGraph(4) - add_edge!(g5,1,2); add_edge!(g5,2,3); add_edge!(g5,1,3); add_edge!(g5,3,4) + add_edge!(g5, 1, 2); add_edge!(g5, 2, 3); add_edge!(g5, 1, 3); add_edge!(g5, 3, 4) for g in testdigraphs(g5) - z = @inferred(dfs_tree(g,1)) + z = @inferred(dfs_tree(g, 1)) @test ne(z) == 3 && nv(z) == 4 @test !has_edge(z, 1, 3) diff --git a/test/traversals/graphvisit.jl b/test/traversals/graphvisit.jl index f658faa0d..9f7ea49f7 100644 --- a/test/traversals/graphvisit.jl +++ b/test/traversals/graphvisit.jl @@ -33,7 +33,7 @@ # dummy edge map test d = @inferred(LightGraphs.DummyEdgeMap()) - e = Edge(1,2) + e = Edge(1, 2) @test d[e] == 0 @test getindex(d, e) == 0 end diff --git a/test/traversals/maxadjvisit.jl b/test/traversals/maxadjvisit.jl index 1d15f8863..bd0d0cf11 100644 --- a/test/traversals/maxadjvisit.jl +++ b/test/traversals/maxadjvisit.jl @@ -17,11 +17,11 @@ (4, 8, 2.), (5, 6, 3.), (6, 7, 1.), - (7, 8, 3.) ] + (7, 8, 3.)] m = length(wedges) - eweights = spzeros(nv(gx),nv(gx)) + eweights = spzeros(nv(gx), nv(gx)) for (s, d, w) in wedges add_edge!(gx, s, d) diff --git a/test/traversals/parallel_bfs.jl b/test/traversals/parallel_bfs.jl index 246406e98..1ed9fbc9a 100644 --- a/test/traversals/parallel_bfs.jl +++ b/test/traversals/parallel_bfs.jl @@ -8,26 +8,26 @@ import Base.Threads: Atomic, @threads @test isempty(next) == true push!(next, 1) @test next[1][] == 1 - @threads for i=2:5 + @threads for i = 2:5 push!(next, i) end - @test Set([i[] for i in next[1:5]]) == Set([1,2,3,4,5]) + @test Set([i[] for i in next[1:5]]) == Set([1, 2, 3, 4, 5]) first = shift!(next) @test first == 1 end g5 = DiGraph(4) - add_edge!(g5,1,2); add_edge!(g5,2,3); add_edge!(g5,1,3); add_edge!(g5,3,4) + add_edge!(g5, 1, 2); add_edge!(g5, 2, 3); add_edge!(g5, 1, 3); add_edge!(g5, 3, 4) g6 = smallgraph(:house) for g in testdigraphs(g5) T = eltype(g) z = @inferred(bfs_tree(LevelSynchronousBFS(), g, T(1))) next = LightGraphs.ThreadQueue(T, nv(g)) # Initialize threadqueue - parents = [Atomic{T}(0) for i=1:nv(g)] # Create parents array + parents = [Atomic{T}(0) for i = 1:nv(g)] # Create parents array LightGraphs.bfs_tree!(LevelSynchronousBFS(), next, g, T(1), parents) t = [i[] for i in parents] - @test t == [T(1),T(1),T(1),T(3)] + @test t == [T(1), T(1), T(1), T(3)] @test nv(z) == T(4) && ne(z) == T(3) && !has_edge(z, 2, 3) end @@ -51,7 +51,7 @@ import Base.Threads: Atomic, @threads n = nv(g) T = eltype(g) next = LightGraphs.ThreadQueue(eltype(g), nv(g)) # Initialize threadqueue - parents = [Atomic{T}(0) for i=1:nv(g)] # Create parents array + parents = [Atomic{T}(0) for i = 1:nv(g)] # Create parents array @test length(next.data) == n @inferred(LightGraphs.bfs_tree!(LevelSynchronousBFS(), next, g, T(1), parents)) @test istree(parents, n, n) diff --git a/test/traversals/randomwalks.jl b/test/traversals/randomwalks.jl index 9f372e3ee..4961cffe4 100644 --- a/test/traversals/randomwalks.jl +++ b/test/traversals/randomwalks.jl @@ -7,8 +7,8 @@ if n < 3 return true end - for i in 1:n-2 - if walk[i+2] == walk[i] + for i in 1:(n - 2) + if walk[i + 2] == walk[i] return false end end @@ -63,22 +63,22 @@ n = 10 gx = CycleGraph(n) - for k = 3:n-1 + for k = 3:(n - 1) add_edge!(gx, 1, k) end for g in testgraphs(gx) - for len = 1:3*n - @test test_nbw(g,1,len) - @test test_nbw(g,2,len) + for len = 1:(3 * n) + @test test_nbw(g, 1, len) + @test test_nbw(g, 2, len) end end #test to make sure it works with self loops. add_edge!(gx, 1, 1) for g in testgraphs(gx) - for len = 1:3*n - @test test_nbw(g,1,len) - @test test_nbw(g,2,len) + for len = 1:(3 * n) + @test test_nbw(g, 1, len) + @test test_nbw(g, 2, len) end end end diff --git a/test/utils.jl b/test/utils.jl index ae8a4f117..0e646ad99 100644 --- a/test/utils.jl +++ b/test/utils.jl @@ -1,17 +1,17 @@ @testset "Utils" begin s = @inferred(LightGraphs.sample!([1:10;], 3)) @test length(s) == 3 - for e in s + for e in s @test 1 <= e <= 10 end - s = @inferred(LightGraphs.sample!([1:10;], 6, exclude=[1,2])) + s = @inferred(LightGraphs.sample!([1:10;], 6, exclude=[1, 2])) @test length(s) == 6 for e in s @test 3 <= e <= 10 end - s = @inferred(LightGraphs.sample(1:10, 6, exclude=[1,2])) + s = @inferred(LightGraphs.sample(1:10, 6, exclude=[1, 2])) @test length(s) == 6 for e in s @test 3 <= e <= 10