forked from SciML/ModelingToolkit.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbipartite_graph.jl
273 lines (233 loc) · 7.89 KB
/
bipartite_graph.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
module BipartiteGraphs
export BipartiteEdge, BipartiteGraph
export 𝑠vertices, 𝑑vertices, has_𝑠vertex, has_𝑑vertex, 𝑠neighbors, 𝑑neighbors,
𝑠edges, 𝑑edges, nsrcs, ndsts, SRC, DST
using DocStringExtensions
using Reexport
using UnPack
using SparseArrays
@reexport using LightGraphs
using Setfield
###
### Edges & Vertex
###
@enum VertType SRC DST ALL
struct BipartiteEdge{I<:Integer} <: LightGraphs.AbstractEdge{I}
src::I
dst::I
function BipartiteEdge(src::I, dst::V) where {I,V}
T = promote_type(I, V)
new{T}(T(src), T(dst))
end
end
LightGraphs.src(edge::BipartiteEdge) = edge.src
LightGraphs.dst(edge::BipartiteEdge) = edge.dst
function Base.show(io::IO, edge::BipartiteEdge)
@unpack src, dst = edge
print(io, "[src: ", src, "] => [dst: ", dst, "]")
end
Base.:(==)(a::BipartiteEdge, b::BipartiteEdge) = src(a) == src(b) && dst(a) == dst(b)
###
### Graph
###
"""
$(TYPEDEF)
A bipartite graph representation between two, possibly distinct, sets of vertices
(source and dependencies). Maps source vertices, labelled `1:N₁`, to vertices
on which they depend (labelled `1:N₂`).
# Fields
$(FIELDS)
# Example
```julia
using ModelingToolkit
ne = 4
srcverts = 1:4
depverts = 1:2
# six source vertices
fadjlist = [[1],[1],[2],[2],[1],[1,2]]
# two vertices they depend on
badjlist = [[1,2,5,6],[3,4,6]]
bg = BipartiteGraph(7, fadjlist, badjlist)
```
"""
mutable struct BipartiteGraph{I<:Integer,F<:Vector{Vector{I}},B<:Union{Vector{Vector{I}},I},M} <: LightGraphs.AbstractGraph{I}
ne::Int
fadjlist::F # `fadjlist[src] => dsts`
badjlist::B # `badjlist[dst] => srcs` or `ndsts`
metadata::M
end
BipartiteGraph(ne::Integer, fadj::AbstractVector, badj::Union{AbstractVector,Integer}=maximum(maximum, fadj); metadata=nothing) = BipartiteGraph(ne, fadj, badj, metadata)
"""
```julia
Base.isequal(bg1::BipartiteGraph{T}, bg2::BipartiteGraph{T}) where {T<:Integer}
```
Test whether two [`BipartiteGraph`](@ref)s are equal.
"""
function Base.isequal(bg1::BipartiteGraph{T}, bg2::BipartiteGraph{T}) where {T<:Integer}
iseq = (bg1.ne == bg2.ne)
iseq &= (bg1.fadjlist == bg2.fadjlist)
iseq &= (bg1.badjlist == bg2.badjlist)
iseq
end
"""
$(SIGNATURES)
Build an empty `BipartiteGraph` with `nsrcs` sources and `ndsts` destinations.
"""
function BipartiteGraph(nsrcs::T, ndsts::T, backedge::Val{B}=Val(true); metadata=nothing) where {T,B}
fadjlist = map(_->T[], 1:nsrcs)
badjlist = B ? map(_->T[], 1:ndsts) : ndsts
BipartiteGraph(0, fadjlist, badjlist, metadata)
end
Base.eltype(::Type{<:BipartiteGraph{I}}) where I = I
function Base.empty!(g::BipartiteGraph)
foreach(empty!, g.fadjlist)
g.badjlist isa AbstractVector && foreach(empty!, g.badjlist)
g.ne = 0
if g.metadata !== nothing
foreach(empty!, g.metadata)
end
g
end
Base.length(::BipartiteGraph) = error("length is not well defined! Use `ne` or `nv`.")
@noinline throw_no_back_edges() = throw(ArgumentError("The graph has no back edges."))
if isdefined(LightGraphs, :has_contiguous_vertices)
LightGraphs.has_contiguous_vertices(::Type{<:BipartiteGraph}) = false
end
LightGraphs.is_directed(::Type{<:BipartiteGraph}) = false
LightGraphs.vertices(g::BipartiteGraph) = (𝑠vertices(g), 𝑑vertices(g))
𝑠vertices(g::BipartiteGraph) = axes(g.fadjlist, 1)
𝑑vertices(g::BipartiteGraph) = g.badjlist isa AbstractVector ? axes(g.badjlist, 1) : Base.OneTo(g.badjlist)
has_𝑠vertex(g::BipartiteGraph, v::Integer) = v in 𝑠vertices(g)
has_𝑑vertex(g::BipartiteGraph, v::Integer) = v in 𝑑vertices(g)
𝑠neighbors(g::BipartiteGraph, i::Integer, with_metadata::Val{M}=Val(false)) where M = M ? zip(g.fadjlist[i], g.metadata[i]) : g.fadjlist[i]
function 𝑑neighbors(g::BipartiteGraph, j::Integer, with_metadata::Val{M}=Val(false)) where M
g.badjlist isa AbstractVector || throw_no_back_edges()
M ? zip(g.badjlist[j], (g.metadata[i][j] for i in g.badjlist[j])) : g.badjlist[j]
end
LightGraphs.ne(g::BipartiteGraph) = g.ne
LightGraphs.nv(g::BipartiteGraph) = sum(length, vertices(g))
LightGraphs.edgetype(g::BipartiteGraph{I}) where I = BipartiteEdge{I}
nsrcs(g::BipartiteGraph) = length(𝑠vertices(g))
ndsts(g::BipartiteGraph) = length(𝑑vertices(g))
function LightGraphs.has_edge(g::BipartiteGraph, edge::BipartiteEdge)
@unpack src, dst = edge
(src in 𝑠vertices(g) && dst in 𝑑vertices(g)) || return false # edge out of bounds
insorted(𝑠neighbors(src), dst)
end
###
### Populate
###
struct NoMetadata
end
const NO_METADATA = NoMetadata()
LightGraphs.add_edge!(g::BipartiteGraph, i::Integer, j::Integer, md=NO_METADATA) = add_edge!(g, BipartiteEdge(i, j), md)
function LightGraphs.add_edge!(g::BipartiteGraph, edge::BipartiteEdge, md=NO_METADATA)
@unpack fadjlist, badjlist = g
s, d = src(edge), dst(edge)
(has_𝑠vertex(g, s) && has_𝑑vertex(g, d)) || error("edge ($edge) out of range.")
@inbounds list = fadjlist[s]
index = searchsortedfirst(list, d)
@inbounds (index <= length(list) && list[index] == d) && return false # edge already in graph
insert!(list, index, d)
if md !== NO_METADATA
insert!(g.metadata[s], index, md)
end
g.ne += 1
if badjlist isa AbstractVector
@inbounds list = badjlist[d]
index = searchsortedfirst(list, s)
insert!(list, index, s)
end
return true # edge successfully added
end
function LightGraphs.add_vertex!(g::BipartiteGraph{T}, type::VertType) where T
if type === DST
if g.badjlist isa AbstractVector
push!(g.badjlist, T[])
else
g.badjlist += 1
end
elseif type === SRC
push!(g.fadjlist, T[])
else
error("type ($type) must be either `DST` or `SRC`")
end
return true # vertex successfully added
end
###
### Edges iteration
###
LightGraphs.edges(g::BipartiteGraph) = BipartiteEdgeIter(g, Val(ALL))
𝑠edges(g::BipartiteGraph) = BipartiteEdgeIter(g, Val(SRC))
𝑑edges(g::BipartiteGraph) = BipartiteEdgeIter(g, Val(DST))
struct BipartiteEdgeIter{T,G} <: LightGraphs.AbstractEdgeIter
g::G
type::Val{T}
end
Base.length(it::BipartiteEdgeIter) = ne(it.g)
Base.length(it::BipartiteEdgeIter{ALL}) = 2ne(it.g)
Base.eltype(it::BipartiteEdgeIter) = edgetype(it.g)
function Base.iterate(it::BipartiteEdgeIter{SRC,<:BipartiteGraph{T}}, state=(1, 1, SRC)) where T
@unpack g = it
neqs = nsrcs(g)
neqs == 0 && return nothing
eq, jvar = state
while eq <= neqs
eq′ = eq
vars = 𝑠neighbors(g, eq′)
if jvar > length(vars)
eq += 1
jvar = 1
continue
end
edge = BipartiteEdge(eq′, vars[jvar])
state = (eq, jvar + 1, SRC)
return edge, state
end
return nothing
end
function Base.iterate(it::BipartiteEdgeIter{DST,<:BipartiteGraph{T}}, state=(1, 1, DST)) where T
@unpack g = it
nvars = ndsts(g)
nvars == 0 && return nothing
ieq, jvar = state
while jvar <= nvars
eqs = 𝑑neighbors(g, jvar)
if ieq > length(eqs)
ieq = 1
jvar += 1
continue
end
edge = BipartiteEdge(eqs[ieq], jvar)
state = (ieq + 1, jvar, DST)
return edge, state
end
return nothing
end
function Base.iterate(it::BipartiteEdgeIter{ALL,<:BipartiteGraph}, state=nothing)
if state === nothing
ss = iterate((@set it.type = Val(SRC)))
elseif state[3] === SRC
ss = iterate((@set it.type = Val(SRC)), state)
elseif state[3] == DST
ss = iterate((@set it.type = Val(DST)), state)
end
if ss === nothing && state[3] == SRC
return iterate((@set it.type = Val(DST)))
else
return ss
end
end
###
### Utils
###
function LightGraphs.incidence_matrix(g::BipartiteGraph, val=true)
I = Int[]
J = Int[]
for i in 𝑠vertices(g), n in 𝑠neighbors(g, i)
push!(I, i)
push!(J, n)
end
S = sparse(I, J, val, nsrcs(g), ndsts(g))
end
end # module