Figure 8.11:

Gauss-Newton iterations for the direct multiple-shooting method

Figure 8.11

Code for Figure 8.11

Text of the GNU GPL.

dms_gn.py


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# Direct multiple-shooting Gauss-Newton SQP solver using CasADi/qpoases.
#
# Mirrors functions/dms_gn.m. ocp must contain CasADi symbolic expressions:
#     'x'   : casadi.SX/MX state vector
#     'u'   : casadi.SX/MX control vector
#     'ode' : casadi.SX/MX state derivative
#     'lsq' : casadi.SX/MX least-squares residuals
#
# data dict keys: 'T', 'x0', 'xN', 'x_min', 'x_max', 'x_guess',
#                 'u_min', 'u_max', 'u_guess'
# opts dict keys: 'N', 'verbose' (optional)
import numpy as np
import casadi


class DmsGn:
    def __init__(self, ocp, data, opts):
        self.ocp = ocp
        self.data = data
        self.opts = opts
        self.verbose = opts.get('verbose', True)

        # Problem dimensions
        self.N = opts['N']
        self.nx = ocp['x'].numel()
        self.nu = ocp['u'].numel()

        # Time grid
        self.t = np.linspace(0, data['T'], self.N + 1)

        # Interval length
        self.dt = data['T'] / self.N

        # Containers populated by rk4/transcribe/init_gauss_newton
        self.fun = {}
        self.nlp = {}
        self.sol = {}

        # Discrete-time dynamics (RK4) and the least-squares residual function
        self._rk4()

        # Transcribe to NLP
        self._transcribe()

        # Initialise decision variable and trajectories
        self.sol['w'] = self.nlp['w0']
        x_traj, u_traj = self.fun['traj'](self.sol['w'])
        self.sol['x'] = np.array(x_traj)
        self.sol['u'] = np.array(u_traj)

        # Build Gauss-Newton QP solver
        self._init_gauss_newton()

    def _rk4(self):
        x = self.ocp['x']
        u = self.ocp['u']
        ode = self.ocp['ode']
        f = casadi.Function('f', [x, u], [ode], ['x', 'p'], ['ode'])

        k1 = f(x, u)
        k2 = f(x + 0.5 * self.dt * k1, u)
        k3 = f(x + 0.5 * self.dt * k2, u)
        k4 = f(x + self.dt * k3, u)
        xk = x + self.dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4)

        self.fun['F'] = casadi.Function('RK4', [x, u], [xk],
                                        ['x0', 'p'], ['xf'])

        lsq = self.ocp['lsq']
        self.fun['Lsq'] = casadi.Function('Lsq', [x, u], [lsq],
                                          ['x', 'p'], ['lsq'])

    def _transcribe(self):
        w = []
        g = []
        M = []
        lbw = []
        ubw = []
        w0 = []

        x_plot = []
        u_plot = []

        xk = casadi.MX.sym('x0', self.nx)
        w.append(xk)
        lbw.append(self.data['x0'])
        ubw.append(self.data['x0'])
        w0.append(self.data['x_guess'])
        x_plot.append(xk)

        for k in range(self.N):
            uk = casadi.MX.sym('u{}'.format(k), self.nu)
            w.append(uk)
            lbw.append(self.data['u_min'])
            ubw.append(self.data['u_max'])
            w0.append(self.data['u_guess'])
            u_plot.append(uk)

            Fk = self.fun['F'](x0=xk, p=uk)
            x_next = Fk['xf']

            M.append(self.fun['Lsq'](xk, uk))

            xk = casadi.MX.sym('x{}'.format(k + 1), self.nx)
            w.append(xk)
            if k == self.N - 1:
                lbw.append(self.data['xN'])
                ubw.append(self.data['xN'])
            else:
                lbw.append(self.data['x_min'])
                ubw.append(self.data['x_max'])
            w0.append(self.data['x_guess'])
            x_plot.append(xk)

            g.append(xk - x_next)

        self.nlp['w'] = casadi.vertcat(*w)
        self.nlp['g'] = casadi.vertcat(*g)
        self.nlp['M'] = casadi.vertcat(*M)
        self.nlp['lbw'] = casadi.vertcat(*lbw)
        self.nlp['ubw'] = casadi.vertcat(*ubw)
        self.nlp['w0'] = casadi.vertcat(*w0)

        self.fun['traj'] = casadi.Function(
            'traj', [self.nlp['w']],
            [casadi.horzcat(*x_plot), casadi.horzcat(*u_plot)],
            ['w'], ['x', 'u'])

    def _init_gauss_newton(self):
        self.nlp['J'] = casadi.jacobian(self.nlp['g'], self.nlp['w'])
        self.nlp['JM'] = casadi.jacobian(self.nlp['M'], self.nlp['w'])

        self.nlp['H'] = self.nlp['JM'].T @ self.nlp['JM']
        self.nlp['c'] = self.nlp['JM'].T @ self.nlp['M']

        self.fun['g'] = casadi.Function('g', [self.nlp['w']], [self.nlp['g']],
                                        ['w'], ['g'])
        self.fun['J'] = casadi.Function('J', [self.nlp['w']], [self.nlp['J']],
                                        ['w'], ['J'])
        self.fun['H'] = casadi.Function('H', [self.nlp['w']],
                                        [self.nlp['H'], self.nlp['c']],
                                        ['w'], ['H', 'c'])

        qp = dict(h=self.nlp['H'].sparsity(), a=self.nlp['J'].sparsity())
        qp_options = dict()
        if not self.verbose:
            qp_options['printLevel'] = 'none'
        self.fun['qp_solver'] = casadi.conic('qp_solver', 'qpoases', qp,
                                             qp_options)

        self.n_iter = 0
        self.sol['norm_dw'] = np.inf

    def sqpstep(self):
        self.n_iter += 1

        w = self.sol['w']
        self.sol['g'] = self.fun['g'](w)
        self.sol['J'] = self.fun['J'](w)
        H_, c_ = self.fun['H'](w)
        self.sol['H'] = H_
        self.sol['c'] = c_

        qp_solution = self.fun['qp_solver'](
            a=self.sol['J'], h=self.sol['H'], g=self.sol['c'],
            lbx=self.nlp['lbw'] - w, ubx=self.nlp['ubw'] - w,
            lba=-self.sol['g'], uba=-self.sol['g'], x0=0)
        dw = np.array(qp_solution['x']).flatten()

        self.sol['norm_dw'] = float(np.linalg.norm(dw))
        self.sol['w'] = w + dw

        x_traj, u_traj = self.fun['traj'](self.sol['w'])
        self.sol['x'] = np.array(x_traj)
        self.sol['u'] = np.array(u_traj)

        if self.verbose or self.n_iter % 10 == 1:
            print('-' * 70)
            print('{:>15s} {:>15s}'.format('SQP iteration', 'norm(dw)'))
        print('{:15d} {:15g}'.format(self.n_iter, self.sol['norm_dw']))

main.py


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# [makes] vdp_gauss_newton.mat
# [depends] functions/dms_gn.py
# Solves the minimization problem with T=10
#  minimize       1/2*integral{t=0 until t=T}(x1^2 + x2^2 + u^2) dt
#  subject to     dot(x1) = (1-x2^2)*x1 - x2 + u,   x1(0)=0, x1(T)=0
#                 dot(x2) = x1,                     x2(0)=1, x2(T)=0
#                 x1(t) >= -0.25, 0<=t<=T
# Joel Andersson, UW Madison 2017
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), 'functions'))

import numpy as np
import casadi
from scipy.io import savemat
from dms_gn import DmsGn

# States and control
x1 = casadi.SX.sym('x1')
x2 = casadi.SX.sym('x2')
u = casadi.SX.sym('u')

# Model equations
x1_dot = (1 - x2**2) * x1 - x2 + u
x2_dot = x1

# Least squares objective terms
lsq = casadi.vertcat(x1, x2, u)

# Problem structure
ocp = dict(x=casadi.vertcat(x1, x2), u=u,
           ode=casadi.vertcat(x1_dot, x2_dot), lsq=lsq)

# Problem data
data = dict(T=10.0,
            x0=np.array([0.0, 1.0]),
            xN=np.array([0.0, 0.0]),
            x_min=np.array([-0.25, -np.inf]),
            x_max=np.array([np.inf, np.inf]),
            x_guess=np.array([0.0, 0.0]),
            u_min=-1.0, u_max=1.0, u_guess=0.0)

# Solver options
opts = dict(N=20, verbose=False)

# Create an OCP solver instance
s = DmsGn(ocp, data, opts)

# Track u iterates across SQP iterations
u_all = s.sol['u'][0, :].reshape(1, -1)

while s.sol['norm_dw'] > 1e-8:
    s.sqpstep()
    u_all = np.vstack((u_all, s.sol['u'][0, :].reshape(1, -1)))

tgrid = s.t
savemat('vdp_gauss_newton.mat', {'tgrid': tgrid, 'u_all': u_all})