-
Notifications
You must be signed in to change notification settings - Fork 105
/
monotonic.jl
430 lines (364 loc) · 15.4 KB
/
monotonic.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#=
Interpolate using cubic Hermite splines. The breakpoints in arrays xbp and ybp are assumed to be sorted.
Evaluate the function in all points of the array xeval.
Methods:
"Linear" yuck
"FiniteDifference" classic cubic interpolation, no tension parameter
Finite difference can overshoot for non-monotonic data
"Cardinal" cubic cardinal splines, uses tension parameter which must be between [0,1]
cubin cardinal splines can overshoot for non-monotonic data
(increasing tension decreases overshoot)
"Akima" monotonic - tangents are determined at each given point locally,
the curve obtained is close to a manually drawn curve, can overshoot for non-monotonic data
"FritschCarlson" monotonic - tangents are first initialized, then adjusted if they are not monotonic
can overshoot for non-monotonic data
"FritschButland" monotonic - faster algorithm (only requires one pass) but somewhat higher apparent "tension"
"Steffen" monotonic - also only one pass, results usually between FritschCarlson and FritschButland
Sources:
Akima (1970), "A New Method of Interpolation and Smooth Curve Fitting Based on Local Procedures", doi:10.1145/321607.321609
Fritsch & Carlson (1980), "Monotone Piecewise Cubic Interpolation", doi:10.1137/0717021.
Fritsch & Butland (1984), "A Method for Constructing Local Monotone Piecewise Cubic Interpolants", doi:10.1137/0905021.
Steffen (1990), "A Simple Method for Monotonic Interpolation in One Dimension", http://adsabs.harvard.edu/abs/1990A%26A...239..443S
Implementation based on http://bl.ocks.org/niclasmattsson/7bceb05fba6c71c78d507adae3d29417
=#
export
LinearMonotonicInterpolation,
FiniteDifferenceMonotonicInterpolation,
CardinalMonotonicInterpolation,
AkimaMonotonicInterpolation,
FritschCarlsonMonotonicInterpolation,
FritschButlandMonotonicInterpolation,
SteffenMonotonicInterpolation
"""
MonotonicInterpolationType
Abstract class for all types of monotonic interpolation.
"""
abstract type MonotonicInterpolationType <: InterpolationType end
"""
LinearMonotonicInterpolation
Simple linear interpolation.
"""
struct LinearMonotonicInterpolation <: MonotonicInterpolationType
end
"""
FiniteDifferenceMonotonicInterpolation
Classic cubic interpolation, no tension parameter.
Finite difference can overshoot for non-monotonic data.
"""
struct FiniteDifferenceMonotonicInterpolation <: MonotonicInterpolationType
end
"""
CardinalMonotonicInterpolation(tension)
Cubic cardinal splines, uses `tension` parameter which must be between [0,1]
Cubin cardinal splines can overshoot for non-monotonic data
(increasing tension reduces overshoot).
"""
struct CardinalMonotonicInterpolation{TTension<:Number} <: MonotonicInterpolationType
tension :: TTension # must be in [0, 1]
end
"""
AkimaMonotonicInterpolation
Monotonic interpolation based on [Akima (1970)
"A New Method of Interpolation and Smooth Curve Fitting Based on Local Procedures",
doi:10.1145/321607.321609](@cite Akima1970).
Tangents are determined at each given point locally,
results are close to manual drawn curves
"""
struct AkimaMonotonicInterpolation <: MonotonicInterpolationType
end
"""
FritschCarlsonMonotonicInterpolation
Monotonic interpolation based on [Fritsch & Carlson (1980),
"Monotone Piecewise Cubic Interpolation", doi:10.1137/0717021](@cite Fritsch1980).
Tangents are first initialized, then adjusted if they are not monotonic
can overshoot for non-monotonic data
"""
struct FritschCarlsonMonotonicInterpolation <: MonotonicInterpolationType
end
"""
FritschButlandMonotonicInterpolation
Monotonic interpolation based on [Fritsch & Butland (1984),
"A Method for Constructing Local Monotone Piecewise Cubic Interpolants",
doi:10.1137/0905021](@cite Fritsch1984).
Faster than FritschCarlsonMonotonicInterpolation (only requires one pass)
but somewhat higher apparent "tension".
"""
struct FritschButlandMonotonicInterpolation <: MonotonicInterpolationType
end
"""
SteffenMonotonicInterpolation
Monotonic interpolation based on [Steffen (1990),
"A Simple Method for Monotonic Interpolation in One Dimension",
http://adsabs.harvard.edu/abs/1990A%26A...239..443S](@cite Steffen1990)
Only one pass, results usually between FritschCarlson and FritschButland.
"""
struct SteffenMonotonicInterpolation <: MonotonicInterpolationType
end
"""
MonotonicInterpolation
Monotonic interpolation up to third order represented by type, knots and
coefficients.
"""
struct MonotonicInterpolation{T, TCoeffs1, TCoeffs2, TCoeffs3, TEl, TInterpolationType<:MonotonicInterpolationType,
TKnots<:AbstractVector{<:Number}, TACoeff <: AbstractArray{TEl,1}} <: AbstractInterpolation{T,1,DimSpec{TInterpolationType}}
it::TInterpolationType
knots::TKnots
A::TACoeff # constant parts of piecewise polynomials
m::Vector{TCoeffs1} # coefficients of linear parts of piecewise polynomials
c::Vector{TCoeffs2} # coefficients of quadratic parts of piecewise polynomials
d::Vector{TCoeffs3} # coefficients of cubic parts of piecewise polynomials
end
function Base.:(==)(o1::MonotonicInterpolation, o2::MonotonicInterpolation)
o1.it == o2.it &&
o1.knots == o2.knots &&
o1.A == o2.A &&
o1.m == o2.m &&
o1.c == o2.c &&
o1.d == o2.d
end
size(A::MonotonicInterpolation) = size(A.knots)
axes(A::MonotonicInterpolation) = axes(A.knots)
itpflag(A::MonotonicInterpolation) = A.it
coefficients(A::MonotonicInterpolation) = A.A
function MonotonicInterpolation(
::Type{TWeights}, it::TInterpolationType, knots::TKnots, A::AbstractArray{TEl,1},
m::Vector{TCoeffs1}, c::Vector{TCoeffs2}, d::Vector{TCoeffs3}
) where {TWeights, TCoeffs1, TCoeffs2, TCoeffs3, TEl, TInterpolationType<:MonotonicInterpolationType, TKnots<:AbstractVector{<:Number}}
isconcretetype(TInterpolationType) || error("The spline type must be a leaf type (was $TInterpolationType)")
isconcretetype(tcoef(A)) || @warn("For performance reasons, consider using an array of a concrete type (eltype(A) == $(eltype(A)))")
check_monotonic(knots, A)
cZero = zero(TWeights)
if isempty(A)
T = Base.promote_op(*, typeof(cZero), eltype(A))
else
T = typeof(cZero * first(A))
end
MonotonicInterpolation{T, TCoeffs1, TCoeffs2, TCoeffs3, TEl, TInterpolationType, TKnots, typeof(A)}(it, knots, A, m, c, d)
end
function interpolate(
::Type{TWeights}, ::Type{TCoeffs1}, ::Type{TCoeffs2}, ::Type{TCoeffs3},
knots::TKnots, A::AbstractArray{TEl,1}, it::TInterpolationType
) where {TWeights,TCoeffs1,TCoeffs2,TCoeffs3,TEl,TKnots<:AbstractVector{<:Number},TInterpolationType<:MonotonicInterpolationType}
check_monotonic(knots, A)
# first we need to determine tangents (m)
n = length(knots)
m, Δ = calcTangents(TCoeffs1, knots, A, it)
c = Vector{TCoeffs2}(undef, n-1)
d = Vector{TCoeffs3}(undef, n-1)
for k ∈ eachindex(c)
if TInterpolationType == LinearMonotonicInterpolation
c[k] = zero(TCoeffs2)
d[k] = zero(TCoeffs3)
else
xdiff = knots[k+1] - knots[k]
c[k] = (3*Δ[k] - 2*m[k] - m[k+1]) / xdiff
d[k] = (m[k] + m[k+1] - 2*Δ[k]) / (xdiff * xdiff)
end
end
MonotonicInterpolation(TWeights, it, knots, A, m, c, d)
end
function interpolate(
knots::AbstractVector{<:Number}, A::AbstractArray{TEl,1},
it::TInterpolationType
) where {TEl,TInterpolationType<:MonotonicInterpolationType}
interpolate(tweight(A),typeof(oneunit(eltype(A)) / oneunit(eltype(knots))),
typeof(oneunit(eltype(A)) / oneunit(eltype(knots))^2),
typeof(oneunit(eltype(A)) / oneunit(eltype(knots))^3),knots,A,it)
end
function (itp::MonotonicInterpolation)(x::Number)
@boundscheck (checkbounds(Bool, itp, x) || Base.throw_boundserror(itp, (x,)))
k = searchsortedfirst(itp.knots, x)
if k > 1
k -= 1
end
xdiff = x - itp.knots[k]
return itp.A[k] + itp.m[k]*xdiff + itp.c[k]*xdiff*xdiff + itp.d[k]*xdiff*xdiff*xdiff
end
function gradient(itp::MonotonicInterpolation, x::Number)
return SVector(gradient1(itp, x))
end
function gradient1(itp::MonotonicInterpolation, x::Number)
@boundscheck (checkbounds(Bool, itp, x) || Base.throw_boundserror(itp, (x,)))
k = searchsortedfirst(itp.knots, x)
if k > 1
k -= 1
end
xdiff = x - itp.knots[k]
return itp.m[k] + 2*itp.c[k]*xdiff + 3*itp.d[k]*xdiff*xdiff
end
function hessian(itp::MonotonicInterpolation, x::Number)
return SVector(hessian1(itp, x))
end
function hessian1(itp::MonotonicInterpolation, x::Number)
@boundscheck (checkbounds(Bool, itp, x) || Base.throw_boundserror(itp, (x,)))
k = searchsortedfirst(itp.knots, x)
if k > 1
k -= 1
end
xdiff = x - itp.knots[k]
return 2*itp.c[k] + 6*itp.d[k]*xdiff
end
@inline function check_monotonic(knots, A)
axes(knots) == axes(A) || throw(DimensionMismatch("knot vector must have the same axes as the corresponding array"))
issorted(knots) || error("knot-vector must be sorted in increasing order")
end
function calcTangents(::Type{TCoeffs}, x::AbstractVector{<:Number},
y::AbstractVector{TEl}, method::LinearMonotonicInterpolation) where {TCoeffs, TEl}
n = length(x)
Δ = Vector{TCoeffs}(undef, n-1)
m = Vector{TCoeffs}(undef, n)
for k ∈ eachindex(Δ)
Δ[k] = (y[k+1] - y[k]) / (x[k+1] - x[k])
m[k] = Δ[k]
end
m[n] = Δ[n-1]
return (m, Δ)
end
function calcTangents(::Type{TCoeffs}, x::AbstractVector{<:Number},
y::AbstractVector{TEl}, method::FiniteDifferenceMonotonicInterpolation) where {TCoeffs, TEl}
n = length(x)
Δ = Vector{TCoeffs}(undef, n-1)
m = Vector{TCoeffs}(undef, n)
for k ∈ eachindex(Δ)
Δ[k] = (y[k+1] - y[k]) / (x[k+1] - x[k])
if k == 1 # left endpoint
m[k] = Δ[k]
else
m[k] = (Δ[k-1] + Δ[k]) / 2
end
end
m[n] = Δ[n-1]
return (m, Δ)
end
function calcTangents(::Type{TCoeffs}, x::AbstractVector{<:Number},
y::AbstractVector{TEl}, method::CardinalMonotonicInterpolation{TTension}) where {TTension, TCoeffs, TEl}
n = length(x)
Δ = Vector{TCoeffs}(undef, n-1)
m = Vector{TCoeffs}(undef, n)
for k ∈ eachindex(Δ)
Δ[k] = (y[k+1] - y[k]) / (x[k+1] - x[k])
if k == 1 # left endpoint
m[k] = Δ[k]
else
m[k] = (oneunit(TTension) - method.tension) * (y[k+1] - y[k-1]) / (x[k+1] - x[k-1])
end
end
m[n] = Δ[n-1]
return (m, Δ)
end
function calcTangents(::Type{TCoeffs}, x::AbstractVector{<:Number},
y::AbstractVector{TEl}, method::AkimaMonotonicInterpolation) where {TCoeffs, TEl}
# based on Akima (1970),
# "A New Method of Interpolation and Smooth Curve Fitting Based on Local Procedures",
# doi:10.1145/321607.321609.
n = length(x)
Δ = Vector{TCoeffs}(undef, n-1)
m = Vector{TCoeffs}(undef, n)
for k ∈ eachindex(Δ)
Δ[k] = (y[k+1] - y[k]) / (x[k+1] - x[k])
end
Γ = [3Δ[1] - 2Δ[2]; 2Δ[1] - Δ[2]; Δ; 2Δ[n-1] - Δ[n-2]; 3Δ[n-1] - 2Δ[n-2]]
for k ∈ eachindex(m)
δ = abs(Γ[k+3] - Γ[k+2]) + abs(Γ[k+1] - Γ[k])
if δ > zero(δ)
α = abs(Γ[k+1] - Γ[k]) / δ
m[k] = (1-α) * Γ[k+1] + α * Γ[k+2]
else
m[k] = 0.5 * Γ[k+1] + 0.5 * Γ[k+2]
end
end
return (m, Δ)
end
function calcTangents(::Type{TCoeffs}, x::AbstractVector{<:Number},
y::AbstractVector{TEl}, method::FritschCarlsonMonotonicInterpolation) where {TCoeffs, TEl}
n = length(x)
Δ = Vector{TCoeffs}(undef, n-1)
m = Vector{TCoeffs}(undef, n)
buff = Vector{typeof(first(Δ)^2)}(undef, n)
for k ∈ eachindex(Δ)
Δ[k] = (y[k+1] - y[k]) / (x[k+1] - x[k])
if k == 1 # left endpoint
m[k] = Δ[k]
else
# If any consecutive secant lines change sign (i.e. curve changes direction), initialize the tangent to zero.
# This is needed to make the interpolation monotonic. Otherwise set tangent to the average of the secants.
if Δ[k-1] * Δ[k] <= zero(Δ[k]^2)
m[k] = zero(TCoeffs)
else
m[k] = (Δ[k-1] + Δ[k]) / 2.0
end
end
end
m[n] = Δ[n-1]
#=
Fritsch & Carlson derived necessary and sufficient conditions for monotonicity in their 1980 paper. Splines will be
monotonic if all tangents are in a certain region of the alpha-beta plane, with alpha and beta as defined below.
A robust choice is to put alpha & beta within a circle around origo with radius 3. The FritschCarlson algorithm
makes simple initial estimates of tangents and then does another pass over data points to move any outlier tangents
into the monotonic region. FritschButland & Steffen algorithms make more elaborate first estimates of tangents that
are guaranteed to lie in the monotonic region, so no second pass is necessary.
=#
# Second pass of FritschCarlson: adjust any non-monotonic tangents.
for k ∈ eachindex(Δ)
if Δ[k] == zero(TCoeffs)
m[k] = zero(TCoeffs)
m[k+1] = zero(TCoeffs)
continue
end
α = m[k] / Δ[k]
β = m[k+1] / Δ[k]
τ = 3.0 * oneunit(α) / sqrt(α^2 + β^2)
if τ < 1.0 # if we're outside the circle with radius 3 then move onto the circle
m[k] = τ * α * Δ[k]
m[k+1] = τ * β * Δ[k]
end
end
return (m, Δ)
end
function calcTangents(::Type{TCoeffs}, x::AbstractVector{<:Number},
y :: AbstractVector{TEl}, method :: FritschButlandMonotonicInterpolation) where {TCoeffs, TEl}
# based on Fritsch & Butland (1984),
# "A Method for Constructing Local Monotone Piecewise Cubic Interpolants",
# doi:10.1137/0905021.
n = length(x)
Δ = Vector{TCoeffs}(undef, n-1)
m = Vector{TCoeffs}(undef, n)
for k ∈ eachindex(Δ)
Δ[k] = (y[k+1] - y[k]) / (x[k+1] - x[k])
if k == 1 # left endpoint
m[k] = Δ[k]
elseif Δ[k-1] * Δ[k] <= zero(Δ[k]^2)
m[k] = zero(TCoeffs)
else
α = (1.0 + (x[k+1] - x[k]) / (x[k+1] - x[k-1])) / 3.0
m[k] = Δ[k-1] * Δ[k] / (α*Δ[k] + (1.0 - α)*Δ[k-1])
end
end
m[n] = Δ[n-1]
return (m, Δ)
end
function calcTangents(::Type{TCoeffs}, x::AbstractVector{<:Number},
y::AbstractVector{TEl}, method::SteffenMonotonicInterpolation) where {TCoeffs, TEl}
# Steffen (1990),
# "A Simple Method for Monotonic Interpolation in One Dimension",
# http://adsabs.harvard.edu/abs/1990A%26A...239..443S
n = length(x)
Δ = Vector{TCoeffs}(undef, n-1)
m = Vector{TCoeffs}(undef, n)
for k ∈ eachindex(Δ)
Δ[k] = (y[k+1] - y[k]) / (x[k+1] - x[k])
if k == 1 # left endpoint
m[k] = Δ[k]
else
p = ((x[k+1] - x[k]) * Δ[k-1] + (x[k] - x[k-1]) * Δ[k]) / (x[k+1] - x[k-1])
m[k] = (sign(Δ[k-1]) + sign(Δ[k])) *
min(abs(Δ[k-1]), abs(Δ[k]), 0.5*abs(p))
end
end
m[n] = Δ[n-1]
return (m, Δ)
end
# How many non-NoInterp dimensions are there?
count_interp_dims(::Type{<:MonotonicInterpolationType}) = 1
lbounds(itp::MonotonicInterpolation) = (first(itp.knots),)
ubounds(itp::MonotonicInterpolation) = (last(itp.knots),)