Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate curvature from smooth.spline in R

Tags:

r

spline

is there a way to calculate the curvature in a specific point having a smooth.spline curve (or similar)in R? The curve is calculate from a set of x,y points.

Thank you in advance.

like image 715
BlueTree Avatar asked Jan 23 '15 16:01

BlueTree


1 Answers

This one is actually very easy if you know that there is a predict() method for objects created by smooth.spline() and that this method has an argument deriv which allows you to predict a given derivative (in your case the second derivative is required) instead of points on the spline.

 cars.spl <- with(cars, smooth.spline(speed, dist, df = 3))
 with(cars, predict(cars.spl, x = speed, deriv = 2))

Which gives:

$x
 [1]  4  4  7  7  8  9 10 10 10 11 11 12 12 12 12 13 13 13 13 14 14 14 14 15 15
[26] 15 16 16 17 17 17 18 18 18 18 19 19 19 20 20 20 20 20 22 23 24 24 24 24 25

$y
 [1] -6.492030e-05 -6.492030e-05  3.889944e-02  3.889944e-02  5.460044e-02
 [6]  7.142609e-02  6.944645e-02  6.944645e-02  6.944645e-02  9.273343e-02
[11]  9.273343e-02  1.034153e-01  1.034153e-01  1.034153e-01  1.034153e-01
[16]  5.057841e-02  5.057841e-02  5.057841e-02  5.057841e-02  1.920888e-02
[21]  1.920888e-02  1.920888e-02  1.920888e-02  1.111307e-01  1.111307e-01
[26]  1.111307e-01  1.616749e-01  1.616749e-01  1.801385e-01  1.801385e-01
[31]  1.801385e-01  1.550027e-01  1.550027e-01  1.550027e-01  1.550027e-01
[36]  2.409237e-01  2.409237e-01  2.409237e-01  2.897166e-01  2.897166e-01
[41]  2.897166e-01  2.897166e-01  2.897166e-01  1.752232e-01  1.095682e-01
[46] -1.855994e-03 -1.855994e-03 -1.855994e-03 -1.855994e-03  4.478382e-05

where $y is the second derivative of the fitted spline, evaluated at the observed speed values in the data used to fit the spline. Of course you can plug in any values you want here, such as 100 values equally spaced over the range of speed. For example:

newspeed <- with(cars, seq(min(speed), max(speed), length = 100))
curvature <- predict(cars.spl, x = newspeed, deriv = 2)

plot(curvature, type = "l")
like image 74
Gavin Simpson Avatar answered Sep 20 '22 13:09

Gavin Simpson