1+ using Test
2+ using AlgebraicControl. CMPC
3+ using AlgebraicControl. ParaConvCat
4+ using Convex
5+ using SCS
6+
7+ A = [0 1 ; .01 0 ]
8+ B = [0 ; 1 ]
9+ Q = 5 * [1.0 0 ; 0 1.0 ]
10+ R = 3.0
11+ x₀ = [3 , 1 ]
12+ N = 10
13+ dim_x = 2
14+ dim_u = 1
15+ ϵ = 0.0001
16+
17+ cost (uₖ,xₖ) = quadform (xₖ,Q) + R* square (uₖ)
18+ dynamics (uₖ,xₖ) = A* xₖ + B* uₖ
19+ set_constraints (uₖ,xₖ) = [
20+ uₖ <= 1 , uₖ >= - 1 ,
21+ xₖ[1 ] <= 3 , xₖ[1 ] >= - 3 ,
22+ xₖ[2 ] <= 2 , xₖ[2 ] >= - 2
23+ ]
24+
25+ one_step = one_step_bifunction (dim_x,dim_u,cost, set_constraints, dynamics)
26+ MPC_bifunc = MPC_bifunction (one_step, N)
27+
28+ us = [Variable (1 ) for i in 1 : N- 1 ]
29+ x_N = Variable (2 )
30+
31+ MPC_prob = to_cvx (MPC_bifunc, us, x₀, x_N)
32+
33+ solve! (MPC_prob, SCS. Optimizer; silent_solver= true )
34+
35+ us_sol = evaluate .(us)
36+
37+ function simulate (A, B, x₀, us, N)
38+ x = x₀
39+ for i in 1 : N
40+ x = A* x + B* us[i]
41+ end
42+ return x
43+ end
44+
45+ # Test that simulate comes close to x_N
46+ res = simulate (A, B, x₀, us_sol, N- 1 )
47+ @test norm (res - evaluate (x_N)) < ϵ
48+
49+ # ## Compare to hand written implementation
50+ xs = Variable (2 , N)
51+ us = Variable (1 , N- 1 )
52+
53+ constraints = Constraint[
54+ xs[:, i+ 1 ] == A* xs[:,i] + B* us[:,i] for i in 1 : N- 1
55+ ]
56+
57+ for i in 1 : N- 1
58+ push! (constraints, xs[:,i][1 ] <= 3 )
59+ push! (constraints, xs[:,i][1 ] >= - 3 )
60+ push! (constraints, xs[:,i][2 ] <= 2 )
61+ push! (constraints, xs[:,i][2 ] >= - 2 )
62+ push! (constraints, us[:,i] <= 1 )
63+ push! (constraints, us[:,i] >= - 1 )
64+ end
65+
66+ push! (constraints, xs[:,1 ] == x₀)
67+
68+ objective = sum ([quadform (xs[:,i], Q) + R* square (us[:,i]) for i in 1 : N- 1 ])
69+
70+ prob = minimize (objective, constraints)
71+
72+ solve! (prob, SCS. Optimizer; silent_solver= true )
73+
74+ true_us_sol = evaluate .(us)
75+
76+ # Test that hand written implementation gets same solution
77+ # as automated implementation.
78+ @test norm (true_us_sol - us_sol) < ϵ
0 commit comments