Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
33ba421
Add MonotonicMakimaInterpolation (makima slopes + Fritsch-Carlson lim…
asinghvi17 Nov 12, 2026
182f2b2
MonotonicMakima: square limiter multiplies both slopes by r = 3/max(α…
asinghvi17 Nov 12, 2026
6649f8b
MonotonicMakima: trim tests and docs example
asinghvi17 Nov 12, 2026
9356087
typos: allow the journal abbreviation "Numer"
asinghvi17 Nov 12, 2026
e1fefbb
Fix monotonic makima slope overflow and promoted buffers
asinghvi17 Nov 17, 2026
b4d3f1b
Fix limiter comment wording
asinghvi17 Nov 17, 2026
8664bce
Merge remote-tracking branch 'upstream/master' into factory/c4e20194-…
asinghvi17 Nov 30, 2026
73afda2
Protect PCHIP and Hermite arithmetic from integer and float overflow
asinghvi17 Nov 30, 2026
d79c9df
Guard Akima intermediates and preserve symbolic numeric safeguards
asinghvi17 Nov 30, 2026
f7fb8c6
Format arithmetic safeguards and regression fixtures
asinghvi17 Nov 30, 2026
e3be3d9
Retain Hermite rounding for safe integer knot spacings
asinghvi17 Nov 30, 2026
8abe1e5
Defer symbolic Akima scaling until numeric substitution
asinghvi17 Nov 30, 2026
099b14d
Use primal weight decisions and retain affine AD sensitivities
asinghvi17 Nov 30, 2026
d1be3ee
Guard shared secants and Hermite coefficient intermediates
asinghvi17 Nov 30, 2026
60c9180
Retain wide-range secants and share symbolic and AD recovery
asinghvi17 Nov 30, 2026
479d053
Allow the ForwardDiff partial accessor used by guarded AD
asinghvi17 Nov 30, 2026
1a03cf1
Keep scalar Hermite broadcasting compatible with Zygote
asinghvi17 Nov 30, 2026
ba0e561
Simplify arithmetic guards to integer widening
asinghvi17 Nov 30, 2026
8961210
Merge remote-tracking branch 'upstream/master' into factory/cc4e335e-…
asinghvi17 Nov 30, 2026
70770aa
Avoid repeated widening and retain dimensioned Akima weights
asinghvi17 Nov 30, 2026
05ef013
Keep Hermite array arithmetic simple and cover Float16 knots
asinghvi17 Nov 30, 2026
0f2b47b
Leave flat-stencil AD recovery to a separate change
asinghvi17 Nov 30, 2026
0c0014f
Remove obsolete Akima AD guarantee
asinghvi17 Dec 1, 2026
7c1cad1
Address integer compatibility, Akima precision, and review simplifica…
asinghvi17 Dec 1, 2026
f1f6bff
Allow the reviewed Base fixed-width integer union in QA
asinghvi17 Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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 `CubicHermiteSpline` with modified Akima slopes passed through a Fritsch–Carlson limiter, preserving monotonicity and keeping flat segments flat. Where the limiter leaves the slopes unchanged it matches makima; see [`MonotonicMakimaInterpolation`](@ref) for the 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
3 changes: 2 additions & 1 deletion src/DataInterpolations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,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
168 changes: 146 additions & 22 deletions src/interpolation_caches.jl
Original file line number Diff line number Diff line change
Expand Up @@ -365,19 +365,40 @@ 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},
# Abstractly declared samples may contain wider values than their first entry.
function _akima_slope_type(u, t)
U = isconcretetype(eltype(u)) ? eltype(u) : mapreduce(typeof, promote_type, u)
V = isconcretetype(eltype(t)) ? eltype(t) : mapreduce(typeof, promote_type, t)
return typeof(_wide_diff(oneunit(U), zero(U)) / _wide_diff(oneunit(V), zero(V)))
end

# Concrete noninteger samples retain Akima's original coefficient precision.
function _akima_coefficient_type(u, t)
U = eltype(u)
return isconcretetype(U) && !(U <: Integer) ? U : _akima_slope_type(u, t)
end

# 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] = _wide_diff(u[i + 1], u[i]) / _wide_diff(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]
b[1] = b[2] = m[3]
return nothing
end
m[2] = 2 * m[3] - m[4]
m[1] = 2 * m[2] - m[3]
Expand All @@ -397,7 +418,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 @@ -417,14 +438,32 @@ 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))
if n == 2
fill!(c, zero(T))
fill!(d, zero(T))
return nothing
end
@inbounds begin
for i in 1:(n - 1)
dt = t[i + 1] - t[i]
dt = _wide_diff(t[i + 1], t[i])
dt = dt isa Integer ? float(dt) : dt
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)
end
Expand All @@ -449,7 +488,7 @@ Base.@constprop :aggressive function AkimaInterpolation(
check_min_length(AkimaInterpolation, t)
t_props = something(search_properties, FindFirstFunctions.SearchProperties(t))
n = length(t)
T = eltype(u)
T = _akima_coefficient_type(u, t)
b = Vector{T}(undef, n)
c = Vector{T}(undef, n - 1)
d = Vector{T}(undef, n - 1)
Expand Down Expand Up @@ -488,9 +527,10 @@ Base.@constprop :aggressive function AkimaInterpolation(
t_props = something(search_properties, FindFirstFunctions.SearchProperties(t))
n = length(t)
dims = size(u)[1:(end - 1)]
b = Array{T}(undef, dims..., n)
c = Array{T}(undef, dims..., n - 1)
d = Array{T}(undef, dims..., n - 1)
S = _akima_coefficient_type(u, t)
b = Array{S}(undef, dims..., n)
c = Array{S}(undef, dims..., n - 1)
d = Array{S}(undef, dims..., n - 1)
u_flat = reshape(u, :, n)
b_flat = reshape(b, :, n)
c_flat = reshape(c, :, n - 1)
Expand Down Expand Up @@ -531,14 +571,15 @@ Base.@constprop :aggressive function AkimaInterpolation(
t_props = something(search_properties, FindFirstFunctions.SearchProperties(t))
n = length(t)
dim = length(u[1])
b = [Vector{T}(undef, dim) for _ in 1:n]
c = [Vector{T}(undef, dim) for _ in 1:(n - 1)]
d = [Vector{T}(undef, dim) for _ in 1:(n - 1)]
S = _akima_coefficient_type(Iterators.flatten(u), t)
b = [Vector{S}(undef, dim) for _ in 1:n]
c = [Vector{S}(undef, dim) for _ in 1:(n - 1)]
d = [Vector{S}(undef, dim) for _ in 1:(n - 1)]
for j in 1:dim
u_j = [u_[j] for u_ in u]
b_j = Vector{T}(undef, n)
c_j = Vector{T}(undef, n - 1)
d_j = Vector{T}(undef, n - 1)
b_j = Vector{S}(undef, n)
c_j = Vector{S}(undef, n - 1)
d_j = Vector{S}(undef, n - 1)
_akima_init!(b_j, c_j, d_j, u_j, t, Val(modified))
for i in 1:n
b[i][j] = b_j[i]
Expand Down Expand Up @@ -1841,6 +1882,89 @@ 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.

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`,
overriding the detected properties (e.g. built with `is_uniform = true`).
Defaults to `nothing`.

# 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
70 changes: 59 additions & 11 deletions src/interpolation_utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -563,8 +563,8 @@ function get_parameters(A::QuinticHermiteSpline, idx)
end

function du_PCHIP(u::AbstractVector{<:Number}, t)
h = diff(t)
δ = diff(u) ./ h
h = map(_wide_diff, @view(t[2:end]), @view(t[1:(end - 1)]))
δ = map(_wide_diff, @view(u[2:end]), @view(u[1:(end - 1)])) ./ h
s = sign.(δ)

# Special handling of the slope at the endpoints, see
Expand Down Expand Up @@ -618,34 +618,82 @@ function du_PCHIP(u::AbstractVector{<:Number}, t)
return _du.(eachindex(t))
end

# Builds each dimension's PCHIP derivative independently, by reusing the scalar
# `du_PCHIP` kernel on a length-`n` scalar slice per leading index (row of a Matrix,
# component of a Vector{Vector}, ...), matching the `AkimaInterpolation` pattern.
function du_PCHIP(u::AbstractArray{T, N}, t) where {T, N}
# Knot slopes of `MonotonicMakimaInterpolation`: makima slopes, followed by a sign pass
# and the square Fritsch–Carlson limiter. See the docstring of
# `MonotonicMakimaInterpolation` for the precise algorithm.
function du_monotonic_makima(u::AbstractVector{<:Number}, t)
n = length(t)
T = _akima_slope_type(u, t)
du = Vector{T}(undef, n)
# `m[k + 2]` is the secant of segment `k`, see `_akima_slopes!`.
m = Vector{T}(undef, n + 3)
_akima_slopes!(du, m, u, t, Val(true))
# `ifelse`/`&`, not `if`/`&&`, so `u` may hold symbolic entries.
@inbounds begin
# Sign pass: keep a slope only if it has the same (nonzero) sign as every
# adjacent secant, so local extrema and flat segments get a zero slope.
for i in 1:n
sₗ = m[i + ifelse(i > 1, 1, 2)]
sᵣ = m[i + ifelse(i < n, 2, 1)]
keep = (sign(du[i]) == sign(sₗ)) &
(sign(du[i]) == sign(sᵣ))
du[i] = ifelse(keep, du[i], zero(T))
end
# Square Fritsch–Carlson limiter, segment by segment from left to right: if
# `max(α, β) > 3`, scale both end slopes by `3 / max(α, β)`. A slope shared with
# the previous segment can only shrink here, which keeps that segment's `(α, β)`
# inside the square.
for k in 1:(n - 1)
s = m[k + 2]
nonzero = s != 0
dmax = max(abs(du[k]), abs(du[k + 1]))
limit = nonzero & (dmax > 3 * abs(s))
dmax_safe = ifelse(limit, dmax, oneunit(dmax))
τ = ifelse(limit, 3 * abs(s) / dmax_safe, one(s / dmax_safe))
du[k] *= τ
du[k + 1] *= τ
end
end
return du
end

# Builds each dimension's knot slopes independently, by reusing a scalar slope kernel
# `du_fn(u, t)` (e.g. `du_PCHIP`) on a length-`n` scalar slice per leading index (row of
# a Matrix, component of a Vector{Vector}, ...), matching the `AkimaInterpolation` pattern.
function _du_per_dimension(du_fn, u::AbstractArray{T, N}, t) where {T, N}
n = length(t)
dims = size(u)[1:(end - 1)]
du = Array{T}(undef, dims..., n)
S = _akima_slope_type(u, t)
du = Array{S}(undef, dims..., n)
u_flat = reshape(u, :, n)
du_flat = reshape(du, :, n)
for i in axes(u_flat, 1)
du_flat[i, :] .= du_PCHIP(u_flat[i, :], t)
du_flat[i, :] .= du_fn(u_flat[i, :], t)
end
return du
end

function du_PCHIP(u::AbstractVector{<:AbstractVector{T}}, t) where {T}
function _du_per_dimension(du_fn, u::AbstractVector{<:AbstractVector{T}}, t) where {T}
dim = length(u[1])
du = [Vector{T}(undef, dim) for _ in eachindex(u)]
S = _akima_slope_type(Iterators.flatten(u), t)
du = [Vector{S}(undef, dim) for _ in eachindex(u)]
for j in 1:dim
u_j = [u_[j] for u_ in u]
du_j = du_PCHIP(u_j, t)
du_j = du_fn(u_j, t)
for i in eachindex(t)
du[i][j] = du_j[i]
end
end
return du
end

du_PCHIP(u::AbstractArray, t) = _du_per_dimension(du_PCHIP, u, t)
du_PCHIP(u::AbstractVector{<:AbstractVector}, t) = _du_per_dimension(du_PCHIP, u, t)
du_monotonic_makima(u::AbstractArray, t) = _du_per_dimension(du_monotonic_makima, u, t)
function du_monotonic_makima(u::AbstractVector{<:AbstractVector}, t)
return _du_per_dimension(du_monotonic_makima, u, t)
end

function integrate_cubic_polynomial(t1, t2, offset, a, b, c, d)
t1_rel = t1 - offset
t2_rel = t2 - offset
Expand Down
Loading
Loading