Skip to content

Commit baa418f

Browse files
jishnubdkarrasch
authored andcommitted
Respect IOContext while displaying a SparseMatrixCSC (#423)
* Respect IOContext in printing column indices * Add docstring to ColumnIndices
1 parent 2a84a1f commit baa418f

File tree

2 files changed

+30
-15
lines changed

2 files changed

+30
-15
lines changed

src/sparsematrix.jl

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,26 @@ function Base.print_array(io::IO, S::AbstractSparseMatrixCSCInclAdjointAndTransp
344344
end
345345
end
346346

347+
"""
348+
ColumnIndices(S::AbstractSparseMatrixCSC)
349+
350+
Return the column indices of the stored values in `S`.
351+
This is an internal type that is used in displaying sparse matrices,
352+
and is not a part of the public interface.
353+
"""
354+
struct ColumnIndices{Ti,S<:AbstractSparseMatrixCSC{<:Any,Ti}} <: AbstractVector{Ti}
355+
arr :: S
356+
end
357+
358+
size(C::ColumnIndices) = (nnz(C.arr),)
359+
# returns the column index of the n-th non-zero value from the column pointer
360+
@inline function getindex(C::ColumnIndices, i::Int)
361+
@boundscheck checkbounds(C, i)
362+
colptr = getcolptr(C.arr)
363+
ind = searchsortedlast(colptr, i)
364+
eltype(C)(ind)
365+
end
366+
347367
# always show matrices as `sparse(I, J, K)`
348368
function Base.show(io::IO, _S::AbstractSparseMatrixCSCInclAdjointAndTranspose)
349369
_checkbuffers(_S)
@@ -358,21 +378,7 @@ function Base.show(io::IO, _S::AbstractSparseMatrixCSCInclAdjointAndTranspose)
358378
print(io, "transpose(")
359379
end
360380
print(io, "sparse(", I, ", ")
361-
if length(I) == 0
362-
print(io, eltype(getcolptr(S)), "[]")
363-
else
364-
print(io, "[")
365-
il = nnz(S) - 1
366-
for col in 1:size(S, 2),
367-
k in getcolptr(S)[col] : (getcolptr(S)[col+1]-1)
368-
print(io, col)
369-
if il > 0
370-
print(io, ", ")
371-
il -= 1
372-
end
373-
end
374-
print(io, "]")
375-
end
381+
show(io, ColumnIndices(S))
376382
print(io, ", ", K, ", ", m, ", ", n, ")")
377383
if _S isa Adjoint || _S isa Transpose
378384
print(io, ")")

test/sparsematrix_constructors_indexing.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1574,6 +1574,15 @@ end
15741574
_show_with_braille_patterns(ioc, _filled_sparse(8, 16))
15751575
@test String(take!(io)) == "⎡⣿⣿⎤\n" *
15761576
"⎣⣿⣿⎦"
1577+
1578+
# respect IOContext while displaying J
1579+
I, J, V = shuffle(1:50), shuffle(1:50), [1:50;]
1580+
S = sparse(I, J, V)
1581+
I, J, V = I[sortperm(J)], sort(J), V[sortperm(J)]
1582+
@test repr(S) == "sparse($I, $J, $V, $(size(S,1)), $(size(S,2)))"
1583+
limctxt(x) = repr(x, context=:limit=>true)
1584+
expstr = "sparse($(limctxt(I)), $(limctxt(J)), $(limctxt(V)), $(size(S,1)), $(size(S,2)))"
1585+
@test limctxt(S) == expstr
15771586
end
15781587

15791588
@testset "issparse for specialized matrix types" begin

0 commit comments

Comments
 (0)