Victor hyk
2013-Nov-01 20:00 UTC
[R] Impose constraint on first order derivative at a point for cubic smoothing spline
Hello, Dr. Simon Wood told me how to force a cubic spline passing through a point. The code is as following. Anyone who knows how I can change the code to force the first derivative to be certain value. For example, the first derivative of the constrained cubic spline equals 2 at point (0, 0.6). I really appreciate your help! Thanks! Best Victor Here is the initial reply and code provided by Dr. Simon Wood: "Actually, you might as well use "gam" directly for this (has the advantage that the smoothing parameter will be chosen correctly subject to the constraint). Here is some code. Key idea is to set the basis and penalty for the spline up first, apply the constraint, and then use gam to fit it..." best, Simon ## Example constraining spline to pass through a ## particular point (0,.6)... ## Fake some data... library(mgcv) set.seed(0) n <- 100 x <- runif(n)*4-1;x <- sort(x); f <- exp(4*x)/(1+exp(4*x));y <- f+rnorm(100)*0.1;plot(x,y) dat <- data.frame(x=x,y=y) ## Create a spline basis and penalty, making sure there is a knot ## at the constraint point, (0 here, but could be anywhere) knots <- data.frame(x=seq(-1,3,length=9)) ## create knots ## set up smoother... sm <- smoothCon(s(x,k=9,bs="cr"),dat,knots=knots)[[1]] ## 3rd parameter is value of spline at knot location 0, ## set it to 0 by dropping... X <- sm$X[,-3] ## spline basis S <- sm$S[[1]][-3,-3] ## spline penalty off <- y*0 + .6 ## offset term to force curve through (0, .6) ## fit spline constrained through (0, .6)... b <- gam(y ~ X - 1 + offset(off),paraPen=list(X=list(S))) lines(x,predict(b)) ## compare to unconstrained fit... b.u <- gam(y ~ s(x,k=9),data=dat,knots=knots) lines(x,predict(b.u)) [[alternative HTML version deleted]]
Seemingly Similar Threads
- Use pcls in "mgcv" package to achieve constrained cubic spline
- Natural cubic splines produced by smooth.Pspline and predict function in the package "pspline"
- Constrained cubic smoothing spline
- finding the best cubic spline fitting
- basic cubic spline smoothing (resending because not sure about pending)