@@ -4,7 +4,7 @@ module HigherOrderFns
44
55# This module provides higher order functions specialized for sparse arrays,
66# particularly map[!]/broadcast[!] for SparseVectors and SparseMatrixCSCs at present.
7- import Base: map, map!, broadcast, copy, copyto!
7+ import Base: map, map!, broadcast, copy, copyto!, extrema
88
99using Base: front, tail, to_shape
1010using .. SparseArrays: SparseVector, SparseMatrixCSC, AbstractSparseVector, AbstractSparseMatrixCSC,
@@ -29,6 +29,7 @@ using LinearAlgebra
2929# (11) Define broadcast[!] methods handling combinations of scalars, sparse vectors/matrices,
3030# structured matrices, and one- and two-dimensional Arrays.
3131# (12) Define map[!] methods handling combinations of sparse and structured matrices.
32+ # (13) Define extrema methods optimized for sparse vectors/matrices.
3233
3334
3435# (0) BroadcastStyle rules and convenience types for dispatch
@@ -1154,4 +1155,27 @@ map(f::Tf, A::SparseOrStructuredMatrix, Bs::Vararg{SparseOrStructuredMatrix,N})
11541155map! (f:: Tf , C:: AbstractSparseMatrixCSC , A:: SparseOrStructuredMatrix , Bs:: Vararg{SparseOrStructuredMatrix,N} ) where {Tf,N} =
11551156 (_checksameshape (C, A, Bs... ); _noshapecheck_map! (f, C, _sparsifystructured (A), map (_sparsifystructured, Bs)... ))
11561157
1158+
1159+ # (13) extrema methods optimized for sparse vectors/matrices.
1160+ function extrema_ (f, A:: SparseVecOrMat )
1161+ M = length (A)
1162+ iszero (M) && throw (ArgumentError (" Sparse array must have at least one element." ))
1163+ N = nnz (A)
1164+ iszero (N) && return f (zero (eltype (A))), f (zero (eltype (A)))
1165+ vmin, vmax = extrema (f, nonzeros (A))
1166+ if N != M
1167+ f0 = f (zero (eltype (A)))
1168+ vmin = min (f0, vmin)
1169+ vmax = max (f0, vmax)
1170+ end
1171+ vmin, vmax
1172+ end
1173+
1174+ extrema (A:: SparseVecOrMat ; dims= :) = extrema (identity, A, dims= dims)
1175+ extrema (f, A:: SparseVecOrMat ; dims= :) = extrema_ (f, A, dims)
1176+ extrema_ (f, x:: SparseVector , :: Colon ) = extrema_ (f, x)
1177+ extrema_ (f, A:: AbstractSparseMatrixCSC , :: Colon ) = extrema_ (f, A)
1178+ extrema_ (f, x:: SparseVector , dims) = invoke (extrema, Tuple{Any, AbstractArray}, f, x; dims= dims)
1179+ extrema_ (f, A:: AbstractSparseMatrixCSC , dims) = invoke (extrema, Tuple{Any, AbstractArray}, f, A; dims= dims)
1180+
11571181end
0 commit comments