Skip to content

Commit e104da1

Browse files
authored
Merge pull request #1657 from Keno/kf/bpgprinting
Add pretty-printing for BipartiteGraph
2 parents 66ac7b3 + a93d288 commit e104da1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/bipartite_graph.jl

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,53 @@ function complete(g::BipartiteGraph{I}) where {I}
184184
BipartiteGraph(g.ne, g.fadjlist, badjlist)
185185
end
186186

187+
# Matrix whose only purpose is to pretty-print the bipartite graph
188+
struct BipartiteAdjacencyList
189+
u::Union{Vector{Int}, Nothing}
190+
end
191+
function Base.show(io::IO, l::BipartiteAdjacencyList)
192+
if l.u === nothing
193+
printstyled(io, '', color = :light_black)
194+
elseif isempty(l.u)
195+
printstyled(io, '', color = :light_black)
196+
else
197+
print(io, l.u)
198+
end
199+
end
200+
201+
struct Label
202+
s::String
203+
end
204+
Base.show(io::IO, l::Label) = print(io, l.s)
205+
206+
struct BipartiteGraphPrintMatrix <:
207+
AbstractMatrix{Union{Label, Int, BipartiteAdjacencyList}}
208+
bpg::BipartiteGraph
209+
end
210+
Base.size(bgpm::BipartiteGraphPrintMatrix) = (max(nsrcs(bgpm.bpg), ndsts(bgpm.bpg)) + 1, 3)
211+
function Base.getindex(bgpm::BipartiteGraphPrintMatrix, i::Integer, j::Integer)
212+
checkbounds(bgpm, i, j)
213+
if i == 1
214+
return (Label.(("#", "src", "dst")))[j]
215+
elseif j == 1
216+
return i - 1
217+
elseif j == 2
218+
return BipartiteAdjacencyList(i - 1 <= nsrcs(bgpm.bpg) ?
219+
𝑠neighbors(bgpm.bpg, i - 1) : nothing)
220+
elseif j == 3
221+
return BipartiteAdjacencyList(i - 1 <= ndsts(bgpm.bpg) ?
222+
𝑑neighbors(bgpm.bpg, i - 1) : nothing)
223+
else
224+
@assert false
225+
end
226+
end
227+
228+
function Base.show(io::IO, b::BipartiteGraph)
229+
print(io, "BipartiteGraph with (", length(b.fadjlist), ", ",
230+
isa(b.badjlist, Int) ? b.badjlist : length(b.badjlist), ") (𝑠,𝑑)-vertices\n")
231+
Base.print_matrix(io, BipartiteGraphPrintMatrix(b))
232+
end
233+
187234
"""
188235
```julia
189236
Base.isequal(bg1::BipartiteGraph{T}, bg2::BipartiteGraph{T}) where {T<:Integer}

0 commit comments

Comments
 (0)