I'm porting some code from R to Julia, and struggling with translating R's spline
function. I need a Julia function:
function spline_j(x,y,xout)
that yields the same return as calling the R function:
spline(x,y,,"fmm",,,xout)
i.e. using the method of Forsyth, Malcolm and Moler, which is the default method in R.
My x
and y
are always 1-dimensional, but the points of x
are not regularly spaced. That non-regularity seems to rule out using the pure-Julia Interpolations
package as the documentation states "presently only LinearInterpolation
supports irregular grids".
The Dierckx
package supports irregular x
, so a candidate for spline_j
is:
using Dierckx
function spline_j(x, y, xout)
spl = Dierckx.Spline1D(x, y)
spl(xout)
end
which matches R's spline
function if method
is "natural"
.
Is it possible to replicate R's "fmm"
method in Julia?
Following this PR https://github.com/JuliaMath/Interpolations.jl/pull/238 (merged as #243), Interpolations.jl actually has a number of excellent monotonic spline interpolation algorithms that support irregular grids, including Fritsch-Carlson (1980), Fritsch-Butland (1984), and Steffen (1990).
It doesn't seem to be reflected in the docs yet, but the options are visible in the following git diff
For example:
using Interpolations, Plots
x = sort(2*rand(10))
y = x.^2 .+ rand.()
itp = interpolate(x,y,FritschCarlsonMonotonicInterpolation())
xq = minimum(x):0.01:maximum(x)
plot(x,y, seriestype=:scatter, label="Data", legend=:topleft, framestyle=:box)
plot!(xq, itp.(xq), label="Interpolation")
If you prefer different interpolation methods, you can also substitute
FiniteDifferenceMonotonicInterpolation
,FritschButlandMonotonicInterpolation
, or SteffenMonotonicInterpolation
for FritschCarlsonMonotonicInterpolation
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With