Skip to content

A small ODE model

This example will cover the basic setup to setup a new model in SUND. It will:

  1. Install and import the model
  2. Build the model and simulation objects
  3. Simulate using the simulation object

The model file

In this example, we used this model, saved as minimal_ode.txt:

Model file

########## NAME
minimal_ode
########## METADATA
time_unit = m
########## MACROS
########## STATES
d/dt(A) = 1 + k1 - r1
d/dt(B) = r1

A(0) = 1.0
B(0) = 0.0

########## PARAMETERS
k1 = 0.5
k2 = 1.0

########## VARIABLES
r1 = k2*A

########## FUNCTIONS
########## EVENTS
########## OUTPUTS
########## INPUTS
########## FEATURES
yA = A
yB = B
A downloadable copy of the model is available here (right-click and save).

Full python code to run the example

The full code to run the example is shown below, but it can also be downloaded here.

Needed packages

The code in the example requires that the following packages are installed (in addition to SUND)

uv add numpy matplotlib
pip install numpy matplotlib

Example code

#%% Import packages
import matplotlib.pyplot as plt
import numpy

import sund

#%% Define the model name
MODEL_NAME = "minimal_ode"

#%% Install the model by using the SUND function 'install_model'
sund.install_model(f"{MODEL_NAME}.txt")

#%% Import the model object by using the SUND function 'load_model'
model = sund.load_model(f"{MODEL_NAME}")

#%% The built in model objects functions can now be used
model.state_values = [2, 2]
print(model.state_values)
model.reset_states()
print(model.state_values)

#%% A simulation object can be constructed from the model template 
sim1 = sund.Simulation(models = model, time_unit = model.time_unit)
print(sim1.state_values)

# Note that the simulation object will be crated from the current instance of the model object
model.state_values = [2, 2]
sim2 = sund.Simulation(models = model, time_unit = model.time_unit)
print(sim2.state_values)

#%% Now we can simulate the model using the simulation object
sim1.simulate(time_vector = numpy.linspace(0, 10, 100))

fig = plt.figure()
feature_index = sim1.feature_names.index('yA')
plt.plot(sim1.time_vector, sim1.feature_data[:, feature_index])
plt.xlabel(sim1.time_unit)
plt.ylabel('A.U.')
plt.title("Simulation result")

#%% Simulating the object again will start the simulation from the last result
sim1.simulate(time_vector = numpy.linspace(0, 10, 100))

fig = plt.figure()
feature_index = sim1.feature_names.index('yA')
plt.plot(sim1.time_vector, sim1.feature_data[:, feature_index])
plt.xlabel(sim1.time_unit)
plt.ylabel('A.U.')
plt.title("Simulation result")

#%% to recreate the original results we need to reset the simulation object
sim1.reset_states()
sim1.simulate(time_vector = numpy.linspace(0, 10, 100))

fig = plt.figure()
feature_index = sim1.feature_names.index('yA')
plt.plot(sim1.time_vector, sim1.feature_data[:, feature_index])
plt.xlabel(sim1.time_unit)
plt.ylabel('A.U.')
plt.title("Simulation result") 

plt.show()