Skip to content

Commit b6a93bd

Browse files
committed
Re-implement reducedim_init for extrema
1 parent 065a28f commit b6a93bd

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

base/reducedim.jl

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,41 @@ for (f1, f2, initval, typeextreme) in ((:min, :max, :Inf, :typemax), (:max, :min
164164
end
165165
end
166166
end
167+
168+
function reducedim_init(f::ExtremaMap, op::typeof(_extrema_rf), A::AbstractArray, region)
169+
# First compute the reduce indices. This will throw an ArgumentError
170+
# if any region is invalid
171+
ri = reduced_indices(A, region)
172+
173+
# Next, throw if reduction is over a region with length zero
174+
any(i -> isempty(axes(A, i)), region) && _empty_reduce_error()
175+
176+
# Make a view of the first slice of the region
177+
A1 = view(A, ri...)
178+
179+
isempty(A1) && return map(f, A1)
180+
# use the max/min of the first slice as initial value for non-empty cases
181+
v0 = reverse(mapreduce(f, op, A1)) # turn minmax to maxmin
182+
183+
T = _realtype(f.f, promote_union(eltype(A)))
184+
Tr = v0[1] isa T && v0[2] isa T ? NTuple{2,T} : typeof(v0)
185+
186+
# but NaNs and missing need to be avoided as initial values
187+
if v0[1] isa Number && isnan(v0[1])
188+
v0 = oftype(v0[1], Inf), oftype(v0[2], -Inf)
189+
elseif isunordered(v0[1])
190+
# v0 is missing or a third-party unordered value
191+
T1, T2 = Tr.parameters
192+
# TODO: Some types, like BigInt, don't support typemin/typemax.
193+
# So a Matrix{Union{BigInt, Missing}} can still error here.
194+
v0 = typemax(nonmissingtype(T1)), typemin(nonmissingtype(T2))
195+
end
196+
# v0 may have changed type.
197+
Tr = v0[1] isa T && v0[2] isa T ? NTuple{2,T} : typeof(v0)
198+
199+
return reducedim_initarray(A, region, v0, Tr)
200+
end
201+
167202
reducedim_init(f::Union{typeof(abs),typeof(abs2)}, op::typeof(max), A::AbstractArray{T}, region) where {T} =
168203
reducedim_initarray(A, region, zero(f(zero(T))), _realtype(f, T))
169204

0 commit comments

Comments
 (0)