-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathcollapse_plot.jl
96 lines (86 loc) · 2.65 KB
/
collapse_plot.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using GraphPlot
function collapse_graph(g::AbstractGraph, membership::Vector{Int})
nb_comm = maximum(membership)
collapsed_edge_weights = Vector{Dict{Int,Float64}}(undef, nb_comm)
for i=1:nb_comm
collapsed_edge_weights[i] = Dict{Int,Float64}()
end
for e in edges(g)
u = src(e)
v = dst(e)
u_comm = membership[u]
v_comm = membership[v]
# for special case of undirected network
if !is_directed(g)
u_comm, v_comm = minmax(u_comm, v_comm)
end
if haskey(collapsed_edge_weights[u_comm], v_comm)
collapsed_edge_weights[u_comm][v_comm] += 1
else
collapsed_edge_weights[u_comm][v_comm] = 1
end
end
collapsed_graph = SimpleGraph(nb_comm)
collapsed_weights = Float64[]
for u=1:nb_comm
for (v,w) in collapsed_edge_weights[u]
add_edge!(collapsed_graph, u, v)
push!(collapsed_weights, w)
end
end
return collapsed_graph, collapsed_weights
end
function community_layout(g::AbstractGraph, membership::Vector{Int})
N = length(membership)
lx = zeros(N)
ly = zeros(N)
comms = Dict{Int,Vector{Int}}()
for (idx,lbl) in enumerate(membership)
if haskey(comms, lbl)
push!(comms[lbl], idx)
else
comms[lbl] = Int[idx]
end
end
h, w = collapse_graph(g, membership)
clx, cly = spring_layout(h)
for (lbl, nodes) in comms
θ = range(0, stop=2pi, length=(length(nodes) + 1))[1:end-1]
for (idx, node) in enumerate(nodes)
lx[node] = 1.8*length(nodes)/N*cos(θ[idx]) + clx[lbl]
ly[node] = 1.8*length(nodes)/N*sin(θ[idx]) + cly[lbl]
end
end
return lx, ly
end
function collapse_layout(g::AbstractGraph, membership::Vector{Int})
sg = Graphs.SimpleGraph(nv(g))
for e in edges(g)
u = src(e)
v = dst(e)
Graphs.add_edge!(sg, u, v)
end
N = length(membership)
lx = zeros(N)
ly = zeros(N)
comms = Dict{Int,Vector{Int}}()
for (idx,lbl) in enumerate(membership)
if haskey(comms, lbl)
push!(comms[lbl], idx)
else
comms[lbl] = Int[idx]
end
end
h, w = collapse_graph(g, membership)
clx, cly = spring_layout(h)
for (lbl, nodes) in comms
subg = sg[nodes]
sublx, subly = spring_layout(subg)
θ = range(0, stop=2pi, length=(length(nodes) + 1))[1:end-1]
for (idx, node) in enumerate(nodes)
lx[node] = 1.8*length(nodes)/N*sublx[idx] + clx[lbl]
ly[node] = 1.8*length(nodes)/N*subly[idx] + cly[lbl]
end
end
return lx, ly
end