A simulation class in Python

This subsection shows how a simulation of the system behavior can be easily done. Any created MPC object contains an instance of the simulation class MPCSim, which by default is called sim.

One step simulation

The most basic method simply computes the succesor state, i.e. the state at the next sampling time for a given input.

MPCSim.predict_next_state(xk, uk)

Compute the succesor state xk1 = A*xk + B*uk

Parameters:
  • xk (numpy array) – the current system state. It must be of size states.
  • uk (numpy array) – the input to apply to the system. It must be of size inputs.
Returns:

the succesor state.

Return type:

numpy array of size states.

For example, assuming the mpc object exist and x represents the current system state, we can do:

uk = mpc.ctl.u_opt[:mpc.size.inputs, 0]  # use only the first input
xk1 = mpc.sim.predict_next_state(xk, uk)

Multi-step simulation

An additional method considers regulation to a fixed reference.

MPCSim.regulate_ref(steps, x_ini)

Simulate MPC regulation to a reference point for a number of steps.

Parameters:
  • steps (int) – number of discret steps to simulate. The period of each step is the discretization time dt.
  • x_ini (numpy array) – initial state where the simulation starts. It must be of size states.

Starting at a point x_ini, this function will apply to the discrete time system (sys.Ad, sys.Bd) the first input vector of the control sequence ctl.u_opt at each time instant for the given number of steps. The goal of the controller is to stabilize the system at the point specified by ctl.x_ref and ctl.u_ref. The simulation results are stored in the structure sim.data.

For example, assuming mpc is a valid MPC object, and mpc.ctl has been already configured, we can simulate the regulation to the origin starting at all states 1 (one) for T=10 steps, i.e. from time t_i=0, to t_f=(T-1)*dt:

import numpy as np
T = 10
mpc.ctl.x_ref = np.zeros(mpc.size.hor_states)
mpc.ctl.u_ref = np.zeros(mpc.size.hor_inputs)
mpc.sim.regulate_ref(T, np.ones(mpc.size.states))
mpc.sim.data.x  # contains the state evolution
mpc.sim.data.u0  # contains the applied inputs

After each run of regulate_ref, the member sim.data will contain the simulation data. It is an instance of the following class:

class muaompc._ltidt.simula._DataPlot(mpc, steps)

This class contains the simulation data after running regulate_ref.

The available members are described below:

J = None

The value of the cost function at each sampling time.

t = None

The discrete time vector, i.e. the sampling times.

u = None

The input sequence computed by the MPC controller at each sampling time.

u0 = None

The input vector applied to the system at each sampling time.

x = None

The system state vector at each sampling time.

Example

An example that plots the simulation results using matplotlib is available under examples/ltidt/sim_matplotlib.