R TUTORIAL for the Second Cource, part 2.3: Lorenz equations

Lorenz equations in R

The Lorenz equations (Lorenz, 1963) were the first chaotic dynamic system to be described. They consist of three differential equations that were assumed to represent idealized behavior of the earth’s atmosphere. We use this model to demonstrate how to implement and solve differential equations in R. The Lorenz model describes the dynamics of three state variables, x, y, and z. The model equations are:

\begin{align*} \frac{{\text d} x}{{\text d} t} &= a\,x + y\,z , \\ \frac{{\text d} y}{{\text d} t} &= b \left( z-y \right) , \\ \frac{{\text d} z}{{\text d} t} &= c\,y - x\,y - z, \end{align*}
subject to the initial conditions
\[ x(0) = y(0) = 0 , \qquad z(0) = 1 . \]
There are three positive parameters a, b, and c, with values originally choisen by Lorenz to be 8/3, 10, and 28, respectively.

Upon using plotting, you might get this error - "Error in plot.new() : figure margins too large". To avoid such errors you can first check par("mar") output:

  par("mar") 
If your output is not uniform, you need to rescale it by entering:
par(mar=c(1,1,1,1)) 
This should rectify the error.
install.packages(“deSolve”)
parameters <- c(a = -8/3, b = -10, c =  28)
state <- c(X = 1, Y = 1, Z = 1)  # initial values
Lorenz<-function(t, state, parameters) {
+   with(as.list(c(state, parameters)),{     # rate of change 
+     dX <- a*X + Y*Z
+     dY <- b * (Y-Z)
+     dZ <- -X*Y + c*Y - Z++     # return the rate of change
+     list(c(dX, dY, dZ))
+   })   # end with(as.list ...
}
# Model application
times <- seq(0, 100, by = 0.01)
library(deSolve)
out <- ode(y = state, times = times, func = Lorenz, parms = parameters)
head(out)
# plotting results
par(oma = c(0, 0, 3, 0))
plot(out, xlab = "time", ylab = "-")
plot(out[, "X"], out[, "Z"], pch = ".")
mtext(outer = TRUE, side = 3, "Lorenz model", cex = 1.5)
Another model:
b<-matrix(c(2,2,2,4,4,4,6,6,6),nrow=3,ncol=3,byrow=TRUE)
b
     [,1] [,2] [,3]
[1,]    2    2    2
[2,]    4    4    4
[3,]    6    6    6

 

  1. https://cran.r-project.org/web/packages/deSolve/vignettes/deSolve.pdf
  2. Soeraert, K., Cash, J., Mazzia, F., Solving differential equations in R, Springer, 2012.
  3. https://www.lehigh.edu/~wes1/R_PDE/R-Matlab_compare.pdf