Show physics, math and engineering students how an ODE solver is made and how effective R classes can be for the construction of the equations that describe natural phenomena. Inspiration for this work comes from the book on "Computer Simulations in Physics" by Harvey Gould, Jan Tobochnik, and Wolfgang Christian. Book link: < http://www.compadre.org/osp/items/detail.cfm?ID=7375>.
The goal of rODE
is to explore R
and its S4
classes and its differences with Java and Python classes while exploring physics simulations by solving ordinary differential equations (ODE
).
This is not your typical black-box ODE solver. You really have to develop your ODE algorithm using any of the ODE solvers available in the package. The objective is learning while coding R, understanding the physics and using the math.
rODE
has been inspired on the extraordinary physics library for computer simulations OpenSourcePhyisics. Take a look at it at http://opensourcephysics.org. I highly recommend the book An Introduction to Computer Simulation Methods: Applications To Physical Systems, (Gould, Tobochnik, and Christian, 2017)
. It has helped me a lot in understanding the physics behind ordinary differential equations. The book briliantly combines code, algorithms, math and physics.
Additionally I have consulted these sources during the developing of the package rODE
:
(Nobles, 1974)
(Atkinson, Han, and Stewart, 2009)
.(Sincovec, 1975)
.(Ritschel, 2013)
.(Kimura, 2009)
.(Dormand and Prince, 1980)
, where you can see the derivation of the ODE solver RK-45
.(Soetaert, Petzoldt, and Setzer, 2010)
.(Ashino, Nagase, and Vaillancourt, 2000)
.The ODE solvers implemented in R so far:
You can install the latest development version of rODE
from github with:
devtools::install_github("f0nzie/rODE", ref = "develop")
Or the stable
version from CRAN
:
install.packages("rODE")
Example scripts are located under the folder examples
inside the package.
These examples make use of a parent class containing a customized rate calculation as well as the step and startup method. The methods that you would commonly find in the base script or parent class are:
getRate()
getState()
step()
or doStep()
setStepSize()
init()
, which is not the same as the S4
class initialize
methodinitialize()
, andThese methods are defined in the virtual classes ODE
and ODESolver
.
Two other classes that serve as definition classes for the ODE solvers are: AbstractODESolver
and ODEAdaptiveSolver
.
For instance, the application KeplerApp.R
needs the class Kepler
located in the Kepler.R
script, which is called with planet <- Kepler(r, v)
, an ODE
object. The solver for the same application is RK45
called with solver <- RK45(planet)
, where planet
is a previuously declared ODE
object. Since RK45
is an ODE solver, the script RK45.R
will be located in the folder ./R
in the package.
The vignettes contain examples of the use of the various ODE solvers.
For instance, the notebook Comparison
and Kepler
use the ODE solver RK45
; FallingParticle
and Planet
use the Euler
solver; Pendulum
makes use of EulerRichardson
; Planet
of Euler
, Projectile
; Reaction
of RK4
, and KeplerEnergy
uses the ODE solver Verlet
.
There are tests for the core ODE solver classes under tests/testthat, as well as additional tests for the examples themselves.
The tests for the examples are two: one for the base/parent classes such as Kepler
or Planet
or Projectile
; this test runner is called run_tests_this_folder.R
.
For the applications there is another runner (run_test_applications.R
) that opens each of the applications as request for a return value. If the hard coded value is not returned, the test will fail. This ensures that any minor change in the core solver classes do not have any impact on the application solutions, and if there is, it must be explained.
You can test all applications under the examples
folder by running the script run_test_applications.R
. The way it works is by getting the list of all applications by filtering those ending with App
. Then removes the extension .R
from each app and starts looping to call each of the applications with do.call
. A list contains the expected
results that are compared against the result coming out from the call to the R application.
library(rODE)#>#> Attaching package: 'rODE'#> The following object is masked from 'package:stats':#>#> stepimportFromExamples("AdaptiveStep.R")# running functionAdaptiveStepApp <- function(verbose = FALSE) {ode <- new("Impulse")ode_solver <- RK45(ode)ode_solver <- init(ode_solver, 0.1)ode_solver <- setTolerance(ode_solver, 1.0e-4)i <- 1; rowVector <- vector("list")while (getState(ode)[1] < 12) {rowVector[[i]] <- list(s1 = getState(ode)[1],s2 = getState(ode)[2],t = getState(ode)[3])ode_solver <- step(ode_solver)ode <- [email protected]i <- i + 1}return(data.table::rbindlist(rowVector))}# run applicationsolution <- AdaptiveStepApp()plot(solution)
# ++++++++++++++++++++++++++++++++++++++++++++++++ example: ComparisonRK45App.R# Compares the solution by the RK45 ODE solver versus the analytical solution# Example file: ComparisonRK45App.R# ODE Solver: Runge-Kutta 45# Class: RK45library(rODE)importFromExamples("ODETest.R")ComparisonRK45App <- function(verbose = FALSE) {ode <- new("ODETest") # create an `ODETest` objectode_solver <- RK45(ode) # select the ODE solverode_solver <- setStepSize(ode_solver, 1) # set the stepode_solver <- setTolerance(ode_solver, 1e-8) # set the tolerancerowVector <- vector("list")time <- 0i <- 1while (time < 50) {rowVector[[i]] <- list(t = [email protected]@state[2],s1 = getState([email protected])[1],s2 = getState([email protected])[2],xs = getExactSolution([email protected], time),rc = getRateCounts(ode),time = time)ode_solver <- step(ode_solver) # advance one stepstepSize <- [email protected] # update the step sizetime <- time + stepSizestate <- getState([email protected]) # get the `state` vectori <- i + 1}return(data.table::rbindlist(rowVector)) # a data table with the results}# show solutionsolution <- ComparisonRK45App() # run the exampleplot(solution)
# +++++++++++++++++++++++++++++++++++++++++++++++ example: FallingParticleApp.R# Application that simulates the free fall of a ball using Euler ODE solverlibrary(rODE)importFromExamples("FallingParticleODE.R") # source the classFallingParticleODEApp <- function(verbose = FALSE) {# initial valuesinitial_y <- 10initial_v <- 0dt <- 0.01ball <- FallingParticleODE(initial_y, initial_v)solver <- Euler(ball) # set the ODE solversolver <- setStepSize(solver, dt) # set the steprowVector <- vector("list")i <- 1# stop loop when the ball hits the ground, state[1] is the vertical positionwhile ([email protected][1] > 0) {rowVector[[i]] <- list(t = [email protected][3],y = [email protected][1],vy = [email protected][2])solver <- step(solver) # move one step at a timeball <- [email protected] # update the ball statei <- i + 1}DT <- data.table::rbindlist(rowVector)return(DT)}# show solutionsolution <- FallingParticleODEApp()plot(solution)
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ example KeplerApp.R# KeplerApp solves an inverse-square law model (Kepler model) using an adaptive# stepsize algorithm.# Application showing two planet orbiting# File in examples: KeplerApp.Rlibrary(rODE)importFromExamples("Kepler.R") # source the class KeplerKeplerApp <- function(verbose = FALSE) {# set the orbit into a predefined state.r <- c(2, 0) # orbit radiusv <- c(0, 0.25) # velocitydt <- 0.1planet <- Kepler(r, v)solver <- RK45(planet)rowVector <- vector("list")i <- 1while ([email protected][5] <= 10) {rowVector[[i]] <- list(t = [email protected][5],planet1.r = [email protected][1],p1anet1.v = [email protected][2],planet2.r = [email protected][3],p1anet2.v = [email protected][4])solver <- step(solver)planet <- [email protected]i <- i + 1}DT <- data.table::rbindlist(rowVector)return(DT)}solution <- KeplerApp()plot(solution)
# ++++++++++++++++++++++++++++++++++++++++++++++++++ example: KeplerEnergyApp.R# Demostration of the use of the Verlet ODE solver#library(rODE)importFromExamples("KeplerEnergy.R") # source the class KeplerKeplerEnergyApp <- function(verbose = FALSE) {# initial valuesx <- 1vx <- 0y <- 0vy <- 2 * pidt <- 0.01tol <- 1e-3particle <- KeplerEnergy()particle <- init(particle, c(x, vx, y, vy, 0))odeSolver <- Verlet(particle)odeSolver <- init(odeSolver, dt)[email protected] <- odeSolverinitialEnergy <- getEnergy(particle)rowVector <- vector("list")i <- 1while (getTime(particle) <= 1.20) {rowVector[[i]] <- list(t = [email protected][5],x = [email protected][1],vx = [email protected][2],y = [email protected][3],vy = [email protected][4],E = getEnergy(particle))particle <- doStep(particle)energy <- getEnergy(particle)i <- i + 1}DT <- data.table::rbindlist(rowVector)return(DT)}solution <- KeplerEnergyApp()plot(solution)
library(rODE)importFromExamples("Logistic.R") # source the class Logistic# Run the applicationLogisticApp <- function(verbose = FALSE) {x <- 0.1vx <- 0r <- 2 # Malthusian parameter (rate of maximum population growth)K <- 10.0 # carrying capacity of the environmentdt <- 0.01; tol <- 1e-3; tmax <- 10population <- Logistic()population <- init(population, c(x, vx, 0), r, K)odeSolver <- Verlet(population)odeSolver <- init(odeSolver, dt)[email protected] <- odeSolverrowVector <- vector("list")i <- 1while (getTime(population) <= tmax) {rowVector[[i]] <- list(t = getTime(population),s1 = [email protected][1],s2 = [email protected][2])population <- doStep(population)i <- i + 1}DT <- data.table::rbindlist(rowVector)return(DT)}# show solutionsolution <- LogisticApp()plot(solution)
# ++++++++++++++++++++++++++++++++++++++++++++++++++ example: PendulumApp.R# Simulation of a pendulum using the EulerRichardson ODE solverlibrary(rODE)suppressPackageStartupMessages(library(ggplot2))importFromExamples("Pendulum.R") # source the classPendulumApp <- function(verbose = FALSE) {# initial valuestheta <- 0.2thetaDot <- 0dt <- 0.1ode <- new("ODE")pendulum <- Pendulum()[email protected][3] <- 0 # set time to zero, t = 0pendulum <- setState(pendulum, theta, thetaDot)pendulum <- setStepSize(pendulum, dt = dt) # using stepSize in RK4[email protected] <- setStepSize([email protected], dt) # set new step sizerowvec <- vector("list")i <- 1while ([email protected][3] <= 40) {rowvec[[i]] <- list(t = [email protected][3], # timetheta = [email protected][1], # anglethetadot = [email protected][2]) # derivative of anglependulum <- step(pendulum)i <- i + 1}DT <- data.table::rbindlist(rowvec)return(DT)}# show solutionsolution <- PendulumApp()plot(solution)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ example: PlanetApp.R# Simulation of Earth orbiting around the SUn using the Euler ODE solverlibrary(rODE)importFromExamples("Planet.R") # source the classPlanetApp <- function(verbose = FALSE) {# x = 1, AU or Astronomical Units. Length of semimajor axis or the orbit# of the Earth around the Sun.x <- 1; vx <- 0; y <- 0; vy <- 6.28; t <- 0state <- c(x, vx, y, vy, t)dt <- 0.01planet <- Planet()[email protected] <- setStepSize([email protected], dt)planet <- init(planet, initState = state)rowvec <- vector("list")i <- 1# run infinite loop. stop with ESCAPE.while ([email protected][5] <= 90) { # Earth orbit is 365 days around the sunrowvec[[i]] <- list(t = [email protected][5], # just doing 3 monthsx = [email protected][1], # to speed up for CRANvx = [email protected][2],y = [email protected][3],vy = [email protected][4])for (j in 1:5) { # advances timeplanet <- doStep(planet)}i <- i + 1}DT <- data.table::rbindlist(rowvec)return(DT)}# run the applicationsolution <- PlanetApp()select_rows <- seq(1, nrow(solution), 10) # do not overplotsolution <- solution[select_rows,]plot(solution)
# +++++++++++++++++++++++++++++++++++++++++++++++++ application: ProjectileApp.R# test Projectile with RK4# originally uses Eulerlibrary(rODE)importFromExamples("Projectile.R") # source the classProjectileApp <- function(verbose = FALSE) {# initial valuesx <- 0; vx <- 10; y <- 0; vy <- 10state <- c(x, vx, y, vy, 0) # state vectordt <- 0.01projectile <- Projectile()projectile <- setState(projectile, x, vx, y, vy)[email protected] <- init([email protected], 0.123)[email protected] <- setStepSize([email protected], dt)rowV <- vector("list")i <- 1while ([email protected][3] >= 0) {rowV[[i]] <- list(t = [email protected][5],x = [email protected][1],vx = [email protected][2],y = [email protected][3], # vertical positionvy = [email protected][4])projectile <- step(projectile)i <- i + 1}DT <- data.table::rbindlist(rowV)return(DT)}solution <- ProjectileApp()plot(solution)
# +++++++++++++++++++++++++++++++++++++++++++++++++++ application: ReactionApp.R# ReactionApp solves an autocatalytic oscillating chemical# reaction (Brusselator model) using# a fourth-order Runge-Kutta algorithm.library(rODE)importFromExamples("Reaction.R") # source the classReactionApp <- function(verbose = FALSE) {X <- 1; Y <- 5;dt <- 0.1reaction <- Reaction(c(X, Y, 0))solver <- RK4(reaction)rowvec <- vector("list")i <- 1while ([email protected]@state[3] < 100) { # stop at t = 100rowvec[[i]] <- list(t = [email protected]@state[3],X = [email protected]@state[1],Y = [email protected]@state[2])solver <- step(solver)i <- i + 1}DT <- data.table::rbindlist(rowvec)return(DT)}solution <- ReactionApp()plot(solution)
# +++++++++++++++++++++++++++++++++++++++++++++++ application: RigidBodyNXFApp.R# example of a nonstiff system is the system of equations describing# the motion of a rigid body without external forces.library(rODE)importFromExamples("RigidBody.R")# run the applicationRigidBodyNXFApp <- function(verbose = FALSE) {# load the R class that sets up the solver for this applicationy1 <- 0 # initial y1 valuey2 <- 1 # initial y2 valuey3 <- 1 # initial y3 valuedt <- 0.01 # delta time for stepbody <- RigidBodyNXF(y1, y2, y3)solver <- Euler(body)solver <- setStepSize(solver, dt)rowVector <- vector("list")i <- 1# stop loop when the body hits the groundwhile ([email protected][4] <= 12) {rowVector[[i]] <- list(t = [email protected][4],y1 = [email protected][1],y2 = [email protected][2],y3 = [email protected][3])solver <- step(solver)body <- [email protected]i <- i + 1}DT <- data.table::rbindlist(rowVector)return(DT)}# get the data table from the appsolution <- RigidBodyNXFApp()plot(solution)
library(rODE)importFromExamples("SHO.R")# SHOApp.RSHOApp <- function(...) {x <- 1.0; v <- 0; k <- 1.0; dt <- 0.01; tolerance <- 1e-3sho <- SHO(x, v, k)solver_factory <- ODESolverFactory()solver <- createODESolver(solver_factory, sho, "DormandPrince45")# solver <- DormandPrince45(sho) # this can also be usedsolver <- setTolerance(solver, tolerance)solver <- init(solver, dt)i <- 1; rowVector <- vector("list")while ([email protected][3] <= 500) {rowVector[[i]] <- list(x = [email protected][1],v = [email protected][2],t = [email protected][3])solver <- step(solver)sho <- [email protected]i <- i + 1}return(data.table::rbindlist(rowVector))}solution <- SHOApp()plot(solution)
# ++++++++++++++++++++++++++++++++++++++++++++++++++application: SpringRK4App.R# Simulation of a spring considering no frictionlibrary(rODE)importFromExamples("SpringRK4.R")# run applicationSpringRK4App <- function(verbose = FALSE) {theta <- 0thetaDot <- -0.2tmax <- 22; dt <- 0.1ode <- new("ODE")spring <- SpringRK4()[email protected][3] <- 0 # set time to zero, t = 0spring <- setState(spring, theta, thetaDot)spring <- setStepSize(spring, dt = dt) # using stepSize in RK4[email protected] <- setStepSize([email protected], dt) # set new step sizerowvec <- vector("list")i <- 1while ([email protected][3] <= tmax) {rowvec[[i]] <- list(t = [email protected][3], # angley1 = [email protected][1], # derivative of the angley2 = [email protected][2]) # timei <- i + 1spring <- step(spring)}DT <- data.table::rbindlist(rowvec)return(DT)}# show solutionsolution <- SpringRK4App()plot(solution)
# ++++++++++++++++++++++++++++++++++++++++++++++++ application: VanderPolApp.R# Solution of the Van der Pol equation#library(rODE)importFromExamples("VanderPol.R")# run the applicationVanderpolApp <- function(verbose = FALSE) {# set the orbit into a predefined state.y1 <- 2; y2 <- 0; dt <- 0.1;rigid_body <- VanderPol(y1, y2)solver <- RK45(rigid_body)rowVector <- vector("list")i <- 1while ([email protected][3] <= 20) {rowVector[[i]] <- list(t = [email protected][3],y1 = [email protected][1],y2 = [email protected][2])solver <- step(solver)rigid_body <- [email protected]i <- i + 1}DT <- data.table::rbindlist(rowVector)return(DT)}# show solutionsolution <- VanderpolApp()plot(solution)
# +++++++++++++++++++++++++++++++++++++ example: VanderpolMuTimeControlApp.R# This is a modification of the original Vanderpol.R script# In this version, we will add tha ability of setting mu and time lapse.# This example is also shown in the Matlab help guidelibrary(rODE)importFromExamples("VanderpolMuTimeControl.R")# run the applicationVanderpolMuTimeControlApp <- function(verbose = FALSE) {# set the orbit into a predefined state.y1 <- 2; y2 <- 0; mu <- 10; tmax <- mu * 3; dt <- 0.01rigid_body <- VanderPol(y1, y2, mu)solver <- RK45(rigid_body)rowVector <- vector("list")i <- 1while ([email protected][3] <= tmax) {rowVector[[i]] <- list(t = [email protected][3],y1 = [email protected][1],y2 = [email protected][2])solver <- step(solver)rigid_body <- [email protected]i <- i + 1}DT <- data.table::rbindlist(rowVector)return(DT)}# show solutionsolution <- VanderpolMuTimeControlApp()plot(solution)
The following books and papers were consulted during the development of this package:
[1] R. Ashino, M. Nagase and R. Vaillancourt. "Behind and beyond the Matlab ODE suite". In: Computers & Mathematics with Applications 40.4-5 (Aug. 2000), pp. 491-512. DOI: 10.1016/s0898-1221(00)00175-9.
[2] K. Atkinson, W. Han and D. E. Stewart. Numerical Solution of Ordinary Differential Equations. Wiley, 2009. ISBN: 978-0-470-04294-6.
[3] J. R. Dormand and P. J. Prince. "A family of embedded Runge-Kutta formulae". In: Journal of computational and applied mathematics 6.1 (Mar. 1980), pp. 19-26. DOI: 10.1016/0771-050x(80)90013-3.
[4] H. Gould, J. Tobochnik and W. Christian. An Introduction to Computer Simulation Methods: Applications To Physical Systems. CreateSpace Independent Publishing Platform, 2017. ISBN: 978-1974427475.
[5] T. Kimura. "On dormand-prince method". In: Retrieved April 27 (2009), p. 2014. <URL: http://depa.fquim.unam.mx/amyd/archivero/DormandPrince_19856.pdf>.
[6] M. A. Nobles. Using the Computer to Solve Petroleum Engineering Problems. Gulf Publishing Co, 1974. ISBN: 978-0872018860.
[7] T. Ritschel. "Numerical Methods For Solution of Di<U+FB00>erential Equations". Cand. thesis. DTU supervisor: John Bagterp Jørgensen, [email protected], DTU Compute. Technical University of Denmark, Department of Applied Mathematics and Computer Science, 2013, p. 224. <URL: http://www.compute.dtu.dk/English.aspx>.
[8] R. Sincovec. "Numerical Reservoir Simulation Using an Ordinary-Differential-Equations Integrator". In: Society of Petroleum Engineers Journal 15.03 (Jun. 1975), pp. 255-264. DOI: 10.2118/5104-pa.
[9] K. Soetaert, T. Petzoldt and R. W. Setzer. "Solving differential equations in R: package deSolve". In: Journal of Statistical Software 33 (2010).