Custom Components

Add New Models

We define system models in the cpsim.models subpackage. Here are steps to add a new model:

  1. Define system dynamics (state-space model for linear systems, ODE for nonlinear systems).

def system_name(t, x, u):
    # ODE here
    return dx   # dx is the derivative of x, shape (n,)
  1. Define a controller for the system, and we can use built-in controllers.

class Controller:
    def __init__(self, dt):
        self.dt = dt
        # init controller here
    def update(self, ref: np.ndarray, feedback_value: np.ndarray, current_time) -> np.ndarray:
        # calculate one step of control input here
        return u   # shape: (m,)
    def set_control_limit(self, control_lo, control_up):
        # set control limits here, the maximum range of control input
    def clear(self):
        # reset controller here if needed
  1. Define the simulation class integrating the dynamics and controller

class SystemName(Simulator):
    def __init__(self, name, dt, max_index, noise=None):
        super().__init__('SystemName ' + name, dt, max_index)
        self.nonlinear(ode=system_name, n=2, m=1, p=2)  # num of states,control inputs,outputs
        controller = Controller(dt)
        settings = {
            'init_state': x_0,  # initial state
            'feedback_type': 'state',  # 'state'or'output', you must define C if 'output'
            'controller': controller
        if noise:
            settings['noise'] = noise  # noise settings

For complete examples, please refer to the source code of the built-in system models.

Add New Controllers

We can define a new controller by inheriting the Controller class.

 1from abc import ABC, abstractmethod
 4class Controller(ABC):
 5    @abstractmethod
 6    def update(self, feedback_value, current_time=None):
 7        pass
 9    @abstractmethod
10    def set_control_limit(self, control_lo, control_up):
11        pass
13    @abstractmethod
14    def set_reference(self, ref):
15        pass
17    def clear(self):
18        pass

Please refer to the source code of the built-in controllers, such as LQR controller, for more details.