Euler Integration and the Lotka Volterra Equations. A notebook from my complexity notebooks, written in Python with NumPy and Matplotlib.

#Import all the libraries used throughout the notebook
import pandas as pd
import numpy as np 
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.font_manager
from pylab import *
%matplotlib inline
# Example using the difference equation approximation of the differential equation dx/dt = -x and dx/dt = x

# set up some basic equations
def basic_negative_func(x):
    return -x #models a 

def basic_positive_func(x):
    return x

# plot the euler approximation
def plot_euler(f,y,tau,steps):
    euler_values = []
    for n in range(steps):   
        euler_values.append(y) #append current value of y
        y = y + (1/tau)*f(y) #update the value of y 
    plt.plot(euler_values,'b.-')
    plt.show()
    
    
plot_euler(basic_negative_func,1,100,200)
plot_euler(basic_positive_func,1,100,200)
Output 1 of the euler integration and the lotka volterra equations notebook
Output 2 of the euler integration and the lotka volterra equations notebook
# Example of Euler integration for Lotka-Volterra Equations

def lotka_volterra(a, b, g, d, dt, time):
    #set initial conditions
    t = 0 #time
    x = 0.5 #prey
    y = 0.5 #predator
    
    t_list = [] #list to collect the timesteps
    x_list = [] #list to collect the prey population values
    y_list = [] #list to collect the predator population values
    
    for step in range(round(time/dt)):
        #add values
        t_list.append(t)
        x_list.append(x)
        y_list.append(y)        
        
        #update values
        t += dt
        x = x + (a*x - b*x*y)*dt
        y = y + (d*x*y - g*y)*dt
    
    return t_list, x_list, y_list

def line_plot(t_list, x_list, y_list):
    plt.plot(t_list,x_list,'b',t_list,y_list,'g') #plot the populations next to each other
    plt.show()
    
t0, x0, y0 = lotka_volterra(0.5, 0.5, 0.4, 0.2, 0.0001, 100)
t1, x1, y1 = lotka_volterra(0.3, 0.7, 0.3, 0.3, 0.0001, 100)
t2, x2, y2 = lotka_volterra(0.3, 0.2, 0.1, 0.1, 0.0001, 100)

line_plot(t0, x0, y0)
line_plot(t1, x1, y1)
line_plot(t2, x2, y2)
Output 3 of the euler integration and the lotka volterra equations notebook
Output 4 of the euler integration and the lotka volterra equations notebook
Output 5 of the euler integration and the lotka volterra equations notebook
def oscillation_plot(x0,y0,x1,y1,x2,y2):
    plt.plot(x0, y0,'b', x1, y1, 'g',x2 ,y2 , 'r') #plot the populations relationship over time
    plt.xlabel('prey')
    plt.ylabel('predator')
    plt.show()
    
oscillation_plot(x0, y0, x1, y1, x2, y2)
Output 6 of the euler integration and the lotka volterra equations notebook