import numpy as np from scipy.optimize import minimize # 系统参数 A = 0.8 B = 0.5 C = 1 D = 0.2 # 参考轨迹函数 def reference_trajectory(t): return np.sin(0.1 * t) # 生成输入数据 def generate_input_data(T): return np.random.uniform(-1, 1, T) # 系统模拟 def simulate_system(u): x = 0 # 初始状态 y = [] for i in range(len(u)): x = A * x + B * u[i] y.append(C * x + D * u[i]) return np.array(y) # DeePC算法实现 def deepc_algorithm(T, Tini, N): # 生成输入数据 ud = generate_input_data(T) # 模拟系统得到输出数据 yd = simulate_system(ud) # 划分数据 Up, Yp, Uf, Yf = partition_data(ud, yd, Tini, N) # 构建优化问题 def objective_function(g): u = Uf @ g y = Yf @ g cost = np.sum((y - reference_trajectory(np.arange(Tini, Tini + N))) ** 2) + 0.1 * np.sum(u ** 2) return cost # 等式约束 def equality_constraint(g): return np.concatenate((Up @ g - ud[:Tini], Yp @ g - yd[:Tini], Uf @ g, Yf @ g)) # 初始猜测 g0 = np.zeros((T - Tini - N + 1, 1)) # 约束条件 constraints = {'type': 'eq', 'fun': equality_constraint} # 求解优化问题 result = minimize(objective_function, g0, constraints=constraints) # 最优输入序列 u_opt = Uf @ result.x return u_opt # 划分数据函数 def partition_data(ud, yd, Tini, N): Up = np.zeros((Tini, T - Tini - N + 1)) Yp = np.zeros((Tini, T - Tini - N + 1)) Uf = np.zeros((N, T - Tini - N + 1)) Yf = np.zeros((N, T - Tini - N + 1)) for i in range(T - Tini - N + 1): Up[:, i] = ud[i:i + Tini] Yp[:, i] = yd[i:i + Tini] Uf[:, i] = ud[i + Tini:i + Tini + N] Yf[:, i] = yd[i + Tini:i + Tini + N] return Up, Yp, Uf, Yf # 测试 T = 100 Tini = 10 N = 5 u_opt = deepc_algorithm(T, Tini, N) print(u_opt)