1.MPC-CBF.py
1.1 MPC类–实现代码1
import do_mpc
from casadi import *
import config
class MPC:
"""MPC-CBF Optimization problem:
min Σ_{k=0}{N-1} 1/2*x'_k^T*Q*x'_k + 1/2*u_k^T*R*u_k over u
s.t.
x_{k+1} = x_k + B*u_k*T_s
x_min <= x_k <= x_max
u_min <= u_k <= u_max
x_0 = x(0)
Δh(x_k, u_k) >= -γ*h(x_k)
where x'_k = x_{des_k} - x_k
"""
def __init__(self):
self.sim_time = config.sim_time # Total simulation time steps
self.Ts = config.Ts # Sampling time
self.T_horizon = config.T_horizon # Prediction horizon
self.x0 = config.x0 # Initial pose
self.v_limit = config.v_limit # Linear velocity limit
self.omega_limit = config.omega_limit # Angular velocity limit
self.R = config.R # Controls cost matrix
self.Q = config.Q # State cost matrix
self.static_obstacles_on = config.static_obstacles_on # Whether to have static obstacles
self.moving_obstacles_on = config.moving_obstacles_on # Whether to have moving obstacles
if self.static_obstacles_on:
self.obs = config.obs # Static Obstacles
if self.moving_obstacles_on: # Moving obstacles
self.moving_obs = config.moving_obs
self.r = config.r # Robot radius
self.control_type = config.control_type # "setpoint" or "traj_tracking"
if self.control_type == "setpoint": # Go-to-goal
self.goal = config.goal # Robot's goal pose
self.gamma = config.gamma # CBF parameter
self.safety_dist = config.safety_dist # Safety distance
self.controller = config.controller # Type of control
self.model = self.define_model()
self.mpc = self.define_mpc()
self.simulator = self.define_simulator()
self.estimator = do_mpc.estimator.StateFeedback(self.model)
self.set_init_state()
def define_model(self):
"""Configures the dynamical model of the system (and part of the objective function).
x_{k+1} = x_k + B*u_k*T_s
Returns:
- model(do_mpc.model.Model): The system model
"""
model_type = 'discrete'
model = do_mpc.model.Model(model_type)
# States
n_states = 3
_x = model.set_variable(var_type='_x', var_name='x', shape=(n_states, 1))
# Inputs
n_controls = 2
_u = model.set_variable(var_type='_u', var_name='u', shape=(n_controls, 1))
# State Space matrices
B = self.get_sys_matrix_B(_x)
# Set right-hand-side of ODE for all introduced states (_x).
x_next = _x + B@_u*self.Ts
model.set_rhs('x', x_next, process_noise=False) # Set to True if adding noise
# Optional: Define an expression, which represents the stage and terminal
# cost of the control problem. This term will be later used as the cost in
# the MPC formulation and can be used to directly plot the trajectory of
# the cost of each state.
model, cost_expr = self.get_cost_expression(model)
model.set_expression(expr_name='cost', expr=cost_expr)
# Moving obstacle (define time-varying parameter for its position)
if self.moving_obstacles_on is True:
for i in range(len(self.moving_obs)):
model.set_variable('_tvp', 'x_moving_obs'+str(i))
model.set_variable('_tvp', 'y_moving_obs'+str(i))
# Setup model
model.setup()
return model
这段代码定义了一个名为 MPC