""" Real-Time CBF-QP Safety Filter Minimizes deviation from nominal control while enforcing the certified barrier condition: min_{u, delta >= 0} 0.5 * ||u - u_nom||^2 + beta * delta^2 subject to: L_f h(x) + L_g h(x)*u + alpha(h(x) - gamma) >= -delta """ from typing import Tuple, Optional, Dict import time import numpy as np import cvxpy as cp class CBFQPSafetyFilter: """ Convex Quadratic Programming (QP) Safety Filter for Control-Affine Systems. Operates at 100+ Hz with warm-starting and slack variable relaxation. """ def __init__( self, control_dim: int, u_min: np.ndarray, u_max: np.ndarray, alpha_cbf: float = 1.0, slack_penalty: float = 1e4, solver: str = "OSQP", ): self.m = control_dim self.u_min = np.asarray(u_min, dtype=np.float64) self.u_max = np.asarray(u_max, dtype=np.float64) self.alpha_cbf = alpha_cbf self.beta = slack_penalty self.solver = solver # Pre-allocate CVXPY parameters for real-time reuse self._u = cp.Variable(self.m) self._delta = cp.Variable(1, nonneg=True) self._u_nom_param = cp.Parameter(self.m) self._Lg_param = cp.Parameter((1, self.m)) self._rhs_param = cp.Parameter(1) # Objective: minimize ||u - u_nom||^2 + beta * delta^2 cost = 0.5 * cp.sum_squares(self._u - self._u_nom_param) + self.beta * cp.square(self._delta) # Constraints: # Lg_h * u + delta >= -Lf_h - alpha*(h - gamma) # u_min <= u <= u_max constraints = [ self._Lg_param @ self._u + self._delta >= self._rhs_param, self._u >= self.u_min, self._u <= self.u_max, ] self.problem = cp.Problem(cp.Minimize(cost), constraints) def filter( self, u_nominal: np.ndarray, h_val: float, Lf_h: float, Lg_h: np.ndarray, gamma: float = 0.0, ) -> Tuple[np.ndarray, Dict[str, float]]: """ Filters nominal control input u_nominal using the CBF-QP inequality. Args: u_nominal: Nominal control input vector in R^m h_val: Current barrier function value h(x) Lf_h: Lie derivative along f in R Lg_h: Lie derivative along g in R^m gamma: Conformal risk margin (tightening parameter) Returns: u_safe: Filtered safe control input in R^m info: Telemetry dict (solve_time, slack, status) """ t0 = time.perf_counter() # Update problem parameters self._u_nom_param.value = np.asarray(u_nominal, dtype=np.float64) self._Lg_param.value = np.asarray(Lg_h, dtype=np.float64).reshape(1, self.m) # RHS = - Lf_h - alpha * (h - gamma) effective_barrier = h_val - gamma rhs_val = -Lf_h - self.alpha_cbf * effective_barrier self._rhs_param.value = np.array([rhs_val], dtype=np.float64) try: self.problem.solve(solver=cp.OSQP, warm_start=True, verbose=False) solve_time = (time.perf_counter() - t0) * 1000.0 # ms if self.problem.status in [cp.OPTIMAL, cp.OPTIMAL_INACCURATE]: u_safe = np.array(self._u.value, dtype=np.float32) slack_val = float(self._delta.value[0]) status = "optimal" else: # Fallback to clamped nominal if solver fails u_safe = np.clip(u_nominal, self.u_min, self.u_max) slack_val = -1.0 status = self.problem.status except Exception as e: solve_time = (time.perf_counter() - t0) * 1000.0 u_safe = np.clip(u_nominal, self.u_min, self.u_max) slack_val = -1.0 status = f"error: {str(e)}" info = { "solve_time_ms": solve_time, "slack": slack_val, "effective_barrier": effective_barrier, "status": status, } return u_safe, info