Search code examples
pythoncontrol-theorycarla

Designing an MPC controller in Python


I am trying to design an MPC controller in Python but I really don't know where to start. I watched videos on YouTube but I was confused even more. Basically, this is for a simulated autonomous vehicle. I've finished the PID controller for it but I didn't run it on the simulator yet:

    def PID(self, Kp, Ki, Kd, reference_velocity, vehicle_velocity, current_time, last_update_time):

        errors = []

        Kp = 0
        Ki = 0
        Kd = 0

        error = reference_velocity - vehicle_velocity
        delta_time = current_time - last_update_time
        last_error = errors[-1]

        proportional = Kp * error
        integral = Ki * error
        derivative = Kd * ((error - last_error) / (delta_time))

        errors.append(error)

        return proportional + integral + derivative

But I don't know how to start with MPC. In my init function, I have the following values:

 def __init__(self, waypoints):
        self.vars                = cutils.CUtils()
        self._current_x          = 0
        self._current_y          = 0
        self._current_yaw        = 0
        self._current_speed      = 0
        self._desired_speed      = 0
        self._current_frame      = 0
        self._current_timestamp  = 0
        self._start_control_loop = False
        self._set_throttle       = 0
        self._set_brake          = 0
        self._set_steer          = 0
        self._waypoints          = waypoints
        self._conv_rad_to_steer  = 180.0 / 70.0 / np.pi
        self._pi                 = np.pi
        self._2pi                = 2.0 * np.pi

I also have the following function definitions. I'll omit the bodies of the functions. I know that I have to use these in the MPC but that's what I need guidance on.

def update_values(self, x, y, yaw, speed, timestamp, frame):
def update_desired_speed(self):
def update_waypoints(self, new_waypoints):
def get_commands(self):
def set_throttle(self, input_throttle):
def set_steer(self, input_steer_in_rad):
def set_brake(self, input_brake):
def update_controls(self):

Solution

  • MPC is an optimization- and model-based control algorithm that is entirely different from a PID controller. A model predictive controller solves optimization problems where a user-defined cost function is minimized subject to the model dynamics (which you need to know/derive) given as an ordinary differential equation. This optimization can further be subject to additional constraints (such as input constraints, state constraints, integral constraints, ...). Since this approach is a very sophisticated control scheme and therefore quite non-trivial to implement, you should ask yourself if the capabilities of an MPC are needed for your application or if a PID control is sufficient.