A small DAE model¶
This example will cover the basic setup to setup a new model in SUND. It will:
- Install and import the model
- Build the model and simulation objects
- Simulate using the simulation object
The model file¶
The code uses this model file, saved as minimal_dae.txt
.
The model file
########## NAME
minimal_dae
########## METADATA
time_unit = s
########## MACROS
########## STATES
d/dt(A) = 1 + k1 - r1
0 = r1 - B
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
It can also be downloaded from from here.
Full python code to run the example¶
The full code to run the example is shown below, but it can also be downloaded from here.
Requirements¶
The code requires that the following packages are installed
uv add numpy matplotlib
pip install numpy matplotlib
Example code¶
#%% Import packages
import matplotlib.pyplot as plt
import numpy as np
import sund
#%% Install the model by using the SUND function 'install_model'
MODEL_NAME = "minimal_dae"
sund.install_model(f"{MODEL_NAME}.txt")
#%% Import the model by using the SUND function 'load_model'
model = sund.load_model(f"{MODEL_NAME}")
#%% A simulation object can be constructed from the model template
sim = sund.Simulation(models = model, time_unit = model.time_unit)
#%% DAE settings
# We set the option for the solver to calculate consistent initial conditions for the algebraic states
# and differential derivatives by using the given initial conditions for the differential states.
# The option is called 'calc_ic', and the default value is false.
options = sim.get_options()
print(f'Option calc_ic before change: {options['calc_ic']}')
options['calc_ic'] = True
print(f'Option calc_ic after change: {options['calc_ic']}')
sim.set_options(options)
#%% Now we can simulate the model using the simulation object
sim.simulate(time_vector = np.linspace(0, 10, 100))
plt.figure()
feature_index = sim.feature_names.index('yA')
plt.plot(sim.time_vector, sim.feature_data[:, feature_index])
plt.xlabel(sim.time_unit)
plt.ylabel('A.U.')
plt.title("Simulation result")
plt.show()