From 33ba421f13fa3775f28265ffa0300ccc68207089 Mon Sep 17 00:00:00 2001 From: Anshul Singhvi Date: Thu, 12 Nov 2026 00:51:59 +0000 Subject: [PATCH 01/10] Add MonotonicMakimaInterpolation (makima slopes + Fritsch-Carlson limiter) Adds `MonotonicMakimaInterpolation(u, t; kwargs...)`, a shape-preserving variant of makima. Like `PCHIPInterpolation`, it computes knot slopes and returns a `CubicHermiteSpline`, so extrapolation, derivatives, integrals and `cache_parameters` work as for any Hermite spline. The slopes are: 1. the makima slopes of `AkimaInterpolation(u, t; modified = true)`, reusing the existing kernel (split out of `_akima_init!` as `_akima_slopes!`); 2. a sign pass that zeroes a slope whose sign differs from an adjacent secant, or whose adjacent secant is zero (flat segments stay flat); 3. a square Fritsch-Carlson limiter: per segment, left to right, if max(alpha, beta) > 3 both end slopes are scaled by 3 / max(alpha, beta). Where steps 2 and 3 do not act, the result is identical to makima. Also fixes `AkimaInterpolation` with two points, which read an uninitialized ghost secant; it now gives the straight line through the two points. The per-dimension wrappers of `du_PCHIP` are generalized into `_du_per_dimension` and shared by both slope kernels. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Anshul Singhvi Harness: claude Model: claude-opus-5-5 Factory-Task: 22fff5cb-ab23-4f6c-a31f-195f557afeb0 Agent-Harness: Claude 2.1.319 Agent-Model: claude-opus-5-5 Agent-Session: factory task 22fff5cb-ab23-4f6c-a31f-195f557afeb0 on m_e7dafdb55d0afc98861a124723a9e3fd (no session URL) --- docs/src/index.md | 1 + docs/src/manual.md | 1 + docs/src/methods.md | 22 +++ src/DataInterpolations.jl | 3 +- src/interpolation_caches.jl | 132 ++++++++++++++++-- src/interpolation_utils.jl | 63 ++++++++- test/Methods/derivative_tests.jl | 19 +++ test/Methods/integral_tests.jl | 9 ++ test/interface.jl | 1 + test/interpolation_tests.jl | 227 +++++++++++++++++++++++++++++++ 10 files changed, 459 insertions(+), 19 deletions(-) diff --git a/docs/src/index.md b/docs/src/index.md index fb2081b5f..4e89da599 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -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 3`, both end slopes of the segment are scaled by the same + factor `τ = 3 / max(α, β)`, i.e. `(α, β)` is projected radially onto the boundary of + the square `[0, 3]²`, keeping the ratio `α : β`. A slope shared with the previous + segment can only shrink, so all segments end up inside the square. + +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) diff --git a/src/interpolation_utils.jl b/src/interpolation_utils.jl index 2153ce538..7527ea1f3 100644 --- a/src/interpolation_utils.jl +++ b/src/interpolation_utils.jl @@ -583,27 +583,69 @@ 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 = typeof(oneunit(eltype(u)) / oneunit(eltype(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 + s_safe = ifelse(nonzero, s, oneunit(s)) + α = du[k] / s_safe + β = du[k + 1] / s_safe + αβ_max = ifelse(α > β, α, β) + limit = nonzero & (αβ_max > 3) + αβ_max_safe = ifelse(limit, αβ_max, one(αβ_max)) + # Written as `3s * (α / max(α, β))` so the larger of the two scaled slopes is + # exactly `3s`. + du[k] = ifelse(limit, 3 * s * (α / αβ_max_safe), du[k]) + du[k + 1] = ifelse(limit, 3 * s * (β / αβ_max_safe), 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) 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)] 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 @@ -611,6 +653,13 @@ function du_PCHIP(u::AbstractVector{<:AbstractVector{T}}, t) where {T} 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 diff --git a/test/Methods/derivative_tests.jl b/test/Methods/derivative_tests.jl index 69fdc7e7f..b35dccabb 100644 --- a/test/Methods/derivative_tests.jl +++ b/test/Methods/derivative_tests.jl @@ -195,6 +195,25 @@ end ) end +@testset "Monotonic Makima Interpolation" begin + # The limiter and the sign pass both act on this data + u = [0.0, 0.05, 1.0, 1.05, 1.1, 1.1, 0.5, 0.0] + t = [0.0, 1.0, 1.1, 2.1, 3.1, 4.0, 5.0, 6.5] + test_derivatives( + MonotonicMakimaInterpolation; args = [u, t], name = "Monotonic Makima Interpolation" + ) + u2 = vcat(u', u') + test_derivatives( + MonotonicMakimaInterpolation; args = [u2, t], + name = "Monotonic Makima Interpolation (Matrix)" + ) + u_vov = [[u_, u_] for u_ in u] + test_derivatives( + MonotonicMakimaInterpolation; args = [u_vov, t], + name = "Monotonic Makima Interpolation (Vector of Vectors)" + ) +end + @testset "Constant Interpolation" begin u = [0.0, 2.0, 1.0, 3.0, 2.0, 6.0, 5.5, 5.5, 2.7, 5.1, 3.0] t = collect(0.0:10.0) diff --git a/test/Methods/integral_tests.jl b/test/Methods/integral_tests.jl index f7cee8af9..65626f432 100644 --- a/test/Methods/integral_tests.jl +++ b/test/Methods/integral_tests.jl @@ -245,6 +245,15 @@ end ) end +@testset "MonotonicMakimaInterpolation" begin + u = [0.0, 0.05, 1.0, 1.05, 1.1, 1.1, 0.5, 0.0] + t = [0.0, 1.0, 1.1, 2.1, 3.1, 4.0, 5.0, 6.5] + test_integral( + MonotonicMakimaInterpolation; args = [u, t], + name = "Monotonic Makima Interpolation (Vector)" + ) +end + @testset "CubicHermiteSpline" begin du = [-0.047, -0.058, 0.054, 0.012, -0.068, 0.0] u = [14.7, 11.51, 10.41, 14.95, 12.24, 11.22] diff --git a/test/interface.jl b/test/interface.jl index 527cb8a1f..8b57fc198 100644 --- a/test/interface.jl +++ b/test/interface.jl @@ -64,6 +64,7 @@ end @testset "Hermite Splines" begin @inferred CubicHermiteSpline(du, u, t) @inferred PCHIPInterpolation(u, t) + @inferred MonotonicMakimaInterpolation(u, t) @inferred QuinticHermiteSpline(ddu, du, u, t) end end diff --git a/test/interpolation_tests.jl b/test/interpolation_tests.jl index b7ac82f6c..d8484af3b 100644 --- a/test/interpolation_tests.jl +++ b/test/interpolation_tests.jl @@ -768,6 +768,13 @@ end @test_throws DataInterpolations.LeftExtrapolationError A(-1.0) @test_throws DataInterpolations.RightExtrapolationError A(11.0) + # Two points: the straight line through them + for modified in (false, true) + A2 = AkimaInterpolation([1.0, 3.0], [0.0, 2.0]; modified) + @test A2.b == [1.0, 1.0] + @test A2.(0.0:0.25:2.0) ≈ 1.0 .+ (0.0:0.25:2.0) + end + # Modified Akima (makima) — same struct, different b computation @testset "Modified Akima (makima)" begin A_makima = @inferred(AkimaInterpolation(u, t; modified = true)) @@ -2145,6 +2152,225 @@ end end end +@testset "MonotonicMakimaInterpolation" begin + # `true` if `v` is non-decreasing up to floating-point rounding of the cubic evaluation + nondecreasing(v) = all(diff(v) .>= -8 * eps(maximum(abs, v))) + # `(α, β)` of every segment with a nonzero secant + function αβ(A) + s = diff(A.u) ./ diff(A.t) + nz = s .!= 0 + return (A.du[1:(end - 1)] ./ s)[nz], (A.du[2:end] ./ s)[nz] + end + + u = [14.7, 11.51, 10.41, 14.95, 12.24, 11.22] + t = [0.0, 62.25, 109.66, 162.66, 205.8, 250.0] + A = @inferred(MonotonicMakimaInterpolation(u, t)) + @test A isa CubicHermiteSpline + for i in eachindex(t) + @test A(t[i]) ≈ u[i] + end + # No overshoot: local extrema are at the data points + us = A(0.0:0.1:250.0) + @test all(minimum(u) .<= us .<= maximum(u)) + @test all(A.du[[3, 4]] .== 0.0) + @test @inferred(output_dim(A)) == 0 + @test @inferred(output_size(A)) == () + + @testset "Monotone data gives a monotone interpolant" begin + rng = StableRNG(13) + for _ in 1:200 + n = rand(rng, 3:12) + t = cumsum(rand(rng, n)) + u = cumsum(rand(rng, n) .^ 3) + A = MonotonicMakimaInterpolation(u, t) + tt = range(t[1], t[end]; length = 2001) + @test nondecreasing(A.(tt)) + # Decreasing data + A = MonotonicMakimaInterpolation(-u, t) + @test nondecreasing(-A.(tt)) + # Every segment ends up in the square [0, 3]² + α, β = αβ(A) + @test all(0 .<= α .<= 3 + 1.0e-12) + @test all(0 .<= β .<= 3 + 1.0e-12) + end + # Plain makima overshoots on this data, the monotone variant does not + u = [0.0, 0.05, 1.0, 1.05, 1.1] + t = [0.0, 1.0, 1.1, 2.1, 3.1] + tt = range(t[1], t[end]; length = 3001) + @test !nondecreasing(AkimaInterpolation(u, t; modified = true).(tt)) + @test nondecreasing(MonotonicMakimaInterpolation(u, t).(tt)) + end + + @testset "Agrees with makima where the limiter does not act" begin + u = [0.0, 1.0, 1.1, 1.2, 1.3] + t = [0.0, 1.0, 2.0, 3.0, 4.0] + A = MonotonicMakimaInterpolation(u, t) + B = AkimaInterpolation(u, t; modified = true) + @test A.du == B.b + tt = range(t[1], t[end]; length = 401) + @test A.(tt) ≈ B.(tt) + + t = collect(0.1:0.1:1.0) + u = exp.(t) + A = MonotonicMakimaInterpolation(u, t) + B = AkimaInterpolation(u, t; modified = true) + @test A.du == B.b + tt = range(t[1], t[end]; length = 401) + @test A.(tt) ≈ B.(tt) + end + + @testset "Sign pass and limiter" begin + # Makima slopes [-3.5, 4.76, ...]: the sign pass zeroes the first one, and the + # limiter scales the second one onto the edge of the square, d₂ = 3 s₁. + u = [0.0, 0.05, 1.0, 1.05, 1.1] + t = [0.0, 1.0, 1.1, 2.1, 3.1] + B = AkimaInterpolation(u, t; modified = true) + A = MonotonicMakimaInterpolation(u, t) + @test B.b[1] < 0 + @test B.b[2] > 3 * 0.05 + @test A.du[1] == 0 + @test A.du[2] ≈ 3 * 0.05 + @test A.du[3:end] == B.b[3:end] + + # A shallow segment between two steep ones: both makima end slopes are > 3s, and + # the radial scaling τ = 3 / max(α, β) keeps their ratio (here 1 : 1). + u = [0.0, 1.0, 2.0, 2.1, 3.1, 4.1] + t = collect(0.0:5.0) + B = AkimaInterpolation(u, t; modified = true) + A = MonotonicMakimaInterpolation(u, t) + s = 0.1 + @test B.b[3] / s > 3 && B.b[4] / s > 3 + @test A.du[3] ≈ 3s + @test A.du[4] ≈ 3s + @test A.du[[1, 2, 5, 6]] == B.b[[1, 2, 5, 6]] + + # Unequal ratio: the larger one goes to exactly 3, the other keeps the ratio + u = [0.0, 1.0, 2.0, 2.1, 2.6, 3.1] + B = AkimaInterpolation(u, t; modified = true) + A = MonotonicMakimaInterpolation(u, t) + α, β = B.b[3] / s, B.b[4] / s + @test max(α, β) > 3 + @test A.du[3] ≈ 3s * α / max(α, β) + @test A.du[4] ≈ 3s * β / max(α, β) + end + + @testset "Flat segments stay flat" begin + u = [0.0, 1.0, 1.0, 1.0, 2.0, 3.0, 3.0] + t = collect(0.0:6.0) + A = MonotonicMakimaInterpolation(u, t) + @test all(A.(range(1.0, 3.0; length = 101)) .== 1.0) + @test all(A.(range(5.0, 6.0; length = 101)) .== 3.0) + @test all(DataInterpolations.derivative.(Ref(A), range(1.0, 3.0; length = 101)) .== 0) + @test nondecreasing(A.(range(0.0, 6.0; length = 601))) + # Constant data + A = MonotonicMakimaInterpolation(fill(2.0, 5), collect(0.0:4.0)) + @test all(A.du .== 0) + @test all(A.(0.0:0.1:4.0) .== 2.0) + end + + @testset "Edge cases" begin + # Two points: the straight line through them + A = MonotonicMakimaInterpolation([1.0, 3.0], [0.0, 2.0]) + @test A.du == [1.0, 1.0] + @test A.(0.0:0.25:2.0) ≈ 1.0 .+ (0.0:0.25:2.0) + A = MonotonicMakimaInterpolation([1.0, 1.0], [0.0, 2.0]) + @test A.du == [0.0, 0.0] + A = MonotonicMakimaInterpolation( + [1.0, 3.0], [0.0, 2.0]; extrapolation = ExtrapolationType.Extension + ) + @test A(-1.0) ≈ 0.0 + @test A(4.0) ≈ 5.0 + + # Three points + A = MonotonicMakimaInterpolation([0.0, 1.0, 4.0], [0.0, 1.0, 2.0]) + @test nondecreasing(A.(range(0.0, 2.0; length = 201))) + A = MonotonicMakimaInterpolation([0.0, 1.0, 0.0], [0.0, 1.0, 2.0]) + @test A.du[2] == 0 + @test all(A.(range(0.0, 2.0; length = 201)) .<= 1.0) + + # Repeated values + u = [1.0, 1.0, 2.0, 2.0, 2.0, 5.0, 5.0] + t = [0.0, 0.5, 1.5, 2.0, 3.5, 4.0, 6.0] + A = MonotonicMakimaInterpolation(u, t) + @test all(A.du .== 0) + @test nondecreasing(A.(range(t[1], t[end]; length = 601))) + + # Steep step: no overshoot or undershoot next to the jump (plain makima + # undershoots below 0 here) + 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] + tt = range(t[1], t[end]; length = 2001) + A = MonotonicMakimaInterpolation(u, t) + us = A.(tt) + @test nondecreasing(us) + @test all(0.0 .<= us .<= 10.0) + @test minimum(AkimaInterpolation(u, t; modified = true).(tt)) < 0 + + # Integer data + A = MonotonicMakimaInterpolation([1, 2, 4, 8], [1, 2, 3, 4]) + @test A.du ≈ MonotonicMakimaInterpolation([1.0, 2.0, 4.0, 8.0], [1.0, 2.0, 3.0, 4.0]).du + + # Duplicate time points and too few points throw an informative error + @test_throws ArgumentError MonotonicMakimaInterpolation( + [1.0, 2.0, 3.0, 4.0, 5.0], [0.0, 1.0, 1.0, 2.0, 3.0] + ) + @test_throws ArgumentError MonotonicMakimaInterpolation([1.0], [1.0]) + @test_throws ArgumentError MonotonicMakimaInterpolation(rand(2, 1), [1.0]) + @test_throws ArgumentError MonotonicMakimaInterpolation([rand(2)], [1.0]) + end + + @testset "Extrapolation and caching" begin + u = [0.0, 0.05, 1.0, 1.05, 1.1] + t = [0.0, 1.0, 1.1, 2.1, 3.1] + A = MonotonicMakimaInterpolation(u, t) + @test_throws DataInterpolations.LeftExtrapolationError A(-1.0) + @test_throws DataInterpolations.RightExtrapolationError A(4.0) + A = MonotonicMakimaInterpolation(u, t; extrapolation = ExtrapolationType.Constant) + @test A(-1.0) == 0.0 + @test A(4.0) == 1.1 + A = MonotonicMakimaInterpolation(u, t; extrapolation = ExtrapolationType.Linear) + @test A(-1.0) ≈ u[1] - A.du[1] + @test A(4.0) ≈ u[end] + 0.9 * A.du[end] + A = MonotonicMakimaInterpolation(u, t; extrapolation = ExtrapolationType.Periodic) + @test A(t[2] + 3.1) ≈ A(t[2]) + A = MonotonicMakimaInterpolation(u, t; extrapolation = ExtrapolationType.Reflective) + @test A(-0.5) ≈ A(0.5) + + A_cached = MonotonicMakimaInterpolation(u, t; cache_parameters = true) + A = MonotonicMakimaInterpolation(u, t) + tt = range(t[1], t[end]; length = 101) + @test A_cached.(tt) ≈ A.(tt) + @test DataInterpolations.integral(A_cached, t[1], t[end]) ≈ + DataInterpolations.integral(A, t[1], t[end]) + end + + @testset "AbstractMatrix" begin + t = 0.1:0.1:1.0 + u2d = [sin.(t) cos.(t)]' |> collect + A = MonotonicMakimaInterpolation(u2d, t) + @test A.du[1, :] == MonotonicMakimaInterpolation(sin.(t), t).du + @test A.du[2, :] == MonotonicMakimaInterpolation(cos.(t), t).du + t_test = 0.1:0.05:1.0 + u_test = reduce(hcat, A.(t_test)) + @test isapprox(u_test[1, :], sin.(t_test), atol = 1.0e-3) + @test isapprox(u_test[2, :], cos.(t_test), atol = 1.0e-3) + @test output_dim(A) == 1 + @test output_size(A) == (2,) + end + @testset "Vector{Vector}" begin + t = 0.1:0.1:1.0 + u_vec = [[sin(t_), cos(t_)] for t_ in t] + A = MonotonicMakimaInterpolation(u_vec, t) + @test getindex.(A.du, 1) == MonotonicMakimaInterpolation(sin.(t), t).du + t_test = 0.1:0.05:1.0 + u_test = reduce(hcat, A.(t_test)) + @test isapprox(u_test[1, :], sin.(t_test), atol = 1.0e-3) + @test isapprox(u_test[2, :], cos.(t_test), atol = 1.0e-3) + @test output_dim(A) == 1 + @test output_size(A) == (2,) + end +end + @testset "Quintic Hermite Spline" begin test_interpolation_type(QuinticHermiteSpline) @@ -2476,6 +2702,7 @@ end @test_nowarn bsa = BSplineApprox(x, t, 3, 20, :Average) @test_nowarn ai = AkimaInterpolation(x, t) @test_nowarn pc = PCHIPInterpolation(x, t) + @test_nowarn mmi = MonotonicMakimaInterpolation(x, t) @test_nowarn bsi = BSplineInterpolation(x, t, 3, :Average) @test_nowarn qs = QuadraticSpline(x, t) # `SmoothArcLengthInterpolation` fits circle/line segments, which requires branching on From 182f2b295385013075cfa416876ff7cdd05bee90 Mon Sep 17 00:00:00 2001 From: Anshul Singhvi Date: Thu, 12 Nov 2026 01:36:58 +0000 Subject: [PATCH 02/10] =?UTF-8?q?MonotonicMakima:=20square=20limiter=20mul?= =?UTF-8?q?tiplies=20both=20slopes=20by=20r=20=3D=203/max(=CE=B1,=20=CE=B2?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When max(α, β) > 3 on a segment, compute r = 3 / max(α, β) once and multiply both end slopes by it. This is the conventional form of the square rule. Previously the slopes were set to 3s * (α / max(α, β)) and 3s * (β / max(α, β)), which made the larger one exactly 3s; now it is 3s up to rounding (a few ulps). Since r <= 1, a limited slope still never grows. The docstring describes the rounding. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Anshul Singhvi Harness: claude Model: claude-opus-5-5 Factory-Task: 8d831c30-b5f6-4950-9cba-449eed9c4c5f Agent-Harness: Claude 2.1.319 Agent-Model: claude-opus-5-5 Agent-Session: factory task 8d831c30-b5f6-4950-9cba-449eed9c4c5f on m_e7dafdb55d0afc98861a124723a9e3fd (no session URL) --- src/interpolation_caches.jl | 10 ++++++---- src/interpolation_utils.jl | 11 ++++++----- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/interpolation_caches.jl b/src/interpolation_caches.jl index 785ba8a8e..e4a60fbcd 100644 --- a/src/interpolation_caches.jl +++ b/src/interpolation_caches.jl @@ -1882,10 +1882,12 @@ computed in three steps: 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 scaled by the same - factor `τ = 3 / max(α, β)`, i.e. `(α, β)` is projected radially onto the boundary of - the square `[0, 3]²`, keeping the ratio `α : β`. A slope shared with the previous - segment can only shrink, so all segments end up inside the square. + 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]²`. diff --git a/src/interpolation_utils.jl b/src/interpolation_utils.jl index 7527ea1f3..9739345d4 100644 --- a/src/interpolation_utils.jl +++ b/src/interpolation_utils.jl @@ -615,11 +615,12 @@ function du_monotonic_makima(u::AbstractVector{<:Number}, t) β = du[k + 1] / s_safe αβ_max = ifelse(α > β, α, β) limit = nonzero & (αβ_max > 3) - αβ_max_safe = ifelse(limit, αβ_max, one(αβ_max)) - # Written as `3s * (α / max(α, β))` so the larger of the two scaled slopes is - # exactly `3s`. - du[k] = ifelse(limit, 3 * s * (α / αβ_max_safe), du[k]) - du[k + 1] = ifelse(limit, 3 * s * (β / αβ_max_safe), du[k + 1]) + # One factor `r = 3 / max(α, β)` for both end slopes; the larger scaled slope + # is then `3s` up to rounding (a few ulps), not exactly `3s`. Since `r ≤ 1`, a + # scaled slope never grows. + r = 3 / ifelse(limit, αβ_max, one(αβ_max)) + du[k] = ifelse(limit, r * du[k], du[k]) + du[k + 1] = ifelse(limit, r * du[k + 1], du[k + 1]) end end return du From 6649f8be68ca9e47226b24293417d45888965d2b Mon Sep 17 00:00:00 2001 From: Anshul Singhvi Date: Thu, 12 Nov 2026 01:36:59 +0000 Subject: [PATCH 03/10] MonotonicMakima: trim tests and docs example Reduce the MonotonicMakimaInterpolation tests to a compact set: monotone output on a few random tables, equality with makima where the limiter is inactive, flat segments, limiter scaling (checks du == r * makima slope), 2-point tables, and an extrapolation/caching smoke test, plus derivative checks against finite differences for Vector and Matrix data. Drop the 200-case sweep, the redundant edge cases, the integral testset and the second docs example. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Anshul Singhvi Harness: claude Model: claude-opus-5-5 Factory-Task: 8d831c30-b5f6-4950-9cba-449eed9c4c5f Agent-Harness: Claude 2.1.319 Agent-Model: claude-opus-5-5 Agent-Session: factory task 8d831c30-b5f6-4950-9cba-449eed9c4c5f on m_e7dafdb55d0afc98861a124723a9e3fd (no session URL) --- docs/src/methods.md | 13 -- test/Methods/derivative_tests.jl | 5 - test/Methods/integral_tests.jl | 9 -- test/interpolation_tests.jl | 200 +++++-------------------------- 4 files changed, 33 insertions(+), 194 deletions(-) diff --git a/docs/src/methods.md b/docs/src/methods.md index 7a0aad91b..62f812e17 100644 --- a/docs/src/methods.md +++ b/docs/src/methods.md @@ -174,19 +174,6 @@ A = MonotonicMakimaInterpolation(u, t) plot(A) ``` -On data with a steep step, makima can undershoot on the flat segment before the step, while the monotone variant keeps it flat: - -```@example tutorial -u_step = [0.0, 0.0, 0.01, 10.0, 10.0, 10.0] -t_step = [0.0, 1.0, 2.0, 2.05, 3.0, 4.0] -A_makima = AkimaInterpolation(u_step, t_step; modified = true) -A_monotonic = MonotonicMakimaInterpolation(u_step, t_step) -tt = range(0.0, 2.2; length = 500) -plot(tt, A_makima.(tt); label = "makima") -plot!(tt, A_monotonic.(tt); label = "monotonic makima") -scatter!(t_step[1:4], u_step[1:4]; label = "data", ylims = (-0.002, 0.03)) -``` - ## 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. diff --git a/test/Methods/derivative_tests.jl b/test/Methods/derivative_tests.jl index b35dccabb..a1ab210ea 100644 --- a/test/Methods/derivative_tests.jl +++ b/test/Methods/derivative_tests.jl @@ -207,11 +207,6 @@ end MonotonicMakimaInterpolation; args = [u2, t], name = "Monotonic Makima Interpolation (Matrix)" ) - u_vov = [[u_, u_] for u_ in u] - test_derivatives( - MonotonicMakimaInterpolation; args = [u_vov, t], - name = "Monotonic Makima Interpolation (Vector of Vectors)" - ) end @testset "Constant Interpolation" begin diff --git a/test/Methods/integral_tests.jl b/test/Methods/integral_tests.jl index 65626f432..f7cee8af9 100644 --- a/test/Methods/integral_tests.jl +++ b/test/Methods/integral_tests.jl @@ -245,15 +245,6 @@ end ) end -@testset "MonotonicMakimaInterpolation" begin - u = [0.0, 0.05, 1.0, 1.05, 1.1, 1.1, 0.5, 0.0] - t = [0.0, 1.0, 1.1, 2.1, 3.1, 4.0, 5.0, 6.5] - test_integral( - MonotonicMakimaInterpolation; args = [u, t], - name = "Monotonic Makima Interpolation (Vector)" - ) -end - @testset "CubicHermiteSpline" begin du = [-0.047, -0.058, 0.054, 0.012, -0.068, 0.0] u = [14.7, 11.51, 10.41, 14.95, 12.24, 11.22] diff --git a/test/interpolation_tests.jl b/test/interpolation_tests.jl index d8484af3b..3c042cafb 100644 --- a/test/interpolation_tests.jl +++ b/test/interpolation_tests.jl @@ -2155,43 +2155,16 @@ end @testset "MonotonicMakimaInterpolation" begin # `true` if `v` is non-decreasing up to floating-point rounding of the cubic evaluation nondecreasing(v) = all(diff(v) .>= -8 * eps(maximum(abs, v))) - # `(α, β)` of every segment with a nonzero secant - function αβ(A) - s = diff(A.u) ./ diff(A.t) - nz = s .!= 0 - return (A.du[1:(end - 1)] ./ s)[nz], (A.du[2:end] ./ s)[nz] - end - - u = [14.7, 11.51, 10.41, 14.95, 12.24, 11.22] - t = [0.0, 62.25, 109.66, 162.66, 205.8, 250.0] - A = @inferred(MonotonicMakimaInterpolation(u, t)) - @test A isa CubicHermiteSpline - for i in eachindex(t) - @test A(t[i]) ≈ u[i] - end - # No overshoot: local extrema are at the data points - us = A(0.0:0.1:250.0) - @test all(minimum(u) .<= us .<= maximum(u)) - @test all(A.du[[3, 4]] .== 0.0) - @test @inferred(output_dim(A)) == 0 - @test @inferred(output_size(A)) == () @testset "Monotone data gives a monotone interpolant" begin rng = StableRNG(13) - for _ in 1:200 - n = rand(rng, 3:12) + for _ in 1:5 + n = rand(rng, 4:12) t = cumsum(rand(rng, n)) u = cumsum(rand(rng, n) .^ 3) - A = MonotonicMakimaInterpolation(u, t) - tt = range(t[1], t[end]; length = 2001) - @test nondecreasing(A.(tt)) - # Decreasing data - A = MonotonicMakimaInterpolation(-u, t) - @test nondecreasing(-A.(tt)) - # Every segment ends up in the square [0, 3]² - α, β = αβ(A) - @test all(0 .<= α .<= 3 + 1.0e-12) - @test all(0 .<= β .<= 3 + 1.0e-12) + tt = range(t[1], t[end]; length = 1001) + @test nondecreasing(MonotonicMakimaInterpolation(u, t).(tt)) + @test nondecreasing(-MonotonicMakimaInterpolation(-u, t).(tt)) end # Plain makima overshoots on this data, the monotone variant does not u = [0.0, 0.05, 1.0, 1.05, 1.1] @@ -2201,122 +2174,54 @@ end @test nondecreasing(MonotonicMakimaInterpolation(u, t).(tt)) end - @testset "Agrees with makima where the limiter does not act" begin - u = [0.0, 1.0, 1.1, 1.2, 1.3] - t = [0.0, 1.0, 2.0, 3.0, 4.0] - A = MonotonicMakimaInterpolation(u, t) - B = AkimaInterpolation(u, t; modified = true) - @test A.du == B.b - tt = range(t[1], t[end]; length = 401) - @test A.(tt) ≈ B.(tt) - + @testset "Equal to makima where the limiter is inactive" begin t = collect(0.1:0.1:1.0) u = exp.(t) + A = @inferred(MonotonicMakimaInterpolation(u, t)) + @test A isa CubicHermiteSpline + @test A.du == AkimaInterpolation(u, t; modified = true).b + end + + @testset "Flat segments stay flat" begin + u = [0.0, 1.0, 1.0, 1.0, 2.0, 3.0, 3.0] + t = collect(0.0:6.0) A = MonotonicMakimaInterpolation(u, t) - B = AkimaInterpolation(u, t; modified = true) - @test A.du == B.b - tt = range(t[1], t[end]; length = 401) - @test A.(tt) ≈ B.(tt) + @test all(A.(range(1.0, 3.0; length = 101)) .== 1.0) + @test all(A.(range(5.0, 6.0; length = 101)) .== 3.0) + @test nondecreasing(A.(range(0.0, 6.0; length = 601))) end - @testset "Sign pass and limiter" begin - # Makima slopes [-3.5, 4.76, ...]: the sign pass zeroes the first one, and the - # limiter scales the second one onto the edge of the square, d₂ = 3 s₁. + @testset "Limiter scaling" begin + # Makima slopes [-3.5, 4.76, ...]: the sign pass zeroes the first one (opposite + # sign to the secant), the limiter scales the second one to 3 s₁. u = [0.0, 0.05, 1.0, 1.05, 1.1] t = [0.0, 1.0, 1.1, 2.1, 3.1] B = AkimaInterpolation(u, t; modified = true) A = MonotonicMakimaInterpolation(u, t) - @test B.b[1] < 0 - @test B.b[2] > 3 * 0.05 @test A.du[1] == 0 @test A.du[2] ≈ 3 * 0.05 @test A.du[3:end] == B.b[3:end] - # A shallow segment between two steep ones: both makima end slopes are > 3s, and - # the radial scaling τ = 3 / max(α, β) keeps their ratio (here 1 : 1). - u = [0.0, 1.0, 2.0, 2.1, 3.1, 4.1] + # A shallow segment between two steep ones: both end slopes are multiplied by + # r = 3 / max(α, β), so the larger goes to 3s (up to rounding) and the ratio is kept + u = [0.0, 1.0, 2.0, 2.1, 2.6, 3.1] t = collect(0.0:5.0) B = AkimaInterpolation(u, t; modified = true) A = MonotonicMakimaInterpolation(u, t) - s = 0.1 - @test B.b[3] / s > 3 && B.b[4] / s > 3 - @test A.du[3] ≈ 3s - @test A.du[4] ≈ 3s + s = (u[4] - u[3]) / (t[4] - t[3]) + r = 3 / (max(B.b[3], B.b[4]) / s) + @test r < 1 + @test A.du[3] == r * B.b[3] + @test A.du[4] == r * B.b[4] + @test max(A.du[3], A.du[4]) ≈ 3s @test A.du[[1, 2, 5, 6]] == B.b[[1, 2, 5, 6]] - - # Unequal ratio: the larger one goes to exactly 3, the other keeps the ratio - u = [0.0, 1.0, 2.0, 2.1, 2.6, 3.1] - B = AkimaInterpolation(u, t; modified = true) - A = MonotonicMakimaInterpolation(u, t) - α, β = B.b[3] / s, B.b[4] / s - @test max(α, β) > 3 - @test A.du[3] ≈ 3s * α / max(α, β) - @test A.du[4] ≈ 3s * β / max(α, β) end - @testset "Flat segments stay flat" begin - u = [0.0, 1.0, 1.0, 1.0, 2.0, 3.0, 3.0] - t = collect(0.0:6.0) - A = MonotonicMakimaInterpolation(u, t) - @test all(A.(range(1.0, 3.0; length = 101)) .== 1.0) - @test all(A.(range(5.0, 6.0; length = 101)) .== 3.0) - @test all(DataInterpolations.derivative.(Ref(A), range(1.0, 3.0; length = 101)) .== 0) - @test nondecreasing(A.(range(0.0, 6.0; length = 601))) - # Constant data - A = MonotonicMakimaInterpolation(fill(2.0, 5), collect(0.0:4.0)) - @test all(A.du .== 0) - @test all(A.(0.0:0.1:4.0) .== 2.0) - end - - @testset "Edge cases" begin - # Two points: the straight line through them + @testset "2-point tables" begin A = MonotonicMakimaInterpolation([1.0, 3.0], [0.0, 2.0]) @test A.du == [1.0, 1.0] @test A.(0.0:0.25:2.0) ≈ 1.0 .+ (0.0:0.25:2.0) - A = MonotonicMakimaInterpolation([1.0, 1.0], [0.0, 2.0]) - @test A.du == [0.0, 0.0] - A = MonotonicMakimaInterpolation( - [1.0, 3.0], [0.0, 2.0]; extrapolation = ExtrapolationType.Extension - ) - @test A(-1.0) ≈ 0.0 - @test A(4.0) ≈ 5.0 - - # Three points - A = MonotonicMakimaInterpolation([0.0, 1.0, 4.0], [0.0, 1.0, 2.0]) - @test nondecreasing(A.(range(0.0, 2.0; length = 201))) - A = MonotonicMakimaInterpolation([0.0, 1.0, 0.0], [0.0, 1.0, 2.0]) - @test A.du[2] == 0 - @test all(A.(range(0.0, 2.0; length = 201)) .<= 1.0) - - # Repeated values - u = [1.0, 1.0, 2.0, 2.0, 2.0, 5.0, 5.0] - t = [0.0, 0.5, 1.5, 2.0, 3.5, 4.0, 6.0] - A = MonotonicMakimaInterpolation(u, t) - @test all(A.du .== 0) - @test nondecreasing(A.(range(t[1], t[end]; length = 601))) - - # Steep step: no overshoot or undershoot next to the jump (plain makima - # undershoots below 0 here) - 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] - tt = range(t[1], t[end]; length = 2001) - A = MonotonicMakimaInterpolation(u, t) - us = A.(tt) - @test nondecreasing(us) - @test all(0.0 .<= us .<= 10.0) - @test minimum(AkimaInterpolation(u, t; modified = true).(tt)) < 0 - - # Integer data - A = MonotonicMakimaInterpolation([1, 2, 4, 8], [1, 2, 3, 4]) - @test A.du ≈ MonotonicMakimaInterpolation([1.0, 2.0, 4.0, 8.0], [1.0, 2.0, 3.0, 4.0]).du - - # Duplicate time points and too few points throw an informative error - @test_throws ArgumentError MonotonicMakimaInterpolation( - [1.0, 2.0, 3.0, 4.0, 5.0], [0.0, 1.0, 1.0, 2.0, 3.0] - ) - @test_throws ArgumentError MonotonicMakimaInterpolation([1.0], [1.0]) - @test_throws ArgumentError MonotonicMakimaInterpolation(rand(2, 1), [1.0]) - @test_throws ArgumentError MonotonicMakimaInterpolation([rand(2)], [1.0]) + @test MonotonicMakimaInterpolation([1.0, 1.0], [0.0, 2.0]).du == [0.0, 0.0] end @testset "Extrapolation and caching" begin @@ -2324,50 +2229,11 @@ end t = [0.0, 1.0, 1.1, 2.1, 3.1] A = MonotonicMakimaInterpolation(u, t) @test_throws DataInterpolations.LeftExtrapolationError A(-1.0) - @test_throws DataInterpolations.RightExtrapolationError A(4.0) - A = MonotonicMakimaInterpolation(u, t; extrapolation = ExtrapolationType.Constant) - @test A(-1.0) == 0.0 - @test A(4.0) == 1.1 - A = MonotonicMakimaInterpolation(u, t; extrapolation = ExtrapolationType.Linear) - @test A(-1.0) ≈ u[1] - A.du[1] - @test A(4.0) ≈ u[end] + 0.9 * A.du[end] - A = MonotonicMakimaInterpolation(u, t; extrapolation = ExtrapolationType.Periodic) - @test A(t[2] + 3.1) ≈ A(t[2]) - A = MonotonicMakimaInterpolation(u, t; extrapolation = ExtrapolationType.Reflective) - @test A(-0.5) ≈ A(0.5) - + A_lin = MonotonicMakimaInterpolation(u, t; extrapolation = ExtrapolationType.Linear) + @test A_lin(4.0) ≈ u[end] + 0.9 * A.du[end] A_cached = MonotonicMakimaInterpolation(u, t; cache_parameters = true) - A = MonotonicMakimaInterpolation(u, t) tt = range(t[1], t[end]; length = 101) @test A_cached.(tt) ≈ A.(tt) - @test DataInterpolations.integral(A_cached, t[1], t[end]) ≈ - DataInterpolations.integral(A, t[1], t[end]) - end - - @testset "AbstractMatrix" begin - t = 0.1:0.1:1.0 - u2d = [sin.(t) cos.(t)]' |> collect - A = MonotonicMakimaInterpolation(u2d, t) - @test A.du[1, :] == MonotonicMakimaInterpolation(sin.(t), t).du - @test A.du[2, :] == MonotonicMakimaInterpolation(cos.(t), t).du - t_test = 0.1:0.05:1.0 - u_test = reduce(hcat, A.(t_test)) - @test isapprox(u_test[1, :], sin.(t_test), atol = 1.0e-3) - @test isapprox(u_test[2, :], cos.(t_test), atol = 1.0e-3) - @test output_dim(A) == 1 - @test output_size(A) == (2,) - end - @testset "Vector{Vector}" begin - t = 0.1:0.1:1.0 - u_vec = [[sin(t_), cos(t_)] for t_ in t] - A = MonotonicMakimaInterpolation(u_vec, t) - @test getindex.(A.du, 1) == MonotonicMakimaInterpolation(sin.(t), t).du - t_test = 0.1:0.05:1.0 - u_test = reduce(hcat, A.(t_test)) - @test isapprox(u_test[1, :], sin.(t_test), atol = 1.0e-3) - @test isapprox(u_test[2, :], cos.(t_test), atol = 1.0e-3) - @test output_dim(A) == 1 - @test output_size(A) == (2,) end end From 93560874b5e5ef3b6fa8ac490f3b499223607c67 Mon Sep 17 00:00:00 2001 From: Anshul Singhvi Date: Thu, 12 Nov 2026 01:36:59 +0000 Subject: [PATCH 04/10] typos: allow the journal abbreviation "Numer" Used in the citation "SIAM J. Numer. Anal." in the MonotonicMakimaInterpolation docstring. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Anshul Singhvi Harness: claude Model: claude-opus-5-5 Factory-Task: 8d831c30-b5f6-4950-9cba-449eed9c4c5f Agent-Harness: Claude 2.1.319 Agent-Model: claude-opus-5-5 Agent-Session: factory task 8d831c30-b5f6-4950-9cba-449eed9c4c5f on m_e7dafdb55d0afc98861a124723a9e3fd (no session URL) --- .typos.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/.typos.toml b/.typos.toml index f314e0a66..a248e1201 100644 --- a/.typos.toml +++ b/.typos.toml @@ -1,6 +1,7 @@ [default.extend-words] Commun = "Commun" Comput = "Comput" +Numer = "Numer" # Additional SciML terms setp = "setp" From e1fefbb3137f52f0cf83e4812e45da9375b19175 Mon Sep 17 00:00:00 2001 From: Anshul Singhvi Date: Tue, 17 Nov 2026 13:35:48 +0000 Subject: [PATCH 05/10] Fix monotonic makima slope overflow and promoted buffers Co-Authored-By: Anshul Singhvi Co-Authored-By: Codex Harness: codex Model: gpt-6.1-sol Factory-Task: 031f1039-f80a-483c-925b-8c42fd463210 Agent-Harness: Codex 0.164.0 Agent-Model: gpt-6.1-sol Agent-Session: factory task 031f1039-f80a-483c-925b-8c42fd463210 on m_e7dafdb55d0afc98861a124723a9e3fd (no session URL) --- src/interpolation_caches.jl | 6 +++--- src/interpolation_utils.jl | 18 ++++++++++++++---- test/interpolation_tests.jl | 28 ++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/src/interpolation_caches.jl b/src/interpolation_caches.jl index e4a60fbcd..ed2da4d89 100644 --- a/src/interpolation_caches.jl +++ b/src/interpolation_caches.jl @@ -400,7 +400,7 @@ function _akima_slopes!( 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 @@ -420,9 +420,9 @@ function _akima_slopes!( # `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 diff --git a/src/interpolation_utils.jl b/src/interpolation_utils.jl index 9739345d4..f9eadce1d 100644 --- a/src/interpolation_utils.jl +++ b/src/interpolation_utils.jl @@ -619,8 +619,15 @@ function du_monotonic_makima(u::AbstractVector{<:Number}, t) # is then `3s` up to rounding (a few ulps), not exactly `3s`. Since `r ≤ 1`, a # scaled slope never grows. r = 3 / ifelse(limit, αβ_max, one(αβ_max)) - du[k] = ifelse(limit, r * du[k], du[k]) - du[k + 1] = ifelse(limit, r * du[k + 1], du[k + 1]) + # If a slope/secant ratio overflowed, normalize by the dominant slope + # first; the common multiplier `r` would otherwise underflow to zero. + dmax = max(abs(du[k]), abs(du[k + 1])) + dmax_safe = ifelse(limit, dmax, oneunit(dmax)) + overflow = !isfinite(αβ_max) + dₗ = ifelse(overflow, (du[k] / dmax_safe) * (3 * abs(s)), r * du[k]) + dᵣ = ifelse(overflow, (du[k + 1] / dmax_safe) * (3 * abs(s)), r * du[k + 1]) + du[k] = ifelse(limit, dₗ, du[k]) + du[k + 1] = ifelse(limit, dᵣ, du[k + 1]) end end return du @@ -632,7 +639,9 @@ end 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) + # Match the scalar kernel: division and the time type can promote the slopes. + S = typeof(oneunit(T) / oneunit(eltype(t))) + du = Array{S}(undef, dims..., n) u_flat = reshape(u, :, n) du_flat = reshape(du, :, n) for i in axes(u_flat, 1) @@ -643,7 +652,8 @@ end 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 = typeof(oneunit(T) / oneunit(eltype(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_fn(u_j, t) diff --git a/test/interpolation_tests.jl b/test/interpolation_tests.jl index 3c042cafb..0ddfeae39 100644 --- a/test/interpolation_tests.jl +++ b/test/interpolation_tests.jl @@ -2217,6 +2217,34 @@ end @test A.du[[1, 2, 5, 6]] == B.b[[1, 2, 5, 6]] end + @testset "Limiter ratio overflow" begin + for (T, small, large) in ((Float64, 1.0e-200, 1.0e200), (Float32, 1.0f-20, 1.0f20)), + sign in (-1, 1) + A = MonotonicMakimaInterpolation(sign .* T[0, small, large, 2large], T[0, 1, 2, 3]) + @test A.du[2] ≈ sign * 3small + @test A(T(0.5)) ≈ sign * small / 8 + end + end + + @testset "Promoted array slopes" begin + u, t = [0, 1, 4, 9], [0.0, 1.0, 2.0, 3.0] + g = ForwardDiff.gradient(tt -> MonotonicMakimaInterpolation(float.(u), tt)(0.5), t) + for shape in (x -> reshape(x, 1, :), x -> [[v] for v in x]) + @test only(MonotonicMakimaInterpolation(shape(u), Int.(t))(0.5)) ≈ 0.3125 + @test ForwardDiff.gradient( + tt -> only(MonotonicMakimaInterpolation(shape(float.(u)), tt)(0.5)), t + ) ≈ g + end + end + + @testset "Unitful slopes" begin + for u in ([0.0, 1.0, 4.0, 9.0], zeros(4)) + A = MonotonicMakimaInterpolation(u * u"m", [0.0, 1.0, 2.0, 3.0]u"s") + reference = MonotonicMakimaInterpolation(u, [0.0, 1.0, 2.0, 3.0])(0.5) + @test A(0.5u"s") ≈ reference * u"m" + end + end + @testset "2-point tables" begin A = MonotonicMakimaInterpolation([1.0, 3.0], [0.0, 2.0]) @test A.du == [1.0, 1.0] From b4d3f1b19e7c7e047499fbdf6892ce7e365efbd2 Mon Sep 17 00:00:00 2001 From: Anshul Singhvi Date: Tue, 17 Nov 2026 09:39:42 -0500 Subject: [PATCH 06/10] Fix limiter comment wording Co-Authored-By: Anshul Singhvi Co-Authored-By: Codex Harness: codex Model: gpt-6.1-sol Factory-Task: 2ac96216-b848-4d94-88f8-f574017c8dbc Agent-Harness: Codex 0.164.0 Agent-Model: gpt-6.1-sol Agent-Session: factory task 2ac96216-b848-4d94-88f8-f574017c8dbc on m_3e9b2709b53bf4c4dade6cc909217625 (no session URL) --- src/interpolation_utils.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/interpolation_utils.jl b/src/interpolation_utils.jl index f9eadce1d..cec00cdad 100644 --- a/src/interpolation_utils.jl +++ b/src/interpolation_utils.jl @@ -620,7 +620,7 @@ function du_monotonic_makima(u::AbstractVector{<:Number}, t) # scaled slope never grows. r = 3 / ifelse(limit, αβ_max, one(αβ_max)) # If a slope/secant ratio overflowed, normalize by the dominant slope - # first; the common multiplier `r` would otherwise underflow to zero. + # first; the common multiplier `r` would otherwise be exactly zero. dmax = max(abs(du[k]), abs(du[k + 1])) dmax_safe = ifelse(limit, dmax, oneunit(dmax)) overflow = !isfinite(αβ_max) From 7bf8775a43e69ca394b3833958321619abe22dc7 Mon Sep 17 00:00:00 2001 From: pankgeorg <8681967+pankgeorg@users.noreply.github.com> Date: Sun, 29 Nov 2026 07:49:35 +0000 Subject: [PATCH 07/10] Fix integer arithmetic in monotonic makima Widen fixed-width secant and Hermite differences before subtracting. Divide by integer knot spacing twice to avoid overflow in the square. Co-authored-by: Codex gpt-6.2-sol (codex-cli 0.172.0, session 01a22642-ff44-7e32-84de-f1cca932f790) --- src/interpolation_caches.jl | 2 +- src/interpolation_utils.jl | 15 +++++++++++++++ src/parameter_caches.jl | 9 ++++++--- test/interpolation_tests.jl | 17 +++++++++++++++++ 4 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/interpolation_caches.jl b/src/interpolation_caches.jl index ed2da4d89..80e138752 100644 --- a/src/interpolation_caches.jl +++ b/src/interpolation_caches.jl @@ -374,7 +374,7 @@ function _akima_slopes!( n = length(u) @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 diff --git a/src/interpolation_utils.jl b/src/interpolation_utils.jl index cec00cdad..3a94256a6 100644 --- a/src/interpolation_utils.jl +++ b/src/interpolation_utils.jl @@ -782,6 +782,21 @@ get_transition_ts(A::AbstractInterpolation) = A.t _u_view(u::AbstractVector, idx) = u[idx] _u_view(u::AbstractArray, idx) = selectdim(u, ndims(u), idx) +_widened_difference(x, y) = x - y + +function _widened_difference(x::T, y::T) where { + T <: Union{ + Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128, + }, + } + # Widen first so both the operands and their signed difference are representable. + return signed(widen(x)) - signed(widen(y)) +end + +function _widened_difference(x::AbstractArray{<:Integer}, y::AbstractArray{<:Integer}) + return _widened_difference.(x, y) +end + _u_point(u::AbstractVector, idx) = u[idx] _u_point(u::AbstractArray, idx) = copy(_u_view(u, idx)) diff --git a/src/parameter_caches.jl b/src/parameter_caches.jl index ce5e63a17..32d4261d1 100644 --- a/src/parameter_caches.jl +++ b/src/parameter_caches.jl @@ -237,14 +237,17 @@ function CubicHermiteParameterCache(du, u, t, cache_parameters) end end +_divide_by_square(x, h) = x / h^2 +_divide_by_square(x, h::Integer) = x / h / h + function cubic_hermite_spline_parameters(du, u, t, idx) - Δt = t[idx + 1] - t[idx] + Δt = _widened_difference(t[idx + 1], t[idx]) u₀ = _u_view(u, idx) u₁ = _u_view(u, idx + 1) du₀ = _u_view(du, idx) du₁ = _u_view(du, idx + 1) - c₁ = (u₁ - u₀ - du₀ * Δt) / Δt^2 - c₂ = (du₁ - du₀ - 2c₁ * Δt) / Δt^2 + c₁ = _divide_by_square(_widened_difference(u₁, u₀) - du₀ * Δt, Δt) + c₂ = _divide_by_square(du₁ - du₀ - 2c₁ * Δt, Δt) return c₁, c₂ end diff --git a/test/interpolation_tests.jl b/test/interpolation_tests.jl index 0ddfeae39..9a26dfa57 100644 --- a/test/interpolation_tests.jl +++ b/test/interpolation_tests.jl @@ -2252,6 +2252,23 @@ end @test MonotonicMakimaInterpolation([1.0, 1.0], [0.0, 2.0]).du == [0.0, 0.0] end + @testset "Integer differences" begin + for cache_parameters in (false, true) + A = MonotonicMakimaInterpolation(UInt8[3, 2], [0, 1]; cache_parameters) + @test A(0) == 3.0 + @test A(0.5) == 2.5 + @test A(1) == 2.0 + + B = MonotonicMakimaInterpolation(Int8[-100, 100], [0, 1]; cache_parameters) + @test B(0) == -100.0 + @test B(0.5) == 0.0 + @test B(1) == 100.0 + + C = MonotonicMakimaInterpolation([0.0, 1.0], Int64[0, 4294967296]; cache_parameters) + @test C(2147483648.0) == 0.5 + end + end + @testset "Extrapolation and caching" begin u = [0.0, 0.05, 1.0, 1.05, 1.1] t = [0.0, 1.0, 1.1, 2.1, 3.1] From 480e42b19caf6da11ead8ee95ba47f6551f3f7c7 Mon Sep 17 00:00:00 2001 From: pankgeorg <8681967+pankgeorg@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:56:38 +0000 Subject: [PATCH 08/10] Keep cubic spline arithmetic safe for integer offsets Widen segment differences and avoid standalone offset squares during evaluation and integration. Use the same width for Akima slopes and coefficients. Keep native Hermite arithmetic when the square fits. Co-authored-by: Codex gpt-6.2-sol (codex-cli 0.172.0, session 01a22642-ff44-7e32-84de-f1cca932f790) --- src/derivatives.jl | 20 ++++++--- src/integrals.jl | 12 +++--- src/interpolation_caches.jl | 4 +- src/interpolation_methods.jl | 36 ++++++++-------- src/interpolation_utils.jl | 56 +++++++++++++++++-------- src/parameter_caches.jl | 32 +++++++++++---- test/interpolation_tests.jl | 80 ++++++++++++++++++++++++++++++++++++ 7 files changed, 182 insertions(+), 58 deletions(-) diff --git a/src/derivatives.jl b/src/derivatives.jl index dcd7def04..2c01f8515 100644 --- a/src/derivatives.jl +++ b/src/derivatives.jl @@ -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) @@ -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 ? _widened_difference(t, 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) @@ -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) @@ -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₂)) @@ -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₂)) diff --git a/src/integrals.jl b/src/integrals.jl index b5bb9720c..cc72f0afe 100644 --- a/src/integrals.jl +++ b/src/integrals.jl @@ -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 @@ -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 @@ -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 @@ -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₂) diff --git a/src/interpolation_caches.jl b/src/interpolation_caches.jl index 80e138752..d7cd20450 100644 --- a/src/interpolation_caches.jl +++ b/src/interpolation_caches.jl @@ -439,9 +439,9 @@ function _akima_init!( _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 diff --git a/src/interpolation_methods.jl b/src/interpolation_methods.jl index 2532ad867..f99df0101 100644 --- a/src/interpolation_methods.jl +++ b/src/interpolation_methods.jl @@ -54,7 +54,7 @@ function _extrapolate_left(A, t) elseif extrapolation_left == ExtrapolationType.Linear slope = _derivative(A, first(A.t), 1) u₁ = _first(A.u) - Δt = t - first(A.t) + Δt = _extrapolation_difference(A, t, first(A.t)) @. u₁ + slope * Δt else _extrapolate_other(A, t, extrapolation_left) @@ -72,7 +72,7 @@ function _extrapolate_right(A, t) elseif extrapolation_right == ExtrapolationType.Linear slope = _derivative(A, last(A.t), length(A.t)) uₙ = _last(A.u) - Δt = t - last(A.t) + Δt = _extrapolation_difference(A, t, last(A.t)) @. uₙ + slope * Δt else _extrapolate_other(A, t, extrapolation_right) @@ -651,13 +651,13 @@ end function _interpolate(A::AkimaInterpolation{<:AbstractVector{<:Number}}, t::Number, iguess) idx = get_idx(A, t, iguess) - wj = t - A.t[idx] + wj = _widened_difference(t, A.t[idx]) return @evalpoly wj A.u[idx] A.b[idx] A.c[idx] A.d[idx] end function _interpolate(A::AkimaInterpolation{<:AbstractArray}, t::Number, iguess) idx = get_idx(A, t, iguess) - wj = t - A.t[idx] + wj = _widened_difference(t, A.t[idx]) uᵢ = _u_view(A.u, idx) bᵢ = _u_view(A.b, idx) cᵢ = _u_view(A.c, idx) @@ -673,7 +673,7 @@ struct _AkimaEvaluator{Tu, Tt, Tb, Tc, Td} t::Tt end @inline function (e::_AkimaEvaluator)(idx::Integer, ttt) - @inbounds wj = ttt - e.t[idx] + @inbounds wj = _widened_difference(ttt, e.t[idx]) return @inbounds @evalpoly wj e.u[idx] e.bv[idx] e.cv[idx] e.dv[idx] end @@ -727,7 +727,7 @@ function _akima_eval_sorted!( u1 = @inbounds u[1] b1 = @inbounds bv[1] @inbounds while i <= m && tt[i] < t1 - out[i] = u1 + b1 * (tt[i] - t1) + out[i] = u1 + b1 * _widened_difference(tt[i], t1) i += 1 end else # Extension @@ -736,7 +736,7 @@ function _akima_eval_sorted!( c1 = @inbounds cv[1] d1 = @inbounds dv[1] @inbounds while i <= m && tt[i] < t1 - wj = tt[i] - t1 + wj = _widened_difference(tt[i], t1) out[i] = @evalpoly wj u1 b1 c1 d1 i += 1 end @@ -766,7 +766,7 @@ function _akima_eval_sorted!( un = @inbounds u[n] bn = @inbounds bv[n] @inbounds while i <= m - out[i] = un + bn * (tt[i] - tn) + out[i] = un + bn * _widened_difference(tt[i], tn) i += 1 end else # Extension @@ -776,7 +776,7 @@ function _akima_eval_sorted!( dn1 = @inbounds dv[n - 1] tn1 = @inbounds t[n - 1] @inbounds while i <= m - wj = tt[i] - tn1 + wj = _widened_difference(tt[i], tn1) out[i] = @evalpoly wj un1 bn1 cn1 dn1 i += 1 end @@ -1361,18 +1361,16 @@ function _interpolate( A::CubicHermiteSpline{<:AbstractArray}, t::Number, iguess ) idx = get_idx(A, t, iguess) - Δt₀ = t - A.t[idx] - Δt₁ = t - A.t[idx + 1] - out = _u_view(A.u, idx) + Δt₀ * _u_view(A.du, idx) c₁, c₂ = get_parameters(A, idx) - out += Δt₀^2 * (c₁ + Δt₁ * c₂) - return out + return _cubic_hermite_segment_eval( + t, A.t[idx], A.t[idx + 1], _u_view(A.u, idx), _u_view(A.du, idx), c₁, c₂ + ) end @inline function _cubic_hermite_segment_eval(ttt, ti, tip1, ui, dui, c1, c2) - dt0 = ttt - ti - dt1 = ttt - tip1 - return ui + dt0 * dui + dt0 * dt0 * (c1 + dt1 * c2) + dt0 = _widened_difference(ttt, ti) + dt1 = _widened_difference(ttt, tip1) + return ui + dt0 * (dui + dt0 * (c1 + dt1 * c2)) end function (A::CubicHermiteSpline{<:AbstractVector{<:Number}})( @@ -1423,7 +1421,7 @@ function _cubic_hermite_eval_sorted!( u1 = @inbounds u[1] du1 = @inbounds du[1] @inbounds while i <= m && tt[i] < t1 - out[i] = u1 + du1 * (tt[i] - t1) + out[i] = u1 + du1 * _widened_difference(tt[i], t1) i += 1 end else # Extension @@ -1495,7 +1493,7 @@ function _cubic_hermite_eval_sorted!( un = @inbounds u[n] dun = @inbounds du[n] @inbounds while i <= m - out[i] = un + dun * (tt[i] - tn) + out[i] = un + dun * _widened_difference(tt[i], tn) i += 1 end else # Extension diff --git a/src/interpolation_utils.jl b/src/interpolation_utils.jl index 3a94256a6..7a7402763 100644 --- a/src/interpolation_utils.jl +++ b/src/interpolation_utils.jl @@ -511,7 +511,7 @@ function get_parameters(A::CubicSpline, idx) end end -function get_parameters(A::CubicHermiteSpline, idx) +@inline function get_parameters(A::CubicHermiteSpline, idx) return if A.cache_parameters A.p.c₁[idx], A.p.c₂[idx] else @@ -672,12 +672,15 @@ function du_monotonic_makima(u::AbstractVector{<:AbstractVector}, t) end function integrate_cubic_polynomial(t1, t2, offset, a, b, c, d) - t1_rel = t1 - offset - t2_rel = t2 - offset - t_sum = t1_rel + t2_rel - t_sq_sum = t1_rel^2 + t2_rel^2 - Δt = t2 - t1 - return Δt * (a + t_sum * (b / 2 + d * t_sq_sum / 4) + c * (t_sq_sum + t1_rel * t2_rel) / 3) + x = _widened_difference(t1, offset) + y = _widened_difference(t2, offset) + Δt = _widened_difference(t2, t1) + # Multiply by a coefficient before multiplying offsets together. + cx = x * c + quadratic = x * cx + y * (cx + y * c) + cubic = x * (x * d) + y * (y * d) + linear_and_cubic = b / 2 + cubic / 4 + return Δt * (a + x * linear_and_cubic + y * linear_and_cubic + quadratic / 3) end function integrate_quintic_polynomial(t1, t2, offset, a, b, c, d, e, f) @@ -704,16 +707,16 @@ function munge_extrapolation(extrapolation, extrapolation_left, extrapolation_ri end function transformation_periodic(A, t) - Δt = last(A.t) - first(A.t) - n, t_ = fldmod(t - first(A.t), Δt) + Δt = _extrapolation_difference(A, last(A.t), first(A.t)) + n, t_ = fldmod(_extrapolation_difference(A, t, first(A.t)), Δt) t_ += first(A.t) (n > 0) && (n -= 1) return t_, n end function transformation_reflective(A, t) - Δt = last(A.t) - first(A.t) - n, t_ = fldmod(t - first(A.t), Δt) + Δt = _extrapolation_difference(A, last(A.t), first(A.t)) + n, t_ = fldmod(_extrapolation_difference(A, t, first(A.t)), Δt) t_ = isodd(n) ? last(A.t) - t_ : first(A.t) + t_ (n > 0) && (n -= 1) return t_, n @@ -784,19 +787,36 @@ _u_view(u::AbstractArray, idx) = selectdim(u, ndims(u), idx) _widened_difference(x, y) = x - y -function _widened_difference(x::T, y::T) where { - T <: Union{ - Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128, - }, - } - # Widen first so both the operands and their signed difference are representable. - return signed(widen(x)) - signed(widen(y)) +const FixedWidthInteger = Union{ + Bool, Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128, +} + +_signed_widen(x) = signed(widen(x)) +_signed_widen(x::Bool) = Int(x) + +function _widened_difference(x::FixedWidthInteger, y::FixedWidthInteger) + return _signed_widen(x) - _signed_widen(y) end function _widened_difference(x::AbstractArray{<:Integer}, y::AbstractArray{<:Integer}) return _widened_difference.(x, y) end +_square_or_nothing(h) = h * h + +@inline function _square_or_nothing(h::FixedWidthInteger) + square, overflow = Base.Checked.mul_with_overflow(h, h) + return overflow ? nothing : square +end + +_divide_by_square(x, h, square) = x / square +_divide_by_square(x, h, ::Nothing) = x / h / h + +_extrapolation_difference(A, x, y) = x - y +function _extrapolation_difference(::Union{AkimaInterpolation, CubicHermiteSpline}, x, y) + return _widened_difference(x, y) +end + _u_point(u::AbstractVector, idx) = u[idx] _u_point(u::AbstractArray, idx) = copy(_u_view(u, idx)) diff --git a/src/parameter_caches.jl b/src/parameter_caches.jl index 32d4261d1..7e9262145 100644 --- a/src/parameter_caches.jl +++ b/src/parameter_caches.jl @@ -237,17 +237,35 @@ function CubicHermiteParameterCache(du, u, t, cache_parameters) end end -_divide_by_square(x, h) = x / h^2 -_divide_by_square(x, h::Integer) = x / h / h - -function cubic_hermite_spline_parameters(du, u, t, idx) - Δt = _widened_difference(t[idx + 1], t[idx]) +@inline function cubic_hermite_spline_parameters(du, u, t, idx) + t₀, t₁ = t[idx], t[idx + 1] u₀ = _u_view(u, idx) u₁ = _u_view(u, idx + 1) du₀ = _u_view(du, idx) du₁ = _u_view(du, idx + 1) - c₁ = _divide_by_square(_widened_difference(u₁, u₀) - du₀ * Δt, Δt) - c₂ = _divide_by_square(du₁ - du₀ - 2c₁ * Δt, Δt) + Δu = _widened_difference(u₁, u₀) + + # Keep the common integer path in the native type through both divisions. + if t₀ isa Int && t₁ isa Int + Δt, difference_overflow = Base.Checked.sub_with_overflow(t₁, t₀) + if !difference_overflow && 0 <= Δt <= isqrt(typemax(Int)) + return _cubic_hermite_coefficients(Δu, du₀, du₁, Δt, Δt * Δt) + end + return _wide_integer_hermite_coefficients(Δu, du₀, du₁, t₀, t₁) + end + + Δt = _widened_difference(t₁, t₀) + return _cubic_hermite_coefficients(Δu, du₀, du₁, Δt, _square_or_nothing(Δt)) +end + +@noinline function _wide_integer_hermite_coefficients(Δu, du₀, du₁, t₀, t₁) + Δt = _widened_difference(t₁, t₀) + return _cubic_hermite_coefficients(Δu, du₀, du₁, Δt, _square_or_nothing(Δt)) +end + +@inline function _cubic_hermite_coefficients(Δu, du₀, du₁, Δt, Δt²) + c₁ = _divide_by_square(Δu - du₀ * Δt, Δt, Δt²) + c₂ = _divide_by_square(du₁ - du₀ - 2c₁ * Δt, Δt, Δt²) return c₁, c₂ end diff --git a/test/interpolation_tests.jl b/test/interpolation_tests.jl index 9a26dfa57..454104d28 100644 --- a/test/interpolation_tests.jl +++ b/test/interpolation_tests.jl @@ -2269,6 +2269,86 @@ end end end + @testset "Cubic integer query offsets" begin + knots = UInt8[0, 10, 40] + values = [0.0, 1.0, 2.0] + for cache_parameters in (false, true) + A = MonotonicMakimaInterpolation(values, knots; cache_parameters) + # The first segment is 11x/90 + x²/1800 - x³/3600. + @test A(UInt8(5)) ≈ 85 // 144 + @test A(Int8(5)) ≈ 85 // 144 + out = zeros(2) + A(out, UInt8[5, 10]) + @test out ≈ [85 / 144, 1.0] + @test DataInterpolations.derivative(A, UInt8(5)) ≈ 77 // 720 + @test DataInterpolations.derivative(A, UInt8(5), 2) ≈ -13 // 1800 + @test DataInterpolations.integral(A, UInt8(40)) ≈ 2935 // 54 + + B = MonotonicMakimaInterpolation(reshape(values, 1, :), knots; cache_parameters) + @test only(B(UInt8(5))) ≈ 85 // 144 + @test only(DataInterpolations.derivative(B, UInt8(5))) ≈ 77 // 720 + @test only(DataInterpolations.integral(B, UInt8(40))) ≈ 2935 // 54 + + # Zero end slopes give 3s² - 2s³ in normalized coordinates. + h = Int64(4294967296) + C = CubicHermiteSpline(zeros(2), [0.0, 1.0], [0, h]; cache_parameters) + q = 3 * (h ÷ 4) + @test C(q) ≈ 27 // 32 + @test only(C(zeros(1), [q])) ≈ 27 // 32 + @test DataInterpolations.derivative(C, q) * h ≈ 9 // 8 + @test DataInterpolations.integral(C, q) / h ≈ 135 // 512 + + # Here even the width's widened integer square is too large. + wide_knots = Int64[-7000000000000000000, 7000000000000000000] + D = CubicHermiteSpline(zeros(2), [0.0, 1.0], wide_knots; cache_parameters) + @test D(0) ≈ 0.5 + @test DataInterpolations.integral(D, 0) / 1.4e19 ≈ 3 // 32 + end + end + + @testset "Cubic large floating-point offsets" begin + for cache_parameters in (false, true) + A = MonotonicMakimaInterpolation(Float32[0, 1], Float32[0, 1.0e20]; cache_parameters) + @test A(5.0f19) ≈ 0.5f0 + @test only(A(zeros(Float32, 1), Float32[5.0e19])) ≈ 0.5f0 + @test DataInterpolations.integral(A, 5.0f19) ≈ 1.25f19 + end + end + + @testset "Cubic integer extrapolation offsets" begin + values = [0.0, 1.0, 2.0] + for constructor in (MonotonicMakimaInterpolation, AkimaInterpolation) + A = constructor(values, Int8[20, 30, 40]; extrapolation = ExtrapolationType.Linear) + @test A(Int8(-120)) ≈ -14.0 + @test only(A(zeros(1), Int8[-120])) ≈ -14.0 + @test DataInterpolations.integral(A, Int8(-120)) ≈ 980.0 + + for (extrapolation, expected) in ( + (ExtrapolationType.Extension, -0.5), + (ExtrapolationType.Periodic, 1.5), + (ExtrapolationType.Reflective, 0.5), + ) + B = constructor(values, UInt8[10, 20, 30]; extrapolation) + @test B(UInt8(5)) ≈ expected + @test only(B(zeros(1), UInt8[5])) ≈ expected + end + end + end + + @testset "Akima widened knot differences" begin + knots = Int8[-120, 10, 120] + values = [0.0, 1.0, 4.0] + for cache_parameters in (false, true) + A = AkimaInterpolation(values, knots; modified = true, cache_parameters) + reference = AkimaInterpolation(values, Float64.(knots); modified = true, cache_parameters) + @test A(-55.0) ≈ reference(-55.0) + @test A(Int8(9)) ≈ reference(9.0) + @test A(zeros(2), Int8[-55, 9]) ≈ reference.([-55.0, 9.0]) + @test DataInterpolations.derivative(A, Int8(9)) ≈ DataInterpolations.derivative(reference, 9.0) + @test DataInterpolations.integral(A, Int8(9)) ≈ DataInterpolations.integral(reference, 9.0) + end + end + @testset "Extrapolation and caching" begin u = [0.0, 0.05, 1.0, 1.05, 1.1] t = [0.0, 1.0, 1.1, 2.1, 3.1] From 48ac7914f94c739c4e44adc25652c47333f90ddc Mon Sep 17 00:00:00 2001 From: pankgeorg <8681967+pankgeorg@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:56:36 +0000 Subject: [PATCH 09/10] Preserve noninteger cubic spline arithmetic Restore the original floating-point evaluation and integral formulas. Keep checked widths and factored offsets on fixed-width integer paths. Add a finite Hermite regression and matrix integral benchmarks. Co-authored-by: Codex gpt-6.2-sol (codex-cli 0.172.0, session 01a22642-ff44-7e32-84de-f1cca932f790) --- benchmark/benchmarks.jl | 13 +++++++++++++ src/DataInterpolations.jl | 4 ++++ src/interpolation_methods.jl | 13 +++++++++---- src/interpolation_utils.jl | 18 ++++++++++++++---- src/parameter_caches.jl | 22 ++++++++++++++++------ test/interpolation_tests.jl | 24 +++++++++++++++++++----- 6 files changed, 75 insertions(+), 19 deletions(-) diff --git a/benchmark/benchmarks.jl b/benchmark/benchmarks.jl index 95bd59d90..a948e3ae6 100644 --- a/benchmark/benchmarks.jl +++ b/benchmark/benchmarks.jl @@ -68,3 +68,16 @@ 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] +SUITE["vector_valued"]["integral"] = BenchmarkGroup() +for A in ( + AkimaInterpolation(integral_values, integral_knots), + CubicHermiteSpline(integral_slopes, integral_values, integral_knots), + CubicSpline(integral_values, integral_knots), + ) + SUITE["vector_valued"]["integral"][string(nameof(typeof(A)))] = + @benchmarkable DataInterpolations.integral($A, 0.25, 10.75) +end diff --git a/src/DataInterpolations.jl b/src/DataInterpolations.jl index 2cfbb2843..17b3b9d3f 100644 --- a/src/DataInterpolations.jl +++ b/src/DataInterpolations.jl @@ -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") diff --git a/src/interpolation_methods.jl b/src/interpolation_methods.jl index f99df0101..c8d5138da 100644 --- a/src/interpolation_methods.jl +++ b/src/interpolation_methods.jl @@ -1361,16 +1361,21 @@ function _interpolate( A::CubicHermiteSpline{<:AbstractArray}, t::Number, iguess ) idx = get_idx(A, t, iguess) + Δt₀ = _widened_difference(t, A.t[idx]) + Δt₁ = _widened_difference(t, A.t[idx + 1]) + out = _u_view(A.u, idx) + Δt₀ * _u_view(A.du, idx) c₁, c₂ = get_parameters(A, idx) - return _cubic_hermite_segment_eval( - t, A.t[idx], A.t[idx + 1], _u_view(A.u, idx), _u_view(A.du, idx), c₁, c₂ - ) + out += _hermite_square_product(Δt₀, c₁ + Δt₁ * c₂, x -> x^2) + return out end +@inline _hermite_square_product(dt, c, square) = square(dt) * c +@inline _hermite_square_product(dt::FixedWidthInteger, c, square) = dt * (dt * c) + @inline function _cubic_hermite_segment_eval(ttt, ti, tip1, ui, dui, c1, c2) dt0 = _widened_difference(ttt, ti) dt1 = _widened_difference(ttt, tip1) - return ui + dt0 * (dui + dt0 * (c1 + dt1 * c2)) + return ui + dt0 * dui + _hermite_square_product(dt0, c1 + dt1 * c2, x -> x * x) end function (A::CubicHermiteSpline{<:AbstractVector{<:Number}})( diff --git a/src/interpolation_utils.jl b/src/interpolation_utils.jl index 7a7402763..0e25398eb 100644 --- a/src/interpolation_utils.jl +++ b/src/interpolation_utils.jl @@ -672,6 +672,20 @@ function du_monotonic_makima(u::AbstractVector{<:AbstractVector}, t) end function integrate_cubic_polynomial(t1, t2, offset, a, b, c, d) + if (t1 isa FixedWidthInteger && t2 isa FixedWidthInteger) || + (offset isa FixedWidthInteger && (t1 isa FixedWidthInteger || t2 isa FixedWidthInteger)) + return _integrate_cubic_integer_offsets(t1, t2, offset, a, b, c, d) + end + + t1_rel = t1 - offset + t2_rel = t2 - offset + t_sum = t1_rel + t2_rel + t_sq_sum = t1_rel^2 + t2_rel^2 + Δt = t2 - t1 + return Δt * (a + t_sum * (b / 2 + d * t_sq_sum / 4) + c * (t_sq_sum + t1_rel * t2_rel) / 3) +end + +function _integrate_cubic_integer_offsets(t1, t2, offset, a, b, c, d) x = _widened_difference(t1, offset) y = _widened_difference(t2, offset) Δt = _widened_difference(t2, t1) @@ -787,10 +801,6 @@ _u_view(u::AbstractArray, idx) = selectdim(u, ndims(u), idx) _widened_difference(x, y) = x - y -const FixedWidthInteger = Union{ - Bool, Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128, -} - _signed_widen(x) = signed(widen(x)) _signed_widen(x::Bool) = Int(x) diff --git a/src/parameter_caches.jl b/src/parameter_caches.jl index 7e9262145..37f3f9f61 100644 --- a/src/parameter_caches.jl +++ b/src/parameter_caches.jl @@ -244,16 +244,26 @@ end du₀ = _u_view(du, idx) du₁ = _u_view(du, idx + 1) Δu = _widened_difference(u₁, u₀) + return _cubic_hermite_parameters(Δu, du₀, du₁, t₀, t₁) +end + +@inline function _cubic_hermite_parameters(Δu, du₀, du₁, t₀, t₁) + Δt = t₁ - t₀ + c₁ = (Δu - du₀ * Δt) / Δt^2 + c₂ = (du₁ - du₀ - 2c₁ * Δt) / Δt^2 + return c₁, c₂ +end +@inline function _cubic_hermite_parameters(Δu, du₀, du₁, t₀::Int, t₁::Int) # Keep the common integer path in the native type through both divisions. - if t₀ isa Int && t₁ isa Int - Δt, difference_overflow = Base.Checked.sub_with_overflow(t₁, t₀) - if !difference_overflow && 0 <= Δt <= isqrt(typemax(Int)) - return _cubic_hermite_coefficients(Δu, du₀, du₁, Δt, Δt * Δt) - end - return _wide_integer_hermite_coefficients(Δu, du₀, du₁, t₀, t₁) + Δt, difference_overflow = Base.Checked.sub_with_overflow(t₁, t₀) + if !difference_overflow && 0 <= Δt <= isqrt(typemax(Int)) + return _cubic_hermite_coefficients(Δu, du₀, du₁, Δt, Δt * Δt) end + return _wide_integer_hermite_coefficients(Δu, du₀, du₁, t₀, t₁) +end +@inline function _cubic_hermite_parameters(Δu, du₀, du₁, t₀::FixedWidthInteger, t₁::FixedWidthInteger) Δt = _widened_difference(t₁, t₀) return _cubic_hermite_coefficients(Δu, du₀, du₁, Δt, _square_or_nothing(Δt)) end diff --git a/test/interpolation_tests.jl b/test/interpolation_tests.jl index 454104d28..79a4c5ad1 100644 --- a/test/interpolation_tests.jl +++ b/test/interpolation_tests.jl @@ -2103,6 +2103,16 @@ end @test_throws ArgumentError CubicHermiteSpline([1.0], [1.0], [1.0]) @test_throws ArgumentError CubicHermiteSpline(rand(2, 1), rand(2, 1), [1.0]) @test_throws ArgumentError CubicHermiteSpline([rand(2)], [rand(2)], [1.0]) + + @testset "Finite floating-point contributions" begin + for cache_parameters in (false, true) + A = CubicHermiteSpline( + [1.75e308, 1.35e308], [0.0, 8.75e307], [0.0, 0.5]; cache_parameters + ) + @test A(0.25) ≈ 4.625e307 + @test only(A(zeros(1), [0.25])) ≈ 4.625e307 + end + end end @testset "PCHIPInterpolation" begin @@ -2306,12 +2316,16 @@ end end end - @testset "Cubic large floating-point offsets" begin + @testset "Limiter-active integer data" begin for cache_parameters in (false, true) - A = MonotonicMakimaInterpolation(Float32[0, 1], Float32[0, 1.0e20]; cache_parameters) - @test A(5.0f19) ≈ 0.5f0 - @test only(A(zeros(Float32, 1), Float32[5.0e19])) ≈ 0.5f0 - @test DataInterpolations.integral(A, 5.0f19) ≈ 1.25f19 + A = MonotonicMakimaInterpolation( + UInt8[0, 10, 20, 21, 26, 31], UInt8[0, 2, 4, 6, 8, 10]; cache_parameters + ) + # The secants 5, 5, 1/2, 5/2, 5/2 give Makima slopes 40/17 and + # 155/78 at knots 4 and 6. The limiter multiplies both by 51/80. + @test A.du[3] ≈ 3 // 2 + @test A.du[4] ≈ 527 // 416 + @test A(UInt8(5)) ≈ 41 // 2 + 97 // 1664 end end From 3f142e9572ddbd0e4feb8bcd18b06cfd750d5c5b Mon Sep 17 00:00:00 2001 From: pankgeorg <8681967+pankgeorg@users.noreply.github.com> Date: Sun, 29 Nov 2026 11:33:02 +0000 Subject: [PATCH 10/10] Keep native arithmetic for safe cubic integer offsets Check integral and sorted Hermite offsets before using the compact formulas. Fuse the wide integral fallback for array-valued samples and keep small 128-bit differences in native signed arithmetic. Co-authored-by: Codex gpt-6.2-sol (codex-cli 0.172.0, session 01a22642-ff44-7e32-84de-f1cca932f790) --- benchmark/benchmarks.jl | 28 +++++++++++++------ src/derivatives.jl | 2 +- src/interpolation_methods.jl | 30 +++++++++++++++++--- src/interpolation_utils.jl | 54 ++++++++++++++++++++++++++++++++++-- test/interpolation_tests.jl | 10 +++++++ 5 files changed, 108 insertions(+), 16 deletions(-) diff --git a/benchmark/benchmarks.jl b/benchmark/benchmarks.jl index a948e3ae6..3c297bb14 100644 --- a/benchmark/benchmarks.jl +++ b/benchmark/benchmarks.jl @@ -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 # ============================================================================= @@ -72,12 +82,14 @@ 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] -SUITE["vector_valued"]["integral"] = BenchmarkGroup() -for A in ( - AkimaInterpolation(integral_values, integral_knots), - CubicHermiteSpline(integral_slopes, integral_values, integral_knots), - CubicSpline(integral_values, integral_knots), - ) - SUITE["vector_valued"]["integral"][string(nameof(typeof(A)))] = - @benchmarkable DataInterpolations.integral($A, 0.25, 10.75) +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 diff --git a/src/derivatives.jl b/src/derivatives.jl index 2c01f8515..8340f81fb 100644 --- a/src/derivatives.jl +++ b/src/derivatives.jl @@ -57,7 +57,7 @@ _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 ? _widened_difference(t, zero(knot)) : _signed_widen(t) + 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. diff --git a/src/interpolation_methods.jl b/src/interpolation_methods.jl index c8d5138da..4db767785 100644 --- a/src/interpolation_methods.jl +++ b/src/interpolation_methods.jl @@ -1378,6 +1378,12 @@ end return ui + dt0 * dui + _hermite_square_product(dt0, c1 + dt1 * c2, x -> x * x) end +@inline function _cubic_hermite_native_segment_eval(ttt, ti, tip1, ui, dui, c1, c2) + dt0 = ttt - ti + dt1 = ttt - tip1 + return ui + dt0 * dui + dt0 * dt0 * (c1 + dt1 * c2) +end + function (A::CubicHermiteSpline{<:AbstractVector{<:Number}})( out::AbstractVector, tt::AbstractVector ) @@ -1399,6 +1405,22 @@ end function _cubic_hermite_eval_sorted!( out::AbstractVector, A::CubicHermiteSpline{<:AbstractVector{<:Number}}, tt::AbstractVector ) + if eltype(A.t) === Int && eltype(tt) === Int && !isempty(tt) + lo = min(first(A.t), first(tt)) + hi = max(last(A.t), last(tt)) + span, overflow = Base.Checked.sub_with_overflow(hi, lo) + # Both sequences are sorted, so this bounds every offset and its square. + if !overflow && span <= isqrt(typemax(Int)) + return _cubic_hermite_eval_sorted!(out, A, tt, _cubic_hermite_native_segment_eval) + end + end + return _cubic_hermite_eval_sorted!(out, A, tt, _cubic_hermite_segment_eval) +end + +function _cubic_hermite_eval_sorted!( + out::AbstractVector, A::CubicHermiteSpline{<:AbstractVector{<:Number}}, tt::AbstractVector, + evaluate_segment::F + ) where {F} u = A.u t = A.t du = A.du @@ -1435,7 +1457,7 @@ function _cubic_hermite_eval_sorted!( tip1 = @inbounds t[2] c1, c2 = get_parameters(A, 1) @inbounds while i <= m && tt[i] < t1 - out[i] = _cubic_hermite_segment_eval(tt[i], t1, tip1, ui, dui, c1, c2) + out[i] = evaluate_segment(tt[i], t1, tip1, ui, dui, c1, c2) i += 1 end end @@ -1461,7 +1483,7 @@ function _cubic_hermite_eval_sorted!( j = i_first_interior + k - 1 ttt = tt[j] c1, c2 = get_parameters(A, idx) - out[j] = _cubic_hermite_segment_eval( + out[j] = evaluate_segment( ttt, t[idx], t[idx + 1], u[idx], du[idx], c1, c2 ) end @@ -1473,7 +1495,7 @@ function _cubic_hermite_eval_sorted!( idx += 1 end c1, c2 = get_parameters(A, idx) - out[i_local] = _cubic_hermite_segment_eval( + out[i_local] = evaluate_segment( ttt, t[idx], t[idx + 1], u[idx], du[idx], c1, c2 ) i_local += 1 @@ -1507,7 +1529,7 @@ function _cubic_hermite_eval_sorted!( dui = @inbounds du[n - 1] c1, c2 = get_parameters(A, n - 1) @inbounds while i <= m - out[i] = _cubic_hermite_segment_eval(tt[i], ti, tn, ui, dui, c1, c2) + out[i] = evaluate_segment(tt[i], ti, tn, ui, dui, c1, c2) i += 1 end end diff --git a/src/interpolation_utils.jl b/src/interpolation_utils.jl index 0e25398eb..2df44b6bd 100644 --- a/src/interpolation_utils.jl +++ b/src/interpolation_utils.jl @@ -674,7 +674,7 @@ end function integrate_cubic_polynomial(t1, t2, offset, a, b, c, d) if (t1 isa FixedWidthInteger && t2 isa FixedWidthInteger) || (offset isa FixedWidthInteger && (t1 isa FixedWidthInteger || t2 isa FixedWidthInteger)) - return _integrate_cubic_integer_offsets(t1, t2, offset, a, b, c, d) + return _integrate_cubic_checked(t1, t2, offset, a, b, c, d) end t1_rel = t1 - offset @@ -685,10 +685,40 @@ function integrate_cubic_polynomial(t1, t2, offset, a, b, c, d) return Δt * (a + t_sum * (b / 2 + d * t_sq_sum / 4) + c * (t_sq_sum + t1_rel * t2_rel) / 3) end -function _integrate_cubic_integer_offsets(t1, t2, offset, a, b, c, d) +@inline _checked_cubic_op(op, checked, x, y) = op(x, y), false +@inline _checked_cubic_op(op, checked, x::T, y::T) where {T <: FixedWidthInteger} = checked(x, y) + +@inline function _checked_cubic_op(op, checked, x::FixedWidthInteger, y::FixedWidthInteger) + T = promote_type(typeof(x), typeof(y)) + if typemin(T) <= x <= typemax(T) && typemin(T) <= y <= typemax(T) + return checked(T(x), T(y)) + end + return zero(T), true +end + +function _integrate_cubic_checked(t1, t2, offset, a, b, c, d) + x, x_overflow = _checked_cubic_op(-, Base.Checked.sub_with_overflow, t1, offset) + y, y_overflow = _checked_cubic_op(-, Base.Checked.sub_with_overflow, t2, offset) + Δt, width_overflow = _checked_cubic_op(-, Base.Checked.sub_with_overflow, t2, t1) + if !(x_overflow | y_overflow | width_overflow) + t_sum, sum_overflow = _checked_cubic_op(+, Base.Checked.add_with_overflow, x, y) + x², x_sq_overflow = _checked_cubic_op(*, Base.Checked.mul_with_overflow, x, x) + y², y_sq_overflow = _checked_cubic_op(*, Base.Checked.mul_with_overflow, y, y) + t_sq_sum, sq_sum_overflow = _checked_cubic_op(+, Base.Checked.add_with_overflow, x², y²) + xy, product_overflow = _checked_cubic_op(*, Base.Checked.mul_with_overflow, x, y) + quadratic, quadratic_overflow = _checked_cubic_op(+, Base.Checked.add_with_overflow, t_sq_sum, xy) + if !(sum_overflow | x_sq_overflow | y_sq_overflow | sq_sum_overflow | product_overflow | quadratic_overflow) + return Δt * (a + t_sum * (b / 2 + d * t_sq_sum / 4) + c * quadratic / 3) + end + end + x = _widened_difference(t1, offset) y = _widened_difference(t2, offset) Δt = _widened_difference(t2, t1) + return _cubic_integral_factored.(x, y, Δt, a, b, c, d) +end + +@inline function _cubic_integral_factored(x, y, Δt, a, b, c, d) # Multiply by a coefficient before multiplying offsets together. cx = x * c quadratic = x * cx + y * (cx + y * c) @@ -804,10 +834,28 @@ _widened_difference(x, y) = x - y _signed_widen(x) = signed(widen(x)) _signed_widen(x::Bool) = Int(x) -function _widened_difference(x::FixedWidthInteger, y::FixedWidthInteger) +@inline function _widened_difference(x::FixedWidthInteger, y::FixedWidthInteger) + if x isa Union{Int128, UInt128} || y isa Union{Int128, UInt128} + return _difference_128(x, y) + end return _signed_widen(x) - _signed_widen(y) end +function _difference_128(x, y) + if typemin(Int128) <= x <= typemax(Int128) && typemin(Int128) <= y <= typemax(Int128) + difference, overflow = Base.Checked.sub_with_overflow(Int128(x), Int128(y)) + overflow || return difference + elseif x >= 0 && y >= 0 + negative = x < y + magnitude = negative ? UInt128(y) - UInt128(x) : UInt128(x) - UInt128(y) + if magnitude <= UInt128(typemax(Int128)) + return negative ? -Int128(magnitude) : Int128(magnitude) + end + negative && magnitude == UInt128(typemax(Int128)) + 1 && return typemin(Int128) + end + return big(x) - big(y) +end + function _widened_difference(x::AbstractArray{<:Integer}, y::AbstractArray{<:Integer}) return _widened_difference.(x, y) end diff --git a/test/interpolation_tests.jl b/test/interpolation_tests.jl index 79a4c5ad1..5ae114167 100644 --- a/test/interpolation_tests.jl +++ b/test/interpolation_tests.jl @@ -2113,6 +2113,16 @@ end @test only(A(zeros(1), [0.25])) ≈ 4.625e307 end end + + @testset "Small 128-bit knot offsets" begin + for T in (Int128, UInt128), cache_parameters in (false, true) + A = CubicHermiteSpline(zeros(4), [0.0, 1.0, 2.0, 3.0], T[0, 1, 2, 3]; cache_parameters) + @test A(T(1)) === 1.0 + @test A(0.5) === 0.5 + @test DataInterpolations.integral(A, T(0), T(2)) === 2.0 + @test DataInterpolations.integral(A, 0, 2) === 2.0 + end + end end @testset "PCHIPInterpolation" begin