How to save and load spline interpolation function

2019-02-27 17:14发布

I need to create thousands and thousands of interpolation splines, each based on 5 pairs of (x, y) values. I would like to save them in a database (or csv file).

How can I export / import them, say in a text format or as an array of real parameters to rebuild each function when I need them?

1条回答
女痞
2楼-- · 2019-02-27 17:47

If you are using the splinefun function from R base package stats, it is very easy to export its construction information.

set.seed(0)
xk <- c(0, 1, 2)
yk <- round(runif(3), 2)
f <- splinefun(xk, yk, "natural")  ## natural cubic spline
construction_info <- environment(f)$z
str(construction_info)
# $ method: int 2
# $ n     : int 3
# $ x     : num [1:3] 0 1 2
# $ y     : num [1:3] 0.9 0.27 0.37
# $ b     : num [1:3] -0.812 -0.265 0.282
# $ c     : num [1:3] 0 0.547 0
# $ d     : num [1:3] 0.182 -0.182 0

The following illustrates what they mean and how we may re-construct the spline manually.

There are n = 3 points, (x[i], y[i]), hence two pieces.

attach(construction_info)

## plot the interpolation spline in gray
curve(f(x, 0), from = x[1], to = x[n], lwd = 10, col = 8)

## highlight knots
points(x, y, pch = 19)

## piecewise re-construction 
piece_cubic <- function (x, xi, yi, bi, ci, di) {
  yi + bi * (x - xi) + ci * (x - xi) ^ 2 + di * (x - xi) ^ 3
  }

## loop through pieces
for (i in 1:(n - 1)) {
  curve(piece_cubic(x, x[i], y[i], b[i], c[i], d[i]), from = x[i], to = x[i + 1],
        add = TRUE, col = i + 1)
  }

detach(construction_info)

enter image description here

We see that our manual re-construction is correct.

Exporting construction information allows us to move away from R and use it elsewhere.

查看更多
登录 后发表回答