Using the AlgLib ODE (Runge-Kutta) Solver with Excel

Or to be more correct, the AlgLib Cash-Karp Solver, Cash-Karp being a refinement of the Runge-Kutta method of solving ordinary differential equations.

Solution of differential equations is an iterative process requiring the repeated application of the solver routine followed by evaluation of the differential equation using an external routine.  This is performed in AlgLib by a process known as reverse communication, whereby an initialisation routine creates a “State” object which is used to transfer data between the solver routine and the external equation evaluation routine (which is in this case a VBA function).  The steps required to wrap this process in an Excel User Defined Function (UDF) are:

  1. Read the name of the ODE evaluation routine and the required input data from the spreadsheet.
  2. Convert data in spreadsheet ranges to variant arrays.
  3. Convert variant arrays (which will always be base 1, 2 dimension arrays) into the form required by the AlgLib routines, which will always be base 0, and may be 1 or 2 dimensional.
  4. Evaluate any additional values required by the AlgLib routines
  5. Set up any required output arrays
  6. Call the appropriate AlgLib routine to initialise the State object
  7. Loop through the AlgLib solver routine and the external ODE evaluation routine until the solver routine returns “False”, which indicates that it has finished.  The VBA function named in “FuncName” is called using the Application.Run method.
  8. Extract the desired results from the State object using the appropriate AlgLib routine
  9. If necessary convert the AlgLib output arrays to a form suitable for Excel.
  10. Assign the output array to the function return value.
  11. Import the necessary AlgLib routines; in this case the only required modules are ODESolver.bas and ap.bas

This process is illustrated in the code for the UDF ODE() shown below (may take some time to display correctly). 

 This code and all the related AlgLib and other routines are included in the file ODESolver.zip.

Function ODE(FuncName As String, Initial As Variant, XA As Variant, _
CoeffA As Variant, Optional Eps As Double = 0.000001, _
Optional Step As Double = 0, Optional MaxIts As Long = 100)
Dim M As Long, N As Long, State As ODESolverState, _
YA() As Double, XA2() As Double, YA2() As Double, i As Long, _
Rtn As Boolean, Rep As ODESolverReport, NC As Long

' The VBA function arguments are the name of the VBA
' ODE evaluation routine, followed by the required input data.

' Convert data in spreadsheet ranges to variant arrays
Initial = GetArray(Initial)
XA = GetArray(XA)
CoeffA = GetArray(CoeffA)

' Convert variant arrays (which will always be base
' 1, 2 dimension arrays) into the form required by the AlgLib
' routines, which will always be base 0, and may be 1 or 2 dimensional.
Rtn = VarAtoDouble1D_0(Initial, YA, N, NC)
If N = 1 And NC > 1 Then N = NC
Rtn = VarAtoDouble1D_0(XA, XA2, M, NC)

' Evaluate any additional values required by the AlgLib routines
MaxIts = MaxIts * M

'Set up any required output arrays
ReDim YA2(0 To M - 1, 0 To N - 1)

'Call the appropriate AlgLib routine to initialise the State object
Call ODESolverRKCK(YA(), N, XA2, M, Eps, Step, State)

' Loop through the AlgLib solver routine and the external ODE
' evaluation routine until the solver routine returns "False",
' which indicates that it has finished.
' The VBA function named in "FuncName" is called using
' the Application.Run method.
Rtn = True
i = 0
Do While Rtn = True And i < MaxIts
Rtn = ODESolverIteration(State)
State.DY = Application.Run(FuncName, State.X, State.Y, CoeffA)
i = i + 1
Loop

 ' Extract the desired results from the State
 ' object using the appropriate AlgLib routine
 Call ODESolverResults(State, M, XA2, YA2, Rep)

' If necessary convert the AlgLib output array(s) to
' a form suitable for Excel. In this case YA2 is
' a 2D base 0 array, which may be assigned to the
' function return value without further processing.

' Assign the output array to the function return value
 ODE = YA2

End Function

The screen shots below show examples of the application of the ODE() function (more details of the final example, buckling of a strut, will be given in the next post):

ODE input and output details, click for full size view

Example 1; First Order kinetic process

Example 1 Output

Example 2; Process dependent on X and Y

Example 2 results

Example 3; damped vibration system

Example 3 output

Example 4; Undamped SHM, ball through the centre of the Earth

Example 4 results

Example 5; deflection of a cantilever strut and buckling load

Example 5 results

Posted in AlgLib, Beam Bending, Differential Equations, Excel, Maths, Newton, UDFs, VBA | Tagged , , , , , , , , | 8 Comments

Elegant solutions, Simple Harmonic Motion, and the hole through the middle of the Earth

No, not the hole (beloved of conspiracy theorists everywhere) where our alien overlords keep their UFO’s, but rather the equally imaginary hole from Pole to Pole (beloved of physics teachers everywhere) where we can drop in objects and watch them travel to the opposite end of the hole and back again, as an example of bodies moving with simple harmonic motion.  In reality it’s not so simple, and in future posts I will develop spreadsheet tools to allow us to analyse the motion of a mass dropped into this hole in more detail to see what they would really do, but for now we will look at why, with suitable simplifying assumptions, the mass will move with simple harmonic motion, and what it’s period of oscillation will be.

The simplifying assumptions are:

  • The hole passes exactly along the axis of rotation of the Earth, and this line is moving through space with constant velocity (so we can ignore tidal effects)
  • The Earth is a perfect sphere of uniform density
  • The hole is a perfect vacuum

We want to show firstly that an object dropped into this hole will move with simple harmonic motion, and secondly to calculate how long it will take to pass through the hole, and back again to exactly the point from which it was dropped.

Simple harmonic motion is the motion of a body attached to an ideal spring, with no other forces acting, so that the force on the body is proportional to the extension or compression of the spring (according to Hooke’s Law) and is directed towards the point at which the spring has zero extension.

How does the gravitational force vary along the length of the hole through the middle of the Earth?  This can be simply determined by dividing the sphere of the Earth into two concentric parts at any depth down the hole; an outer shell and an inner ball.  It can be shown that the gravitational field inside a spherical shell is zero for any thickness of shell, so that the gravitational field at any point down the hole is equal to that due to the sphere below that level.  If this sphere has a radius R the mass of the sphere is proportional to R3, and gravitational force at the surface of the sphere is proportional to mass / R2, the gravitational force at distance R from the centre is therefore proportional to R3/ R2 = R, and the resulting motion will be simple harmonic.

To determine the period of oscillation of a body dropped down the hole, consider a second body moving at orbital velocity at the surface of the Earth, that is with a radial acceleration, ar, equal to the acceleration due to gravity at the surface, g.  As this body moves around the Earth, if the radial line to the body forms an angle θ with the axis of the hole (i.e. the polar axis) then:

  • The component of its radial acceleration parallel to the polar axis will be gCosθ
  • Its perpendicular distance from the equatorial plane will be RCosθ
  • Its acceleration towards the equatorial plane is therefore proportional to its distance from this plane
  • Since its initial acceleration was equal to that of an object dropped down the Polar hole, and its component of acceleration in the direction of the hole is proportional to its distance from the plane through the centre of the hole, it follows that the path of the orbiting body projected onto the Polar Axis follows exactly the same path as an object dropped down the hole

Radial acceleration of a body moving with velocity V in a circle of radius R = V2/R
For orbital velocity, radial acceleration = g, therefore V = (gR)0.5
Circumference of a sphere = 2πR, therefore orbital period = 2πR / (gR)0.5 = 2π(R/g)0.5 = Period of oscillation of a body through the Polar hole.

Taking g = 9.81 m/s2 and R = 6,371,000 m, the period of oscillation of the mass dropped down the hole through the middle of the Earth is therefore:
2π(6,371,000/9.81)0.5 = 5063 seconds, or 84 minutes and 23 seconds.

The maximum speed of the object falling down the hole will be when it reaches the centre, at which point it will have zero acceleration and will be travelling parallel to the orbiting body, and will therefore have a speed equal to orbital velocity, i.e. (9.81*6,371,000)0.5 = 7906 m/s.

Posted in Differential Equations, Maths, Newton | Tagged , , , | 5 Comments

Find dead links

When useful sites close, leading to dead links, try:

www.archive.org

where web sites are archived on a regular basis.

You will need the exact web address, there is no text search, but if you have it there is a good chance you will find what you are looking for.

Thanks to the Eng-Tips forum for this tip.

Posted in Computing - general | Tagged , | Leave a comment

Xll add-ins; are they worth the trouble?

As regular readers will know, I occasionally delve into compiling code in C++, or even Fortran, as dlls and link to them with a short piece of VBA to communicate between the spreadsheet and the compiled code.  I have also sometimes had a look at compiling code as an xll file, but found it all too hard, and it hasn’t been obvious to me what the benefits are.  What do others think?  Am I missing something?  What are the benefits of compiling an xll file, compared with a dll?

For future reference (should I decide to have another go at the xll route), two useful looking resources are:

Excel xll Add-in Development

The XLL Add-In Library

Make that three:

Grumpy Old Programmer on XL-DNA

Posted in Excel, Link to dll | Tagged , , , | 8 Comments

AlgLib Spline Functions

Following earlier posts on cubic splines I have collected the Alglib interpolation routines, and the necessary supporting routines, and written interface functions to allow most of the 1Dspline routines to be called from the spreadsheet.  Since there is a large measure of overlap in the supporting routines, I have also included the VBA versions of the basic matrix routines.  The spreadsheet (including full open source code) can be downloaded from AL-Spline-Matrix07.zip (Excel 2007 version) or AL-Spline-Matrix03.zip (pre 2007 versions).

The included functions are; Spline Functions:

  • Cspline1DA: Cubic spline interpolation
  • Akimspline1DA: Akima spline interpolation
  • CRspline1DA: Catmull-Rom spline interpolation
  • Hspline1DA: Hermite spline interpolation
  • Csplinefit1DA: Least squares fit of cubic spline
  • Csplinefitcw1DA: Weighted and constrained least squares fit of cubic spline
  • CSplineint1D: Integration of a cubic spline
  • AkimSplineint1D: Integration of an Akima spline
  • CRSplineint1D: Integration of a Catmull-Rom spline
  • HSplineint1D: Integration of a Hermite spline
  • Csplinediff1D: Differentiation of a cubic spline
  • Akimsplinediff1D: Differentiation of an Akima spline
  • CRsplinediff1D: Differentiation of a Catmull-Rom spline
  • Hsplinediff1D: Differentiation of a Hermite spline

Matrix Functions:

  • RMatInv: Inverse of real matrix
  • CMatInv: Inverse of complex matrix
  • EigenVR: Eigen values and Eigen vectors of a real matrix
  • EigenVS: Eigen values and Eigen vectors of a symmetric matrix

The main differences from the spline functions presented previously are:

  • The Hermite Spline function requires user input first derivative values for each point.
  • The Akima Spline function was not previously included
  • The cubic spline and Catmull-Rom spline functions allow the end segments to be specified as quadratic or cyclic
  • Data may be listed in any order, and is sorted by increasing X value by the function
  • Functions are included to perform least-squares fitting of curves (with or without weighting and or constraints), as well as exact fit.
  • Integration functions are provided for each spline type.

Further details of the interface functions, and the required Alglib modules, will be provided in a later post.

Posted in Excel, Maths, Newton, UDFs, VBA | Tagged , , , , , , , , , , | 6 Comments