File: test_trustregion_exact.py

package info (click to toggle)
python-scipy 1.1.0-7
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 93,828 kB
  • sloc: python: 156,854; ansic: 82,925; fortran: 80,777; cpp: 7,505; makefile: 427; sh: 294
file content (357 lines) | stat: -rw-r--r-- 13,189 bytes parent folder | download
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
"""
Unit tests for trust-region iterative subproblem.

To run it in its simplest form::
  nosetests test_optimize.py

"""
from __future__ import division, print_function, absolute_import

import numpy as np
from scipy.optimize._trustregion_exact import (
    estimate_smallest_singular_value,
    singular_leading_submatrix,
    IterativeSubproblem)
from scipy.linalg import (svd, get_lapack_funcs, det,
                          cho_factor, cho_solve, qr,
                          eigvalsh, eig, norm)
from numpy.testing import (assert_, assert_array_equal,
                           assert_equal, assert_array_almost_equal,
                           assert_array_less)


def random_entry(n, min_eig, max_eig, case):

    # Generate random matrix
    rand = np.random.uniform(-1, 1, (n, n))

    # QR decomposition
    Q, _, _ = qr(rand, pivoting='True')

    # Generate random eigenvalues
    eigvalues = np.random.uniform(min_eig, max_eig, n)
    eigvalues = np.sort(eigvalues)[::-1]

    # Generate matrix
    Qaux = np.multiply(eigvalues, Q)
    A = np.dot(Qaux, Q.T)

    # Generate gradient vector accordingly
    # to the case is being tested.
    if case == 'hard':
        g = np.zeros(n)
        g[:-1] = np.random.uniform(-1, 1, n-1)
        g = np.dot(Q, g)
    elif case == 'jac_equal_zero':
        g = np.zeros(n)
    else:
        g = np.random.uniform(-1, 1, n)

    return A, g


class TestEstimateSmallestSingularValue(object):

    def test_for_ill_condiotioned_matrix(self):

        # Ill-conditioned triangular matrix
        C = np.array([[1, 2, 3, 4],
                      [0, 0.05, 60, 7],
                      [0, 0, 0.8, 9],
                      [0, 0, 0, 10]])

        # Get svd decomposition
        U, s, Vt = svd(C)

        # Get smallest singular value and correspondent right singular vector.
        smin_svd = s[-1]
        zmin_svd = Vt[-1, :]

        # Estimate smallest singular value
        smin, zmin = estimate_smallest_singular_value(C)

        # Check the estimation
        assert_array_almost_equal(smin, smin_svd, decimal=8)
        assert_array_almost_equal(abs(zmin), abs(zmin_svd), decimal=8)


class TestSingularLeadingSubmatrix(object):

    def test_for_already_singular_leading_submatrix(self):

        # Define test matrix A.
        # Note that the leading 2x2 submatrix is singular.
        A = np.array([[1, 2, 3],
                      [2, 4, 5],
                      [3, 5, 6]])

        # Get Cholesky from lapack functions
        cholesky, = get_lapack_funcs(('potrf',), (A,))

        # Compute Cholesky Decomposition
        c, k = cholesky(A, lower=False, overwrite_a=False, clean=True)

        delta, v = singular_leading_submatrix(A, c, k)

        A[k-1, k-1] += delta

        # Check if the leading submatrix is singular.
        assert_array_almost_equal(det(A[:k, :k]), 0)

        # Check if `v` fullfil the specified properties
        quadratic_term = np.dot(v, np.dot(A, v))
        assert_array_almost_equal(quadratic_term, 0)

    def test_for_simetric_indefinite_matrix(self):

        # Define test matrix A.
        # Note that the leading 5x5 submatrix is indefinite.
        A = np.asarray([[1, 2, 3, 7, 8],
                        [2, 5, 5, 9, 0],
                        [3, 5, 11, 1, 2],
                        [7, 9, 1, 7, 5],
                        [8, 0, 2, 5, 8]])

        # Get Cholesky from lapack functions
        cholesky, = get_lapack_funcs(('potrf',), (A,))

        # Compute Cholesky Decomposition
        c, k = cholesky(A, lower=False, overwrite_a=False, clean=True)

        delta, v = singular_leading_submatrix(A, c, k)

        A[k-1, k-1] += delta

        # Check if the leading submatrix is singular.
        assert_array_almost_equal(det(A[:k, :k]), 0)

        # Check if `v` fullfil the specified properties
        quadratic_term = np.dot(v, np.dot(A, v))
        assert_array_almost_equal(quadratic_term, 0)

    def test_for_first_element_equal_to_zero(self):

        # Define test matrix A.
        # Note that the leading 2x2 submatrix is singular.
        A = np.array([[0, 3, 11],
                      [3, 12, 5],
                      [11, 5, 6]])

        # Get Cholesky from lapack functions
        cholesky, = get_lapack_funcs(('potrf',), (A,))

        # Compute Cholesky Decomposition
        c, k = cholesky(A, lower=False, overwrite_a=False, clean=True)

        delta, v = singular_leading_submatrix(A, c, k)

        A[k-1, k-1] += delta

        # Check if the leading submatrix is singular
        assert_array_almost_equal(det(A[:k, :k]), 0)

        # Check if `v` fullfil the specified properties
        quadratic_term = np.dot(v, np.dot(A, v))
        assert_array_almost_equal(quadratic_term, 0)


class TestIterativeSubproblem(object):

    def test_for_the_easy_case(self):

        # `H` is chosen such that `g` is not orthogonal to the
        # eigenvector associated with the smallest eigenvalue `s`.
        H = [[10, 2, 3, 4],
             [2, 1, 7, 1],
             [3, 7, 1, 7],
             [4, 1, 7, 2]]
        g = [1, 1, 1, 1]

        # Trust Radius
        trust_radius = 1

        # Solve Subproblem
        subprob = IterativeSubproblem(x=0,
                                      fun=lambda x: 0,
                                      jac=lambda x: np.array(g),
                                      hess=lambda x: np.array(H),
                                      k_easy=1e-10,
                                      k_hard=1e-10)
        p, hits_boundary = subprob.solve(trust_radius)

        assert_array_almost_equal(p, [0.00393332, -0.55260862,
                                      0.67065477, -0.49480341])
        assert_array_almost_equal(hits_boundary, True)

    def test_for_the_hard_case(self):

        # `H` is chosen such that `g` is orthogonal to the
        # eigenvector associated with the smallest eigenvalue `s`.
        H = [[10, 2, 3, 4],
             [2, 1, 7, 1],
             [3, 7, 1, 7],
             [4, 1, 7, 2]]
        g = [6.4852641521327437, 1, 1, 1]
        s = -8.2151519874416614

        # Trust Radius
        trust_radius = 1

        # Solve Subproblem
        subprob = IterativeSubproblem(x=0,
                                      fun=lambda x: 0,
                                      jac=lambda x: np.array(g),
                                      hess=lambda x: np.array(H),
                                      k_easy=1e-10,
                                      k_hard=1e-10)
        p, hits_boundary = subprob.solve(trust_radius)

        assert_array_almost_equal(-s, subprob.lambda_current)

    def test_for_interior_convergence(self):

        H = [[1.812159, 0.82687265, 0.21838879, -0.52487006, 0.25436988],
             [0.82687265, 2.66380283, 0.31508988, -0.40144163, 0.08811588],
             [0.21838879, 0.31508988, 2.38020726, -0.3166346, 0.27363867],
             [-0.52487006, -0.40144163, -0.3166346, 1.61927182, -0.42140166],
             [0.25436988, 0.08811588, 0.27363867, -0.42140166, 1.33243101]]

        g = [0.75798952, 0.01421945, 0.33847612, 0.83725004, -0.47909534]

        # Solve Subproblem
        subprob = IterativeSubproblem(x=0,
                                      fun=lambda x: 0,
                                      jac=lambda x: np.array(g),
                                      hess=lambda x: np.array(H))
        p, hits_boundary = subprob.solve(1.1)

        assert_array_almost_equal(p, [-0.68585435, 0.1222621, -0.22090999,
                                      -0.67005053, 0.31586769])
        assert_array_almost_equal(hits_boundary, False)
        assert_array_almost_equal(subprob.lambda_current, 0)
        assert_array_almost_equal(subprob.niter, 1)

    def test_for_jac_equal_zero(self):

        H = [[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809],
             [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396],
             [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957],
             [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298],
             [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]]

        g = [0, 0, 0, 0, 0]

        # Solve Subproblem
        subprob = IterativeSubproblem(x=0,
                                      fun=lambda x: 0,
                                      jac=lambda x: np.array(g),
                                      hess=lambda x: np.array(H),
                                      k_easy=1e-10,
                                      k_hard=1e-10)
        p, hits_boundary = subprob.solve(1.1)

        assert_array_almost_equal(p, [0.06910534, -0.01432721,
                                      -0.65311947, -0.23815972,
                                      -0.84954934])
        assert_array_almost_equal(hits_boundary, True)

    def test_for_jac_very_close_to_zero(self):

        H = [[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809],
             [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396],
             [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957],
             [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298],
             [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]]

        g = [0, 0, 0, 0, 1e-15]

        # Solve Subproblem
        subprob = IterativeSubproblem(x=0,
                                      fun=lambda x: 0,
                                      jac=lambda x: np.array(g),
                                      hess=lambda x: np.array(H),
                                      k_easy=1e-10,
                                      k_hard=1e-10)
        p, hits_boundary = subprob.solve(1.1)

        assert_array_almost_equal(p, [0.06910534, -0.01432721,
                                      -0.65311947, -0.23815972,
                                      -0.84954934])
        assert_array_almost_equal(hits_boundary, True)

    def test_for_random_entries(self):
        # Seed
        np.random.seed(1)

        # Dimension
        n = 5

        for case in ('easy', 'hard', 'jac_equal_zero'):

            eig_limits = [(-20, -15),
                          (-10, -5),
                          (-10, 0),
                          (-5, 5),
                          (-10, 10),
                          (0, 10),
                          (5, 10),
                          (15, 20)]

            for min_eig, max_eig in eig_limits:
                # Generate random symmetric matrix H with
                # eigenvalues between min_eig and max_eig.
                H, g = random_entry(n, min_eig, max_eig, case)

                # Trust radius
                trust_radius_list = [0.1, 0.3, 0.6, 0.8, 1, 1.2, 3.3, 5.5, 10]

                for trust_radius in trust_radius_list:
                    # Solve subproblem with very high accuracy
                    subprob_ac = IterativeSubproblem(0,
                                                     lambda x: 0,
                                                     lambda x: g,
                                                     lambda x: H,
                                                     k_easy=1e-10,
                                                     k_hard=1e-10)

                    p_ac, hits_boundary_ac = subprob_ac.solve(trust_radius)

                    # Compute objective function value
                    J_ac = 1/2*np.dot(p_ac, np.dot(H, p_ac))+np.dot(g, p_ac)

                    stop_criteria = [(0.1, 2),
                                     (0.5, 1.1),
                                     (0.9, 1.01)]

                    for k_opt, k_trf in stop_criteria:

                        # k_easy and k_hard computed in function
                        # of k_opt and k_trf accordingly to
                        # Conn, A. R., Gould, N. I., & Toint, P. L. (2000).
                        # "Trust region methods". Siam. p. 197.
                        k_easy = min(k_trf-1,
                                     1-np.sqrt(k_opt))
                        k_hard = 1-k_opt

                        # Solve subproblem
                        subprob = IterativeSubproblem(0,
                                                      lambda x: 0,
                                                      lambda x: g,
                                                      lambda x: H,
                                                      k_easy=k_easy,
                                                      k_hard=k_hard)
                        p, hits_boundary = subprob.solve(trust_radius)

                        # Compute objective function value
                        J = 1/2*np.dot(p, np.dot(H, p))+np.dot(g, p)

                        # Check if it respect k_trf
                        if hits_boundary:
                            assert_array_equal(np.abs(norm(p)-trust_radius) <=
                                               (k_trf-1)*trust_radius, True)
                        else:
                            assert_equal(norm(p) <= trust_radius, True)

                        # Check if it respect k_opt
                        assert_equal(J <= k_opt*J_ac, True)