-
Notifications
You must be signed in to change notification settings - Fork 33
/
replace_missing.jl
78 lines (70 loc) · 2.4 KB
/
replace_missing.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
replace_missing(a::AbstractRaster, newmissingval)
replace_missing(a::AbstractRasterStack, newmissingval)
Replace missing values in the array or stack with a new missing value,
also updating the `missingval` field/s.
# Keywords
$FILENAME_KEYWORD
$SUFFIX_KEYWORD
# Example
```jldoctest
using Rasters, RasterDataSources, ArchGDAL
A = Raster(WorldClim{Climate}, :prec; month=1) |> replace_missing
missingval(A)
# output
missing
```
"""
replace_missing(x; missingval=missing, kw...) = replace_missing(x, missingval; kw...)
function replace_missing(A::AbstractRaster{T}, missingval::MV;
filename=nothing, suffix=nothing
) where {T,MV}
MT = if ismissing(missingval)
promote_type(T, Missing)
else
promote_type(nonmissingtype(T), MV)
end
old_missingval = Rasters.missingval(A)
missingval = convert(MT, missingval)
repmissing(x) = isequal(x, old_missingval) || ismissing(x) ? missingval : x
# Disk-backed arrays need to be lazy, memory-backed don't.
# But in both cases we make sure we return an array with the missingval
# in the eltype, even if there are no missing values in the array.
if !isnothing(filename)
A1 = create(filename, MT, dims(A);
parent=parent(A), suffix, missingval, name=name(A), metadata=metadata(A)
)
open(A1; write=true) do O
O .= repmissing.(A)
end
return A1
else
# We need to force T of Union{T,Missing} for DiskArrays broadcasts
if isdisk(A)
data = repmissing.(parent(A))
if missingval isa Missing
data = MissingDiskArray(MT, data)
end
else
data = similar(parent(A), MT)
data .= repmissing.(parent(A))
end
return rebuild(A; data, missingval)
end
end
function replace_missing(st::AbstractRasterStack, args...; suffix=keys(st), kw...)
mapargs(st, suffix) do A, s
replace_missing(A, args...; suffix=s, kw...)
end
end
function replace_missing(s::AbstractRasterSeries, args...; kw...)
map(x -> replace_missing(x, args...; kw...), s)
end
function replace_missing!(s::RasterSeriesOrStack, args...; kw...)
map(x -> replace_missing!(x, args...; kw...), s)
end
function replace_missing!(A::AbstractRaster, missingval=missing)
repmissing(x) = isequal(x, Rasters.missingval(A)) ? missingval : x
A .= repmissing.(A)
return rebuild(A; missingval)
end