@@ -4,7 +4,7 @@ module HigherOrderFns
4
4
5
5
# This module provides higher order functions specialized for sparse arrays,
6
6
# 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
8
8
9
9
using Base: front, tail, to_shape
10
10
using .. SparseArrays: SparseVector, SparseMatrixCSC, AbstractSparseVector, AbstractSparseMatrixCSC,
@@ -29,6 +29,7 @@ using LinearAlgebra
29
29
# (11) Define broadcast[!] methods handling combinations of scalars, sparse vectors/matrices,
30
30
# structured matrices, and one- and two-dimensional Arrays.
31
31
# (12) Define map[!] methods handling combinations of sparse and structured matrices.
32
+ # (13) Define extrema methods optimized for sparse vectors/matrices.
32
33
33
34
34
35
# (0) BroadcastStyle rules and convenience types for dispatch
@@ -1154,4 +1155,27 @@ map(f::Tf, A::SparseOrStructuredMatrix, Bs::Vararg{SparseOrStructuredMatrix,N})
1154
1155
map! (f:: Tf , C:: AbstractSparseMatrixCSC , A:: SparseOrStructuredMatrix , Bs:: Vararg{SparseOrStructuredMatrix,N} ) where {Tf,N} =
1155
1156
(_checksameshape (C, A, Bs... ); _noshapecheck_map! (f, C, _sparsifystructured (A), map (_sparsifystructured, Bs)... ))
1156
1157
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
+
1157
1181
end
0 commit comments