Skip to content
Draft
1 change: 1 addition & 0 deletions .typos.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
[default.extend-words]
Commun = "Commun"
Comput = "Comput"
Numer = "Numer"

# Additional SciML terms
setp = "setp"
Expand Down
25 changes: 25 additions & 0 deletions benchmark/benchmarks.jl
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,16 @@ SUITE["eval"]["cubic_vector"] = @benchmarkable $cubic($t_eval)
SUITE["eval"]["akima_vector"] = @benchmarkable $akima($t_eval)
SUITE["eval"]["constant_vector"] = @benchmarkable $const_interp($t_eval)

hermite_knots = Int64.(0:2:398)
hermite_queries = Int64.(1:2:397)
hermite_out = zeros(length(hermite_queries))
cached_hermite = CubicHermiteSpline(
0.0625 .* cos.(0.0625 .* hermite_knots), sin.(0.0625 .* hermite_knots),
hermite_knots; cache_parameters = true
)
SUITE["eval"]["cached_hermite_integer_queries"] =
@benchmarkable $cached_hermite($hermite_out, $hermite_queries)

# =============================================================================
# Derivatives
# =============================================================================
Expand All @@ -68,3 +78,18 @@ umat = rand(rng, 5, 200)
lin_vv = LinearInterpolation(umat, t)
SUITE["vector_valued"]["construct"] = @benchmarkable LinearInterpolation($umat, $t)
SUITE["vector_valued"]["eval"] = @benchmarkable $lin_vv(5.4321)

integral_knots = Float64.(0:11)
integral_values = [sin(0.2 * i + 0.1 * t) for i in 1:8, t in integral_knots]
integral_slopes = [0.1 * cos(0.2 * i + 0.1 * t) for i in 1:8, t in integral_knots]
for (group, knots) in (("integral", integral_knots), ("integer_integral", Int64.(integral_knots)))
SUITE["vector_valued"][group] = BenchmarkGroup()
for A in (
AkimaInterpolation(integral_values, knots),
CubicHermiteSpline(integral_slopes, integral_values, knots),
CubicSpline(integral_values, knots),
)
SUITE["vector_valued"][group][string(nameof(typeof(A)))] =
@benchmarkable DataInterpolations.integral($A, 0.25, 10.75)
end
end
1 change: 1 addition & 0 deletions docs/src/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ corresponding to `(u,t)` pairs.
- `BSplineApprox(u,t,d,h,knotVec)` - A regression B-spline which smooths the fitting curve. The argument choices are the same as the `BSplineInterpolation`, with the additional parameter `h<length(t)` which is the number of control points to use, with smaller `h` indicating more smoothing.
- `CubicHermiteSpline(du, u, t)` - A third order Hermite interpolation, which matches the values and first (`du`) order derivatives in the data points exactly.
- `PCHIPInterpolation(u, t)` - a type of `CubicHermiteSpline` where the derivative values `du` are derived from the input data in such a way that the interpolation never overshoots the data.
- `MonotonicMakimaInterpolation(u, t)` - a type of `CubicHermiteSpline` that uses the modified Akima (makima) derivative values, limited so that the interpolation is monotone wherever the data is and never overshoots the data.
- `QuinticHermiteSpline(ddu, du, u, t)` - a fifth order Hermite interpolation, which matches the values and first (`du`) and second (`ddu`) order derivatives in the data points exactly.
- `SmoothArcLengthInterpolation(u)` - A C¹ smooth, unit-speed (arc-length parameterized) interpolation through `u` given in matrix form `(ndim, ndata)`, approximated with line and circle segments. Unlike the methods above, `t` is derived from `u` rather than supplied by the user. See [Smooth arc length interpolation](arclength_interpolation.md) for details.

Expand Down
1 change: 1 addition & 0 deletions docs/src/manual.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ BSplineInterpolation
BSplineApprox
CubicHermiteSpline
PCHIPInterpolation
MonotonicMakimaInterpolation
QuinticHermiteSpline
```

Expand Down
9 changes: 9 additions & 0 deletions docs/src/methods.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,15 @@ A = PCHIPInterpolation(u, t)
plot(A)
```

## Monotonic Makima Interpolation

This is a type of `CubicHermiteSpline` whose derivative values `du` are the modified Akima (makima) slopes of `AkimaInterpolation(u, t; modified = true)`, passed through a Fritsch–Carlson monotonicity limiter: slopes at local extrema and next to flat segments are set to zero, and on each segment the end slopes are scaled back so that `du / secant` lies in the square `[0, 3]²`. Like PCHIP, the interpolation never overshoots the data and is monotone wherever the data is; where the limiter does not act, it is identical to makima. See [`MonotonicMakimaInterpolation`](@ref) for the precise algorithm.

```@example tutorial
A = MonotonicMakimaInterpolation(u, t)
plot(A)
```

## Quintic Hermite Spline

This is the quintic (fifth order) Hermite interpolation. It matches the values and first and second order derivatives in the data points exactly.
Expand Down
7 changes: 6 additions & 1 deletion src/DataInterpolations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ A(1.5)
"""
@enumx ExtrapolationType None Constant Linear Extension Periodic Reflective

const FixedWidthInteger = Union{
Bool, Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128,
}

include("parameter_caches.jl")
include("interpolation_caches.jl")
include("interpolation_utils.jl")
Expand Down Expand Up @@ -248,7 +252,8 @@ _output_size(u::AbstractArray) = Base.front(size(u))
export LinearInterpolation, QuadraticInterpolation, LagrangeInterpolation,
AkimaInterpolation, ConstantInterpolation, SmoothedConstantInterpolation,
QuadraticSpline, CubicSpline, BSplineInterpolation, BSplineApprox,
CubicHermiteSpline, PCHIPInterpolation, QuinticHermiteSpline,
CubicHermiteSpline, PCHIPInterpolation, MonotonicMakimaInterpolation,
QuinticHermiteSpline,
SmoothArcLengthInterpolation, LinearInterpolationIntInv,
ConstantInterpolationIntInv, ExtrapolationType
export output_dim, output_size
Expand Down
20 changes: 14 additions & 6 deletions src/derivatives.jl
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ DataInterpolations.derivative(A, 2.5)
"""
function derivative(A, t, order = 1)
(order ∉ (1, 2)) && throw(DerivativeNotFoundError())
order == 2 && (t = _second_derivative_query(A, t))
if t < first(A.t)
_extrapolate_derivative_left(A, t, order)
elseif t > last(A.t)
Expand All @@ -52,6 +53,13 @@ function derivative(A, t, order = 1)
end
end

_second_derivative_query(A, t) = t
function _second_derivative_query(A::Union{AkimaInterpolation, CubicHermiteSpline}, t::FixedWidthInteger)
knot = first(A.t)
# The backwards ForwardDiff pass negates both the query and its perturbation.
return knot isa FixedWidthInteger ? _signed_widen(t) - _signed_widen(zero(knot)) : _signed_widen(t)
end

# Zero of the derivative's value type, shaped like one data point.
function _zero_derivative(A)
u₁ = _first(A.u)
Expand Down Expand Up @@ -310,14 +318,14 @@ end
function _derivative(A::AkimaInterpolation{<:AbstractVector{<:Number}}, t::Number, iguess)
idx = get_idx(A, t, iguess; idx_shift = -1, side = :first)
j = min(idx, length(A.c)) # for smooth derivative at A.t[end]
wj = t - A.t[idx]
wj = _widened_difference(t, A.t[idx])
return @evalpoly wj A.b[idx] 2A.c[j] 3A.d[j]
end

function _derivative(A::AkimaInterpolation{<:AbstractArray}, t::Number, iguess)
idx = get_idx(A, t, iguess; idx_shift = -1, side = :first)
j = min(idx, length(A.t) - 1) # for smooth derivative at A.t[end]
wj = t - A.t[idx]
wj = _widened_difference(t, A.t[idx])
bᵢ = _u_view(A.b, idx)
cⱼ = _u_view(A.c, j)
dⱼ = _u_view(A.d, j)
Expand Down Expand Up @@ -532,8 +540,8 @@ function _derivative(
A::CubicHermiteSpline{<:AbstractVector{<:Number}}, t::Number, iguess
)
idx = get_idx(A, t, iguess)
Δt₀ = t - A.t[idx]
Δt₁ = t - A.t[idx + 1]
Δt₀ = _widened_difference(t, A.t[idx])
Δt₁ = _widened_difference(t, A.t[idx + 1])
out = A.du[idx]
c₁, c₂ = get_parameters(A, idx)
out += Δt₀ * (Δt₀ * c₂ + 2(c₁ + Δt₁ * c₂))
Expand All @@ -544,8 +552,8 @@ function _derivative(
A::CubicHermiteSpline{<:AbstractArray}, t::Number, iguess
)
idx = get_idx(A, t, iguess)
Δt₀ = t - A.t[idx]
Δt₁ = t - A.t[idx + 1]
Δt₀ = _widened_difference(t, A.t[idx])
Δt₁ = _widened_difference(t, A.t[idx + 1])
out = _u_view(A.du, idx)
c₁, c₂ = get_parameters(A, idx)
out = out + Δt₀ * (Δt₀ * c₂ + 2(c₁ + Δt₁ * c₂))
Expand Down
12 changes: 6 additions & 6 deletions src/integrals.jl
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,10 @@ function _extrapolate_integral_left(A, t)
return if extrapolation_left == ExtrapolationType.None
throw(LeftExtrapolationError())
elseif extrapolation_left == ExtrapolationType.Constant
_first(A.u) * (first(A.t) - t)
_first(A.u) * _extrapolation_difference(A, first(A.t), t)
elseif extrapolation_left == ExtrapolationType.Linear
slope = derivative(A, first(A.t))
Δt = first(A.t) - t
Δt = _extrapolation_difference(A, first(A.t), t)
u₁ = _first(A.u)
@. (u₁ - slope * Δt / 2) * Δt
elseif extrapolation_left == ExtrapolationType.Extension
Expand Down Expand Up @@ -173,10 +173,10 @@ function _extrapolate_integral_right(A, t)
return if extrapolation_right == ExtrapolationType.None
throw(RightExtrapolationError())
elseif extrapolation_right == ExtrapolationType.Constant
_last(A.u) * (t - last(A.t))
_last(A.u) * _extrapolation_difference(A, t, last(A.t))
elseif extrapolation_right == ExtrapolationType.Linear
slope = derivative(A, last(A.t))
Δt = t - last(A.t)
Δt = _extrapolation_difference(A, t, last(A.t))
uₙ = _last(A.u)
@. (uₙ + slope * Δt / 2) * Δt
elseif extrapolation_right == ExtrapolationType.Extension
Expand Down Expand Up @@ -592,7 +592,7 @@ function _integral(
c₁, c₂ = get_parameters(A, idx)
tᵢ = A.t[idx]
tᵢ₊₁ = A.t[idx + 1]
c = c₁ - c₂ * (tᵢ₊₁ - tᵢ)
c = c₁ - c₂ * _widened_difference(tᵢ₊₁, tᵢ)
return integrate_cubic_polynomial(t1, t2, tᵢ, A.u[idx], A.du[idx], c, c₂)
end

Expand All @@ -602,7 +602,7 @@ function _integral(
c₁, c₂ = get_parameters(A, idx)
tᵢ = A.t[idx]
tᵢ₊₁ = A.t[idx + 1]
c = c₁ - c₂ * (tᵢ₊₁ - tᵢ)
c = c₁ - c₂ * _widened_difference(tᵢ₊₁, tᵢ)
uᵢ = _u_view(A.u, idx)
duᵢ = _u_view(A.du, idx)
return integrate_cubic_polynomial(t1, t2, tᵢ, uᵢ, duᵢ, c, c₂)
Expand Down
146 changes: 129 additions & 17 deletions src/interpolation_caches.jl
Original file line number Diff line number Diff line change
Expand Up @@ -361,24 +361,31 @@ struct AkimaInterpolation{
end
end

# In-place scalar kernel for computing the Akima / makima coefficients.
# Allocates a single length-(n+3) buffer for the padded divided differences;
# every other intermediate (dm, f1, f2, f12, w1, w2, ind, b-default) from the
# original vectorized formulation is fused into a scalar pass.
function _akima_init!(
b::AbstractVector{T}, c::AbstractVector{T}, d::AbstractVector{T},
# In-place scalar kernel for the Akima / makima knot slopes `b` (length n).
# `m` is a length-(n+3) buffer that is filled with the padded divided differences:
# `m[k + 2]` is the secant of segment `k` (k = 1, ..., n - 1), and `m[1:2]`,
# `m[n + 2:n + 3]` are the linearly extrapolated ghost secants. Every other intermediate
# (dm, f1, f2, f12, w1, w2, ind, b-default) of the original vectorized formulation is
# fused into a scalar pass.
function _akima_slopes!(
b::AbstractVector{T}, m::AbstractVector{T},
u::AbstractVector, t::AbstractVector, ::Val{modified}
) where {T, modified}
n = length(u)
m = Vector{T}(undef, n + 3)
@inbounds begin
for i in 1:(n - 1)
m[i + 2] = (u[i + 1] - u[i]) / (t[i + 1] - t[i])
m[i + 2] = _widened_difference(u[i + 1], u[i]) / _widened_difference(t[i + 1], t[i])
end
if n == 2
# A single secant: its linear extrapolation is the secant itself, which
# makes both knot slopes equal to it (a straight line).
m[1] = m[2] = m[4] = m[5] = m[3]
else
m[2] = 2 * m[3] - m[4]
m[1] = 2 * m[2] - m[3]
m[n + 2] = 2 * m[n + 1] - m[n]
m[n + 3] = 2 * m[n + 2] - m[n + 1]
end
m[2] = 2 * m[3] - m[4]
m[1] = 2 * m[2] - m[3]
m[n + 2] = 2 * m[n + 1] - m[n]
m[n + 3] = 2 * m[n + 2] - m[n + 1]

# First pass: maximum weight, used as the small-weight cutoff
wmax = zero(T)
Expand All @@ -393,7 +400,7 @@ function _akima_init!(
w12 = w1 + w2
wmax = ifelse(w12 > wmax, w12, wmax)
end
tol = T(1.0e-9) * wmax
tol = oftype(one(T), 1.0e-9) * wmax

# Second pass: coefficients
for i in 1:n
Expand All @@ -413,16 +420,28 @@ function _akima_init!(
# `ifelse`, not `?:`, so `u` may hold symbolic (e.g. Symbolics.Num) entries.
full = w12 > tol
part = 2 * w12 > tol
s = ifelse(part, ifelse(w1 > w2, w1, w2), one(w12))
s = ifelse(part, ifelse(w1 > w2, w1, w2), oneunit(w12))
bw = (w1 / s * m[i + 1] + w2 / s * m[i + 2]) / ifelse(part, w12 / s, one(w12))
λ = 2 * w12 / ifelse(part, tol, one(tol)) - 1
λ = 2 * w12 / ifelse(part, tol, oneunit(tol)) - 1
b[i] = ifelse(full, bw, ifelse(part, bdefault + λ * (bw - bdefault), bdefault))
end
end
return nothing
end

# In-place scalar kernel for computing the Akima / makima coefficients.
function _akima_init!(
b::AbstractVector{T}, c::AbstractVector{T}, d::AbstractVector{T},
u::AbstractVector, t::AbstractVector, ::Val{modified}
) where {T, modified}
n = length(u)
m = Vector{T}(undef, n + 3)
_akima_slopes!(b, m, u, t, Val(modified))
@inbounds begin
for i in 1:(n - 1)
dt = t[i + 1] - t[i]
dt = _widened_difference(t[i + 1], t[i])
c[i] = (3 * m[i + 2] - 2 * b[i] - b[i + 1]) / dt
d[i] = (b[i] + b[i + 1] - 2 * m[i + 2]) / (dt * dt)
d[i] = _divide_by_square(b[i] + b[i + 1] - 2 * m[i + 2], dt, _square_or_nothing(dt))
end
end
return nothing
Expand Down Expand Up @@ -1835,6 +1854,99 @@ function PCHIPInterpolation(u, t; kwargs...)
return CubicHermiteSpline(du, u, t; kwargs...)
end

"""
MonotonicMakimaInterpolation(u, t; extrapolation::ExtrapolationType.T = ExtrapolationType.None, extrapolation_left::ExtrapolationType.T = ExtrapolationType.None,
extrapolation_right::ExtrapolationType.T = ExtrapolationType.None, cache_parameters = false)

A shape-preserving variant of the modified Akima (makima) interpolation. It is a
[`CubicHermiteSpline`](@ref) whose derivative values `du` are the makima slopes of
[`AkimaInterpolation`](@ref) with `modified = true`, passed through a Fritsch–Carlson
monotonicity limiter. On every segment where the data is monotone the interpolant is
monotone, it never overshoots the data (local extrema of the interpolant are at data
points), and flat segments of the data stay flat. Where steps 2 and 3 below leave the
slopes unchanged, the interpolant is identical to `AkimaInterpolation(u, t; modified = true)`.

With secants `s_k = (u[k + 1] - u[k]) / (t[k + 1] - t[k])`, the slope `d_i` at knot `i` is
computed in three steps:

1. **Makima slopes.** `d_i = (w₁ s_{i-1} + w₂ s_i) / (w₁ + w₂)` with
`w₁ = |s_{i+1} - s_i| + |s_{i+1} + s_i| / 2` and
`w₂ = |s_{i-1} - s_{i-2}| + |s_{i-1} + s_{i-2}| / 2`. Missing secants at the ends are
linearly extrapolated (`s_0 = 2s_1 - s_2`, `s_{-1} = 2s_0 - s_1` and the mirror image on
the right), and `d_i = 0` when `w₁ = w₂ = 0` (the adjacent secants are then both 0).
These are exactly the slopes of `AkimaInterpolation(u, t; modified = true)`, including
its fallback to the mean of the adjacent secants when both weights are negligible
compared with the largest weight.
2. **Sign pass.** `d_i` is set to `0` if its sign differs from the sign of an adjacent
secant (`s_{i-1}` or `s_i`; only one of them at the end points), or if an adjacent
secant is `0`. Local extrema of the data and flat segments therefore get zero slopes.
3. **Square Fritsch–Carlson limiter.** For each segment `k` with `s_k ≠ 0`, processed
from left to right, let `α = d_k / s_k` and `β = d_{k+1} / s_k` (both `≥ 0` after
step 2). If `max(α, β) > 3`, both end slopes of the segment are multiplied by the
same factor `τ = 3 / max(α, β)`, i.e. `(α, β)` is projected radially onto the boundary
of the square `[0, 3]²`, keeping the ratio `α : β`. In floating point the larger
scaled slope is `3 s_k` up to rounding (within a few ulps), not exactly `3 s_k`. A
slope shared with the previous segment can only shrink (`τ ≤ 1`), so all segments end
up inside the square, up to that rounding.

Fritsch & Carlson (1980) show that a cubic Hermite segment is monotone if and only if
`(α, β)` lies in a certain region of the first quadrant, which contains the square `[0, 3]²`.
Their algorithm limits `(α, β)` to the disk of radius 3 instead, with the scaling factor
`τ = 3 / √(α² + β²)`; the square used here is a larger subset of the monotonicity region,
so it modifies the makima slopes less often and less strongly (for example `(α, β) = (3, 3)`
is left unchanged). Fritsch–Butland type methods such as [`PCHIPInterpolation`](@ref)
(weighted harmonic mean of the secants) and the method of Steffen (1990) differ in that they
do not limit an existing slope: they define the slope by a formula that lies in the
monotonicity region by construction, so they do not reduce to makima on smooth data.

References:

- F. N. Fritsch and R. E. Carlson, "Monotone Piecewise Cubic Interpolation",
SIAM J. Numer. Anal. 17(2), 238–246 (1980), doi:10.1137/0717021.
- C. Moler, "Makima Piecewise Cubic Interpolation", [https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/](https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/).

With 2 data points the interpolant is the straight line through them.

# Arguments

- `u`: data points.
- `t`: time points.

# Keywords

- `extrapolation`: The extrapolation type applied left and right of the data. Possible options
are `ExtrapolationType.None` (default), `ExtrapolationType.Constant`, `ExtrapolationType.Linear`
`ExtrapolationType.Extension`, `ExtrapolationType.Periodic` and `ExtrapolationType.Reflective`.
- `extrapolation_left`: The extrapolation type applied left of the data. See `extrapolation` for
the possible options. This keyword is ignored if `extrapolation != ExtrapolationType.None`.
- `extrapolation_right`: The extrapolation type applied right of the data. See `extrapolation` for
the possible options. This keyword is ignored if `extrapolation != ExtrapolationType.None`.
- `cache_parameters`: precompute parameters at initialization for faster interpolation computations. Note: if activated, `u` and `t` should not be modified. Defaults to `false`.
- `search_properties`: a pre-built `FindFirstFunctions.SearchProperties` for `t`, used
to skip the construction-time knot probe or override its result (e.g. built with
`is_uniform = true`). Defaults to `nothing`, which probes `t` automatically.

# Examples

```julia
using DataInterpolations

u = [0.0, 0.0, 0.01, 10.0, 10.0, 10.0]
t = [0.0, 1.0, 2.0, 2.05, 3.0, 4.0]
A = MonotonicMakimaInterpolation(u, t)
A(0.5) # 0.0, whereas makima undershoots to about -0.00047 here
```
"""
function MonotonicMakimaInterpolation(u, t; kwargs...)
u, t = munge_data(u, t)
# Checked here (rather than in the delegated `CubicHermiteSpline` constructor) so the
# error names `MonotonicMakimaInterpolation` and fires before the slopes are computed.
check_no_duplicate_t(:MonotonicMakimaInterpolation, t)
check_min_length(:MonotonicMakimaInterpolation, 2, t)
du = du_monotonic_makima(u, t)
return CubicHermiteSpline(du, u, t; kwargs...)
end

"""
QuinticHermiteSpline(ddu, du, u, t; extrapolation_left::ExtrapolationType.T = ExtrapolationType.None,
extrapolation_right::ExtrapolationType.T = ExtrapolationType.None)
Expand Down
Loading