Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step40/zero/12.input_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/20.attention.dense.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step40/zero/20.attention.dense.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step40/zero/20.attention.dense.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/5.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_bracket.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_constraints.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentiate.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_minpack_py.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_nonlin.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_qap.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_remove_redundancy.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_root_scalar.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_shgo.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_spectral.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_krylov.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_ncg.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/cobyla.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/linesearch.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/minpack.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/nonlin.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/optimize.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/slsqp.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/tnc.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__numdiff.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_chandrupatla.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cython_optimize.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_differentiable_functions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_isotonic_regression.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linear_assignment.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lsq_common.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_minimize_constrained.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/test__dual_annealing.py +379 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py +310 -0
- venv/lib/python3.10/site-packages/scipy/optimize/tests/test__numdiff.py +815 -0
ckpts/universal/global_step40/zero/12.input_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8523dc545e41fb0b6435f525322994f037664ec33efa489269a66de79422e5c4
|
3 |
+
size 9293
|
ckpts/universal/global_step40/zero/20.attention.dense.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:614aa7f29fa06123715521ffaa2f43b6826e36acf19d40084407078c7829ac07
|
3 |
+
size 16778396
|
ckpts/universal/global_step40/zero/20.attention.dense.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:658c7a26f3763b13aecbef97dd2036f89fd50678f5de2a2dbab2fae752216530
|
3 |
+
size 16778411
|
ckpts/universal/global_step40/zero/20.attention.dense.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:5f4c31ad044e554f78ebbff7c1d7485ddab94dcd2f67e220d2c88116c0566e64
|
3 |
+
size 16778317
|
ckpts/universal/global_step40/zero/5.mlp.dense_4h_to_h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:df575a3954914370f0a4b80e38c072cf179dc97ea665d8a62dbb38b15f5c82a5
|
3 |
+
size 33555533
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (13.6 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_bracket.cpython-310.pyc
ADDED
Binary file (18.8 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-310.pyc
ADDED
Binary file (17.7 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_constraints.cpython-310.pyc
ADDED
Binary file (21.5 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-310.pyc
ADDED
Binary file (19.6 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-310.pyc
ADDED
Binary file (62.9 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_differentiate.cpython-310.pyc
ADDED
Binary file (21.6 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-310.pyc
ADDED
Binary file (10.9 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-310.pyc
ADDED
Binary file (22.4 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-310.pyc
ADDED
Binary file (12.8 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-310.pyc
ADDED
Binary file (5.77 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-310.pyc
ADDED
Binary file (21 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog.cpython-310.pyc
ADDED
Binary file (27.8 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-310.pyc
ADDED
Binary file (14.5 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-310.pyc
ADDED
Binary file (37.6 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_minpack_py.cpython-310.pyc
ADDED
Binary file (38.1 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_nonlin.cpython-310.pyc
ADDED
Binary file (46.5 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_qap.cpython-310.pyc
ADDED
Binary file (23.4 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_remove_redundancy.cpython-310.pyc
ADDED
Binary file (10.3 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_root_scalar.cpython-310.pyc
ADDED
Binary file (15.9 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_shgo.cpython-310.pyc
ADDED
Binary file (44.4 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_spectral.cpython-310.pyc
ADDED
Binary file (7.33 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion.cpython-310.pyc
ADDED
Binary file (7.89 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_krylov.cpython-310.pyc
ADDED
Binary file (1.4 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/_trustregion_ncg.cpython-310.pyc
ADDED
Binary file (3.25 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/cobyla.cpython-310.pyc
ADDED
Binary file (666 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/linesearch.cpython-310.pyc
ADDED
Binary file (800 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/minpack.cpython-310.pyc
ADDED
Binary file (938 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/nonlin.cpython-310.pyc
ADDED
Binary file (1.05 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/optimize.cpython-310.pyc
ADDED
Binary file (1.07 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/slsqp.cpython-310.pyc
ADDED
Binary file (779 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/__pycache__/tnc.cpython-310.pyc
ADDED
Binary file (848 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test__numdiff.cpython-310.pyc
ADDED
Binary file (24.4 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_chandrupatla.cpython-310.pyc
ADDED
Binary file (26.6 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_cython_optimize.cpython-310.pyc
ADDED
Binary file (2.34 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_differentiable_functions.cpython-310.pyc
ADDED
Binary file (16.8 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_isotonic_regression.cpython-310.pyc
ADDED
Binary file (5.71 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_linear_assignment.cpython-310.pyc
ADDED
Binary file (4.19 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_lsq_common.cpython-310.pyc
ADDED
Binary file (8.29 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_minimize_constrained.cpython-310.pyc
ADDED
Binary file (27.2 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-310.pyc
ADDED
Binary file (95.5 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/test__dual_annealing.py
ADDED
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Dual annealing unit tests implementation.
|
2 |
+
# Copyright (c) 2018 Sylvain Gubian <[email protected]>,
|
3 |
+
# Yang Xiang <[email protected]>
|
4 |
+
# Author: Sylvain Gubian, PMP S.A.
|
5 |
+
"""
|
6 |
+
Unit tests for the dual annealing global optimizer
|
7 |
+
"""
|
8 |
+
from scipy.optimize import dual_annealing, Bounds
|
9 |
+
|
10 |
+
from scipy.optimize._dual_annealing import EnergyState
|
11 |
+
from scipy.optimize._dual_annealing import LocalSearchWrapper
|
12 |
+
from scipy.optimize._dual_annealing import ObjectiveFunWrapper
|
13 |
+
from scipy.optimize._dual_annealing import StrategyChain
|
14 |
+
from scipy.optimize._dual_annealing import VisitingDistribution
|
15 |
+
from scipy.optimize import rosen, rosen_der
|
16 |
+
import pytest
|
17 |
+
import numpy as np
|
18 |
+
from numpy.testing import assert_equal, assert_allclose, assert_array_less
|
19 |
+
from pytest import raises as assert_raises
|
20 |
+
from scipy._lib._util import check_random_state
|
21 |
+
|
22 |
+
|
23 |
+
class TestDualAnnealing:
|
24 |
+
|
25 |
+
def setup_method(self):
|
26 |
+
# A function that returns always infinity for initialization tests
|
27 |
+
self.weirdfunc = lambda x: np.inf
|
28 |
+
# 2-D bounds for testing function
|
29 |
+
self.ld_bounds = [(-5.12, 5.12)] * 2
|
30 |
+
# 4-D bounds for testing function
|
31 |
+
self.hd_bounds = self.ld_bounds * 4
|
32 |
+
# Number of values to be generated for testing visit function
|
33 |
+
self.nbtestvalues = 5000
|
34 |
+
self.high_temperature = 5230
|
35 |
+
self.low_temperature = 0.1
|
36 |
+
self.qv = 2.62
|
37 |
+
self.seed = 1234
|
38 |
+
self.rs = check_random_state(self.seed)
|
39 |
+
self.nb_fun_call = 0
|
40 |
+
self.ngev = 0
|
41 |
+
|
42 |
+
def callback(self, x, f, context):
|
43 |
+
# For testing callback mechanism. Should stop for e <= 1 as
|
44 |
+
# the callback function returns True
|
45 |
+
if f <= 1.0:
|
46 |
+
return True
|
47 |
+
|
48 |
+
def func(self, x, args=()):
|
49 |
+
# Using Rastrigin function for performing tests
|
50 |
+
if args:
|
51 |
+
shift = args
|
52 |
+
else:
|
53 |
+
shift = 0
|
54 |
+
y = np.sum((x - shift) ** 2 - 10 * np.cos(2 * np.pi * (
|
55 |
+
x - shift))) + 10 * np.size(x) + shift
|
56 |
+
self.nb_fun_call += 1
|
57 |
+
return y
|
58 |
+
|
59 |
+
def rosen_der_wrapper(self, x, args=()):
|
60 |
+
self.ngev += 1
|
61 |
+
return rosen_der(x, *args)
|
62 |
+
|
63 |
+
# FIXME: there are some discontinuities in behaviour as a function of `qv`,
|
64 |
+
# this needs investigating - see gh-12384
|
65 |
+
@pytest.mark.parametrize('qv', [1.1, 1.41, 2, 2.62, 2.9])
|
66 |
+
def test_visiting_stepping(self, qv):
|
67 |
+
lu = list(zip(*self.ld_bounds))
|
68 |
+
lower = np.array(lu[0])
|
69 |
+
upper = np.array(lu[1])
|
70 |
+
dim = lower.size
|
71 |
+
vd = VisitingDistribution(lower, upper, qv, self.rs)
|
72 |
+
values = np.zeros(dim)
|
73 |
+
x_step_low = vd.visiting(values, 0, self.high_temperature)
|
74 |
+
# Make sure that only the first component is changed
|
75 |
+
assert_equal(np.not_equal(x_step_low, 0), True)
|
76 |
+
values = np.zeros(dim)
|
77 |
+
x_step_high = vd.visiting(values, dim, self.high_temperature)
|
78 |
+
# Make sure that component other than at dim has changed
|
79 |
+
assert_equal(np.not_equal(x_step_high[0], 0), True)
|
80 |
+
|
81 |
+
@pytest.mark.parametrize('qv', [2.25, 2.62, 2.9])
|
82 |
+
def test_visiting_dist_high_temperature(self, qv):
|
83 |
+
lu = list(zip(*self.ld_bounds))
|
84 |
+
lower = np.array(lu[0])
|
85 |
+
upper = np.array(lu[1])
|
86 |
+
vd = VisitingDistribution(lower, upper, qv, self.rs)
|
87 |
+
# values = np.zeros(self.nbtestvalues)
|
88 |
+
# for i in np.arange(self.nbtestvalues):
|
89 |
+
# values[i] = vd.visit_fn(self.high_temperature)
|
90 |
+
values = vd.visit_fn(self.high_temperature, self.nbtestvalues)
|
91 |
+
|
92 |
+
# Visiting distribution is a distorted version of Cauchy-Lorentz
|
93 |
+
# distribution, and as no 1st and higher moments (no mean defined,
|
94 |
+
# no variance defined).
|
95 |
+
# Check that big tails values are generated
|
96 |
+
assert_array_less(np.min(values), 1e-10)
|
97 |
+
assert_array_less(1e+10, np.max(values))
|
98 |
+
|
99 |
+
def test_reset(self):
|
100 |
+
owf = ObjectiveFunWrapper(self.weirdfunc)
|
101 |
+
lu = list(zip(*self.ld_bounds))
|
102 |
+
lower = np.array(lu[0])
|
103 |
+
upper = np.array(lu[1])
|
104 |
+
es = EnergyState(lower, upper)
|
105 |
+
assert_raises(ValueError, es.reset, owf, check_random_state(None))
|
106 |
+
|
107 |
+
def test_low_dim(self):
|
108 |
+
ret = dual_annealing(
|
109 |
+
self.func, self.ld_bounds, seed=self.seed)
|
110 |
+
assert_allclose(ret.fun, 0., atol=1e-12)
|
111 |
+
assert ret.success
|
112 |
+
|
113 |
+
def test_high_dim(self):
|
114 |
+
ret = dual_annealing(self.func, self.hd_bounds, seed=self.seed)
|
115 |
+
assert_allclose(ret.fun, 0., atol=1e-12)
|
116 |
+
assert ret.success
|
117 |
+
|
118 |
+
def test_low_dim_no_ls(self):
|
119 |
+
ret = dual_annealing(self.func, self.ld_bounds,
|
120 |
+
no_local_search=True, seed=self.seed)
|
121 |
+
assert_allclose(ret.fun, 0., atol=1e-4)
|
122 |
+
|
123 |
+
def test_high_dim_no_ls(self):
|
124 |
+
ret = dual_annealing(self.func, self.hd_bounds,
|
125 |
+
no_local_search=True, seed=self.seed)
|
126 |
+
assert_allclose(ret.fun, 0., atol=1e-4)
|
127 |
+
|
128 |
+
def test_nb_fun_call(self):
|
129 |
+
ret = dual_annealing(self.func, self.ld_bounds, seed=self.seed)
|
130 |
+
assert_equal(self.nb_fun_call, ret.nfev)
|
131 |
+
|
132 |
+
def test_nb_fun_call_no_ls(self):
|
133 |
+
ret = dual_annealing(self.func, self.ld_bounds,
|
134 |
+
no_local_search=True, seed=self.seed)
|
135 |
+
assert_equal(self.nb_fun_call, ret.nfev)
|
136 |
+
|
137 |
+
def test_max_reinit(self):
|
138 |
+
assert_raises(ValueError, dual_annealing, self.weirdfunc,
|
139 |
+
self.ld_bounds)
|
140 |
+
|
141 |
+
def test_reproduce(self):
|
142 |
+
res1 = dual_annealing(self.func, self.ld_bounds, seed=self.seed)
|
143 |
+
res2 = dual_annealing(self.func, self.ld_bounds, seed=self.seed)
|
144 |
+
res3 = dual_annealing(self.func, self.ld_bounds, seed=self.seed)
|
145 |
+
# If we have reproducible results, x components found has to
|
146 |
+
# be exactly the same, which is not the case with no seeding
|
147 |
+
assert_equal(res1.x, res2.x)
|
148 |
+
assert_equal(res1.x, res3.x)
|
149 |
+
|
150 |
+
def test_rand_gen(self):
|
151 |
+
# check that np.random.Generator can be used (numpy >= 1.17)
|
152 |
+
# obtain a np.random.Generator object
|
153 |
+
rng = np.random.default_rng(1)
|
154 |
+
|
155 |
+
res1 = dual_annealing(self.func, self.ld_bounds, seed=rng)
|
156 |
+
# seed again
|
157 |
+
rng = np.random.default_rng(1)
|
158 |
+
res2 = dual_annealing(self.func, self.ld_bounds, seed=rng)
|
159 |
+
# If we have reproducible results, x components found has to
|
160 |
+
# be exactly the same, which is not the case with no seeding
|
161 |
+
assert_equal(res1.x, res2.x)
|
162 |
+
|
163 |
+
def test_bounds_integrity(self):
|
164 |
+
wrong_bounds = [(-5.12, 5.12), (1, 0), (5.12, 5.12)]
|
165 |
+
assert_raises(ValueError, dual_annealing, self.func,
|
166 |
+
wrong_bounds)
|
167 |
+
|
168 |
+
def test_bound_validity(self):
|
169 |
+
invalid_bounds = [(-5, 5), (-np.inf, 0), (-5, 5)]
|
170 |
+
assert_raises(ValueError, dual_annealing, self.func,
|
171 |
+
invalid_bounds)
|
172 |
+
invalid_bounds = [(-5, 5), (0, np.inf), (-5, 5)]
|
173 |
+
assert_raises(ValueError, dual_annealing, self.func,
|
174 |
+
invalid_bounds)
|
175 |
+
invalid_bounds = [(-5, 5), (0, np.nan), (-5, 5)]
|
176 |
+
assert_raises(ValueError, dual_annealing, self.func,
|
177 |
+
invalid_bounds)
|
178 |
+
|
179 |
+
def test_deprecated_local_search_options_bounds(self):
|
180 |
+
def func(x):
|
181 |
+
return np.sum((x - 5) * (x - 1))
|
182 |
+
bounds = list(zip([-6, -5], [6, 5]))
|
183 |
+
# Test bounds can be passed (see gh-10831)
|
184 |
+
|
185 |
+
with pytest.warns(RuntimeWarning, match=r"Method CG cannot handle "):
|
186 |
+
dual_annealing(
|
187 |
+
func,
|
188 |
+
bounds=bounds,
|
189 |
+
minimizer_kwargs={"method": "CG", "bounds": bounds})
|
190 |
+
|
191 |
+
def test_minimizer_kwargs_bounds(self):
|
192 |
+
def func(x):
|
193 |
+
return np.sum((x - 5) * (x - 1))
|
194 |
+
bounds = list(zip([-6, -5], [6, 5]))
|
195 |
+
# Test bounds can be passed (see gh-10831)
|
196 |
+
dual_annealing(
|
197 |
+
func,
|
198 |
+
bounds=bounds,
|
199 |
+
minimizer_kwargs={"method": "SLSQP", "bounds": bounds})
|
200 |
+
|
201 |
+
with pytest.warns(RuntimeWarning, match=r"Method CG cannot handle "):
|
202 |
+
dual_annealing(
|
203 |
+
func,
|
204 |
+
bounds=bounds,
|
205 |
+
minimizer_kwargs={"method": "CG", "bounds": bounds})
|
206 |
+
|
207 |
+
def test_max_fun_ls(self):
|
208 |
+
ret = dual_annealing(self.func, self.ld_bounds, maxfun=100,
|
209 |
+
seed=self.seed)
|
210 |
+
|
211 |
+
ls_max_iter = min(max(
|
212 |
+
len(self.ld_bounds) * LocalSearchWrapper.LS_MAXITER_RATIO,
|
213 |
+
LocalSearchWrapper.LS_MAXITER_MIN),
|
214 |
+
LocalSearchWrapper.LS_MAXITER_MAX)
|
215 |
+
assert ret.nfev <= 100 + ls_max_iter
|
216 |
+
assert not ret.success
|
217 |
+
|
218 |
+
def test_max_fun_no_ls(self):
|
219 |
+
ret = dual_annealing(self.func, self.ld_bounds,
|
220 |
+
no_local_search=True, maxfun=500, seed=self.seed)
|
221 |
+
assert ret.nfev <= 500
|
222 |
+
assert not ret.success
|
223 |
+
|
224 |
+
def test_maxiter(self):
|
225 |
+
ret = dual_annealing(self.func, self.ld_bounds, maxiter=700,
|
226 |
+
seed=self.seed)
|
227 |
+
assert ret.nit <= 700
|
228 |
+
|
229 |
+
# Testing that args are passed correctly for dual_annealing
|
230 |
+
def test_fun_args_ls(self):
|
231 |
+
ret = dual_annealing(self.func, self.ld_bounds,
|
232 |
+
args=((3.14159,)), seed=self.seed)
|
233 |
+
assert_allclose(ret.fun, 3.14159, atol=1e-6)
|
234 |
+
|
235 |
+
# Testing that args are passed correctly for pure simulated annealing
|
236 |
+
def test_fun_args_no_ls(self):
|
237 |
+
ret = dual_annealing(self.func, self.ld_bounds,
|
238 |
+
args=((3.14159, )), no_local_search=True,
|
239 |
+
seed=self.seed)
|
240 |
+
assert_allclose(ret.fun, 3.14159, atol=1e-4)
|
241 |
+
|
242 |
+
def test_callback_stop(self):
|
243 |
+
# Testing that callback make the algorithm stop for
|
244 |
+
# fun value <= 1.0 (see callback method)
|
245 |
+
ret = dual_annealing(self.func, self.ld_bounds,
|
246 |
+
callback=self.callback, seed=self.seed)
|
247 |
+
assert ret.fun <= 1.0
|
248 |
+
assert 'stop early' in ret.message[0]
|
249 |
+
assert not ret.success
|
250 |
+
|
251 |
+
@pytest.mark.parametrize('method, atol', [
|
252 |
+
('Nelder-Mead', 2e-5),
|
253 |
+
('COBYLA', 1e-5),
|
254 |
+
('Powell', 1e-8),
|
255 |
+
('CG', 1e-8),
|
256 |
+
('BFGS', 1e-8),
|
257 |
+
('TNC', 1e-8),
|
258 |
+
('SLSQP', 2e-7),
|
259 |
+
])
|
260 |
+
def test_multi_ls_minimizer(self, method, atol):
|
261 |
+
ret = dual_annealing(self.func, self.ld_bounds,
|
262 |
+
minimizer_kwargs=dict(method=method),
|
263 |
+
seed=self.seed)
|
264 |
+
assert_allclose(ret.fun, 0., atol=atol)
|
265 |
+
|
266 |
+
def test_wrong_restart_temp(self):
|
267 |
+
assert_raises(ValueError, dual_annealing, self.func,
|
268 |
+
self.ld_bounds, restart_temp_ratio=1)
|
269 |
+
assert_raises(ValueError, dual_annealing, self.func,
|
270 |
+
self.ld_bounds, restart_temp_ratio=0)
|
271 |
+
|
272 |
+
def test_gradient_gnev(self):
|
273 |
+
minimizer_opts = {
|
274 |
+
'jac': self.rosen_der_wrapper,
|
275 |
+
}
|
276 |
+
ret = dual_annealing(rosen, self.ld_bounds,
|
277 |
+
minimizer_kwargs=minimizer_opts,
|
278 |
+
seed=self.seed)
|
279 |
+
assert ret.njev == self.ngev
|
280 |
+
|
281 |
+
def test_from_docstring(self):
|
282 |
+
def func(x):
|
283 |
+
return np.sum(x * x - 10 * np.cos(2 * np.pi * x)) + 10 * np.size(x)
|
284 |
+
lw = [-5.12] * 10
|
285 |
+
up = [5.12] * 10
|
286 |
+
ret = dual_annealing(func, bounds=list(zip(lw, up)), seed=1234)
|
287 |
+
assert_allclose(ret.x,
|
288 |
+
[-4.26437714e-09, -3.91699361e-09, -1.86149218e-09,
|
289 |
+
-3.97165720e-09, -6.29151648e-09, -6.53145322e-09,
|
290 |
+
-3.93616815e-09, -6.55623025e-09, -6.05775280e-09,
|
291 |
+
-5.00668935e-09], atol=4e-8)
|
292 |
+
assert_allclose(ret.fun, 0.000000, atol=5e-13)
|
293 |
+
|
294 |
+
@pytest.mark.parametrize('new_e, temp_step, accepted, accept_rate', [
|
295 |
+
(0, 100, 1000, 1.0097587941791923),
|
296 |
+
(0, 2, 1000, 1.2599210498948732),
|
297 |
+
(10, 100, 878, 0.8786035869128718),
|
298 |
+
(10, 60, 695, 0.6812920690579612),
|
299 |
+
(2, 100, 990, 0.9897404249173424),
|
300 |
+
])
|
301 |
+
def test_accept_reject_probabilistic(
|
302 |
+
self, new_e, temp_step, accepted, accept_rate):
|
303 |
+
# Test accepts unconditionally with e < current_energy and
|
304 |
+
# probabilistically with e > current_energy
|
305 |
+
|
306 |
+
rs = check_random_state(123)
|
307 |
+
|
308 |
+
count_accepted = 0
|
309 |
+
iterations = 1000
|
310 |
+
|
311 |
+
accept_param = -5
|
312 |
+
current_energy = 1
|
313 |
+
for _ in range(iterations):
|
314 |
+
energy_state = EnergyState(lower=None, upper=None)
|
315 |
+
# Set energy state with current_energy, any location.
|
316 |
+
energy_state.update_current(current_energy, [0])
|
317 |
+
|
318 |
+
chain = StrategyChain(
|
319 |
+
accept_param, None, None, None, rs, energy_state)
|
320 |
+
# Normally this is set in run()
|
321 |
+
chain.temperature_step = temp_step
|
322 |
+
|
323 |
+
# Check if update is accepted.
|
324 |
+
chain.accept_reject(j=1, e=new_e, x_visit=[2])
|
325 |
+
if energy_state.current_energy == new_e:
|
326 |
+
count_accepted += 1
|
327 |
+
|
328 |
+
assert count_accepted == accepted
|
329 |
+
|
330 |
+
# Check accept rate
|
331 |
+
pqv = 1 - (1 - accept_param) * (new_e - current_energy) / temp_step
|
332 |
+
rate = 0 if pqv <= 0 else np.exp(np.log(pqv) / (1 - accept_param))
|
333 |
+
|
334 |
+
assert_allclose(rate, accept_rate)
|
335 |
+
|
336 |
+
def test_bounds_class(self):
|
337 |
+
# test that result does not depend on the bounds type
|
338 |
+
def func(x):
|
339 |
+
f = np.sum(x * x - 10 * np.cos(2 * np.pi * x)) + 10 * np.size(x)
|
340 |
+
return f
|
341 |
+
lw = [-5.12] * 5
|
342 |
+
up = [5.12] * 5
|
343 |
+
|
344 |
+
# Unbounded global minimum is all zeros. Most bounds below will force
|
345 |
+
# a DV away from unbounded minimum and be active at solution.
|
346 |
+
up[0] = -2.0
|
347 |
+
up[1] = -1.0
|
348 |
+
lw[3] = 1.0
|
349 |
+
lw[4] = 2.0
|
350 |
+
|
351 |
+
# run optimizations
|
352 |
+
bounds = Bounds(lw, up)
|
353 |
+
ret_bounds_class = dual_annealing(func, bounds=bounds, seed=1234)
|
354 |
+
|
355 |
+
bounds_old = list(zip(lw, up))
|
356 |
+
ret_bounds_list = dual_annealing(func, bounds=bounds_old, seed=1234)
|
357 |
+
|
358 |
+
# test that found minima, function evaluations and iterations match
|
359 |
+
assert_allclose(ret_bounds_class.x, ret_bounds_list.x, atol=1e-8)
|
360 |
+
assert_allclose(ret_bounds_class.x, np.arange(-2, 3), atol=1e-7)
|
361 |
+
assert_allclose(ret_bounds_list.fun, ret_bounds_class.fun, atol=1e-9)
|
362 |
+
assert ret_bounds_list.nfev == ret_bounds_class.nfev
|
363 |
+
|
364 |
+
def test_callable_jac_with_args_gh11052(self):
|
365 |
+
# dual_annealing used to fail when `jac` was callable and `args` were
|
366 |
+
# used; check that this is resolved. Example is from gh-11052.
|
367 |
+
rng = np.random.default_rng(94253637693657847462)
|
368 |
+
def f(x, power):
|
369 |
+
return np.sum(np.exp(x ** power))
|
370 |
+
|
371 |
+
def jac(x, power):
|
372 |
+
return np.exp(x ** power) * power * x ** (power - 1)
|
373 |
+
|
374 |
+
res1 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], seed=rng,
|
375 |
+
minimizer_kwargs=dict(method='L-BFGS-B'))
|
376 |
+
res2 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], seed=rng,
|
377 |
+
minimizer_kwargs=dict(method='L-BFGS-B',
|
378 |
+
jac=jac))
|
379 |
+
assert_allclose(res1.fun, res2.fun, rtol=1e-6)
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py
ADDED
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Unit test for Linear Programming via Simplex Algorithm.
|
3 |
+
"""
|
4 |
+
import numpy as np
|
5 |
+
from numpy.testing import assert_, assert_allclose, assert_equal
|
6 |
+
from pytest import raises as assert_raises
|
7 |
+
from scipy.optimize._linprog_util import _clean_inputs, _LPProblem
|
8 |
+
from scipy._lib._util import VisibleDeprecationWarning
|
9 |
+
from copy import deepcopy
|
10 |
+
from datetime import date
|
11 |
+
|
12 |
+
|
13 |
+
def test_aliasing():
|
14 |
+
"""
|
15 |
+
Test for ensuring that no objects referred to by `lp` attributes,
|
16 |
+
`c`, `A_ub`, `b_ub`, `A_eq`, `b_eq`, `bounds`, have been modified
|
17 |
+
by `_clean_inputs` as a side effect.
|
18 |
+
"""
|
19 |
+
lp = _LPProblem(
|
20 |
+
c=1,
|
21 |
+
A_ub=[[1]],
|
22 |
+
b_ub=[1],
|
23 |
+
A_eq=[[1]],
|
24 |
+
b_eq=[1],
|
25 |
+
bounds=(-np.inf, np.inf)
|
26 |
+
)
|
27 |
+
lp_copy = deepcopy(lp)
|
28 |
+
|
29 |
+
_clean_inputs(lp)
|
30 |
+
|
31 |
+
assert_(lp.c == lp_copy.c, "c modified by _clean_inputs")
|
32 |
+
assert_(lp.A_ub == lp_copy.A_ub, "A_ub modified by _clean_inputs")
|
33 |
+
assert_(lp.b_ub == lp_copy.b_ub, "b_ub modified by _clean_inputs")
|
34 |
+
assert_(lp.A_eq == lp_copy.A_eq, "A_eq modified by _clean_inputs")
|
35 |
+
assert_(lp.b_eq == lp_copy.b_eq, "b_eq modified by _clean_inputs")
|
36 |
+
assert_(lp.bounds == lp_copy.bounds, "bounds modified by _clean_inputs")
|
37 |
+
|
38 |
+
|
39 |
+
def test_aliasing2():
|
40 |
+
"""
|
41 |
+
Similar purpose as `test_aliasing` above.
|
42 |
+
"""
|
43 |
+
lp = _LPProblem(
|
44 |
+
c=np.array([1, 1]),
|
45 |
+
A_ub=np.array([[1, 1], [2, 2]]),
|
46 |
+
b_ub=np.array([[1], [1]]),
|
47 |
+
A_eq=np.array([[1, 1]]),
|
48 |
+
b_eq=np.array([1]),
|
49 |
+
bounds=[(-np.inf, np.inf), (None, 1)]
|
50 |
+
)
|
51 |
+
lp_copy = deepcopy(lp)
|
52 |
+
|
53 |
+
_clean_inputs(lp)
|
54 |
+
|
55 |
+
assert_allclose(lp.c, lp_copy.c, err_msg="c modified by _clean_inputs")
|
56 |
+
assert_allclose(lp.A_ub, lp_copy.A_ub, err_msg="A_ub modified by _clean_inputs")
|
57 |
+
assert_allclose(lp.b_ub, lp_copy.b_ub, err_msg="b_ub modified by _clean_inputs")
|
58 |
+
assert_allclose(lp.A_eq, lp_copy.A_eq, err_msg="A_eq modified by _clean_inputs")
|
59 |
+
assert_allclose(lp.b_eq, lp_copy.b_eq, err_msg="b_eq modified by _clean_inputs")
|
60 |
+
assert_(lp.bounds == lp_copy.bounds, "bounds modified by _clean_inputs")
|
61 |
+
|
62 |
+
|
63 |
+
def test_missing_inputs():
|
64 |
+
c = [1, 2]
|
65 |
+
A_ub = np.array([[1, 1], [2, 2]])
|
66 |
+
b_ub = np.array([1, 1])
|
67 |
+
A_eq = np.array([[1, 1], [2, 2]])
|
68 |
+
b_eq = np.array([1, 1])
|
69 |
+
|
70 |
+
assert_raises(TypeError, _clean_inputs)
|
71 |
+
assert_raises(TypeError, _clean_inputs, _LPProblem(c=None))
|
72 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=A_ub))
|
73 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=A_ub, b_ub=None))
|
74 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, b_ub=b_ub))
|
75 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=None, b_ub=b_ub))
|
76 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=A_eq))
|
77 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=A_eq, b_eq=None))
|
78 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, b_eq=b_eq))
|
79 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=None, b_eq=b_eq))
|
80 |
+
|
81 |
+
|
82 |
+
def test_too_many_dimensions():
|
83 |
+
cb = [1, 2, 3, 4]
|
84 |
+
A = np.random.rand(4, 4)
|
85 |
+
bad2D = [[1, 2], [3, 4]]
|
86 |
+
bad3D = np.random.rand(4, 4, 4)
|
87 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=bad2D, A_ub=A, b_ub=cb))
|
88 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=bad3D, b_ub=cb))
|
89 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=A, b_ub=bad2D))
|
90 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=bad3D, b_eq=cb))
|
91 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=A, b_eq=bad2D))
|
92 |
+
|
93 |
+
|
94 |
+
def test_too_few_dimensions():
|
95 |
+
bad = np.random.rand(4, 4).ravel()
|
96 |
+
cb = np.random.rand(4)
|
97 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=bad, b_ub=cb))
|
98 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=bad, b_eq=cb))
|
99 |
+
|
100 |
+
|
101 |
+
def test_inconsistent_dimensions():
|
102 |
+
m = 2
|
103 |
+
n = 4
|
104 |
+
c = [1, 2, 3, 4]
|
105 |
+
|
106 |
+
Agood = np.random.rand(m, n)
|
107 |
+
Abad = np.random.rand(m, n + 1)
|
108 |
+
bgood = np.random.rand(m)
|
109 |
+
bbad = np.random.rand(m + 1)
|
110 |
+
boundsbad = [(0, 1)] * (n + 1)
|
111 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=Abad, b_ub=bgood))
|
112 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=Agood, b_ub=bbad))
|
113 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=Abad, b_eq=bgood))
|
114 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=Agood, b_eq=bbad))
|
115 |
+
assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, bounds=boundsbad))
|
116 |
+
with np.testing.suppress_warnings() as sup:
|
117 |
+
sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged")
|
118 |
+
assert_raises(ValueError, _clean_inputs,
|
119 |
+
_LPProblem(c=c, bounds=[[1, 2], [2, 3], [3, 4], [4, 5, 6]]))
|
120 |
+
|
121 |
+
|
122 |
+
def test_type_errors():
|
123 |
+
lp = _LPProblem(
|
124 |
+
c=[1, 2],
|
125 |
+
A_ub=np.array([[1, 1], [2, 2]]),
|
126 |
+
b_ub=np.array([1, 1]),
|
127 |
+
A_eq=np.array([[1, 1], [2, 2]]),
|
128 |
+
b_eq=np.array([1, 1]),
|
129 |
+
bounds=[(0, 1)]
|
130 |
+
)
|
131 |
+
bad = "hello"
|
132 |
+
|
133 |
+
assert_raises(TypeError, _clean_inputs, lp._replace(c=bad))
|
134 |
+
assert_raises(TypeError, _clean_inputs, lp._replace(A_ub=bad))
|
135 |
+
assert_raises(TypeError, _clean_inputs, lp._replace(b_ub=bad))
|
136 |
+
assert_raises(TypeError, _clean_inputs, lp._replace(A_eq=bad))
|
137 |
+
assert_raises(TypeError, _clean_inputs, lp._replace(b_eq=bad))
|
138 |
+
|
139 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(bounds=bad))
|
140 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(bounds="hi"))
|
141 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(bounds=["hi"]))
|
142 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[("hi")]))
|
143 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, "")]))
|
144 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2), (1, "")]))
|
145 |
+
assert_raises(TypeError, _clean_inputs,
|
146 |
+
lp._replace(bounds=[(1, date(2020, 2, 29))]))
|
147 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[[[1, 2]]]))
|
148 |
+
|
149 |
+
|
150 |
+
def test_non_finite_errors():
|
151 |
+
lp = _LPProblem(
|
152 |
+
c=[1, 2],
|
153 |
+
A_ub=np.array([[1, 1], [2, 2]]),
|
154 |
+
b_ub=np.array([1, 1]),
|
155 |
+
A_eq=np.array([[1, 1], [2, 2]]),
|
156 |
+
b_eq=np.array([1, 1]),
|
157 |
+
bounds=[(0, 1)]
|
158 |
+
)
|
159 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(c=[0, None]))
|
160 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(c=[np.inf, 0]))
|
161 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(c=[0, -np.inf]))
|
162 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(c=[np.nan, 0]))
|
163 |
+
|
164 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(A_ub=[[1, 2], [None, 1]]))
|
165 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(b_ub=[np.inf, 1]))
|
166 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(A_eq=[[1, 2], [1, -np.inf]]))
|
167 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(b_eq=[1, np.nan]))
|
168 |
+
|
169 |
+
|
170 |
+
def test__clean_inputs1():
|
171 |
+
lp = _LPProblem(
|
172 |
+
c=[1, 2],
|
173 |
+
A_ub=[[1, 1], [2, 2]],
|
174 |
+
b_ub=[1, 1],
|
175 |
+
A_eq=[[1, 1], [2, 2]],
|
176 |
+
b_eq=[1, 1],
|
177 |
+
bounds=None
|
178 |
+
)
|
179 |
+
|
180 |
+
lp_cleaned = _clean_inputs(lp)
|
181 |
+
|
182 |
+
assert_allclose(lp_cleaned.c, np.array(lp.c))
|
183 |
+
assert_allclose(lp_cleaned.A_ub, np.array(lp.A_ub))
|
184 |
+
assert_allclose(lp_cleaned.b_ub, np.array(lp.b_ub))
|
185 |
+
assert_allclose(lp_cleaned.A_eq, np.array(lp.A_eq))
|
186 |
+
assert_allclose(lp_cleaned.b_eq, np.array(lp.b_eq))
|
187 |
+
assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
|
188 |
+
|
189 |
+
assert_(lp_cleaned.c.shape == (2,), "")
|
190 |
+
assert_(lp_cleaned.A_ub.shape == (2, 2), "")
|
191 |
+
assert_(lp_cleaned.b_ub.shape == (2,), "")
|
192 |
+
assert_(lp_cleaned.A_eq.shape == (2, 2), "")
|
193 |
+
assert_(lp_cleaned.b_eq.shape == (2,), "")
|
194 |
+
|
195 |
+
|
196 |
+
def test__clean_inputs2():
|
197 |
+
lp = _LPProblem(
|
198 |
+
c=1,
|
199 |
+
A_ub=[[1]],
|
200 |
+
b_ub=1,
|
201 |
+
A_eq=[[1]],
|
202 |
+
b_eq=1,
|
203 |
+
bounds=(0, 1)
|
204 |
+
)
|
205 |
+
|
206 |
+
lp_cleaned = _clean_inputs(lp)
|
207 |
+
|
208 |
+
assert_allclose(lp_cleaned.c, np.array(lp.c))
|
209 |
+
assert_allclose(lp_cleaned.A_ub, np.array(lp.A_ub))
|
210 |
+
assert_allclose(lp_cleaned.b_ub, np.array(lp.b_ub))
|
211 |
+
assert_allclose(lp_cleaned.A_eq, np.array(lp.A_eq))
|
212 |
+
assert_allclose(lp_cleaned.b_eq, np.array(lp.b_eq))
|
213 |
+
assert_equal(lp_cleaned.bounds, [(0, 1)])
|
214 |
+
|
215 |
+
assert_(lp_cleaned.c.shape == (1,), "")
|
216 |
+
assert_(lp_cleaned.A_ub.shape == (1, 1), "")
|
217 |
+
assert_(lp_cleaned.b_ub.shape == (1,), "")
|
218 |
+
assert_(lp_cleaned.A_eq.shape == (1, 1), "")
|
219 |
+
assert_(lp_cleaned.b_eq.shape == (1,), "")
|
220 |
+
|
221 |
+
|
222 |
+
def test__clean_inputs3():
|
223 |
+
lp = _LPProblem(
|
224 |
+
c=[[1, 2]],
|
225 |
+
A_ub=np.random.rand(2, 2),
|
226 |
+
b_ub=[[1], [2]],
|
227 |
+
A_eq=np.random.rand(2, 2),
|
228 |
+
b_eq=[[1], [2]],
|
229 |
+
bounds=[(0, 1)]
|
230 |
+
)
|
231 |
+
|
232 |
+
lp_cleaned = _clean_inputs(lp)
|
233 |
+
|
234 |
+
assert_allclose(lp_cleaned.c, np.array([1, 2]))
|
235 |
+
assert_allclose(lp_cleaned.b_ub, np.array([1, 2]))
|
236 |
+
assert_allclose(lp_cleaned.b_eq, np.array([1, 2]))
|
237 |
+
assert_equal(lp_cleaned.bounds, [(0, 1)] * 2)
|
238 |
+
|
239 |
+
assert_(lp_cleaned.c.shape == (2,), "")
|
240 |
+
assert_(lp_cleaned.b_ub.shape == (2,), "")
|
241 |
+
assert_(lp_cleaned.b_eq.shape == (2,), "")
|
242 |
+
|
243 |
+
|
244 |
+
def test_bad_bounds():
|
245 |
+
lp = _LPProblem(c=[1, 2])
|
246 |
+
|
247 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(bounds=(1, 2, 2)))
|
248 |
+
assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2, 2)]))
|
249 |
+
with np.testing.suppress_warnings() as sup:
|
250 |
+
sup.filter(VisibleDeprecationWarning, "Creating an ndarray from ragged")
|
251 |
+
assert_raises(ValueError, _clean_inputs,
|
252 |
+
lp._replace(bounds=[(1, 2), (1, 2, 2)]))
|
253 |
+
assert_raises(ValueError, _clean_inputs,
|
254 |
+
lp._replace(bounds=[(1, 2), (1, 2), (1, 2)]))
|
255 |
+
|
256 |
+
lp = _LPProblem(c=[1, 2, 3, 4])
|
257 |
+
|
258 |
+
assert_raises(ValueError, _clean_inputs,
|
259 |
+
lp._replace(bounds=[(1, 2, 3, 4), (1, 2, 3, 4)]))
|
260 |
+
|
261 |
+
|
262 |
+
def test_good_bounds():
|
263 |
+
lp = _LPProblem(c=[1, 2])
|
264 |
+
|
265 |
+
lp_cleaned = _clean_inputs(lp) # lp.bounds is None by default
|
266 |
+
assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
|
267 |
+
|
268 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[]))
|
269 |
+
assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
|
270 |
+
|
271 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[[]]))
|
272 |
+
assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
|
273 |
+
|
274 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=(1, 2)))
|
275 |
+
assert_equal(lp_cleaned.bounds, [(1, 2)] * 2)
|
276 |
+
|
277 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, 2)]))
|
278 |
+
assert_equal(lp_cleaned.bounds, [(1, 2)] * 2)
|
279 |
+
|
280 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, None)]))
|
281 |
+
assert_equal(lp_cleaned.bounds, [(1, np.inf)] * 2)
|
282 |
+
|
283 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, 1)]))
|
284 |
+
assert_equal(lp_cleaned.bounds, [(-np.inf, 1)] * 2)
|
285 |
+
|
286 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, None), (-np.inf, None)]))
|
287 |
+
assert_equal(lp_cleaned.bounds, [(-np.inf, np.inf)] * 2)
|
288 |
+
|
289 |
+
lp = _LPProblem(c=[1, 2, 3, 4])
|
290 |
+
|
291 |
+
lp_cleaned = _clean_inputs(lp) # lp.bounds is None by default
|
292 |
+
assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 4)
|
293 |
+
|
294 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=(1, 2)))
|
295 |
+
assert_equal(lp_cleaned.bounds, [(1, 2)] * 4)
|
296 |
+
|
297 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, 2)]))
|
298 |
+
assert_equal(lp_cleaned.bounds, [(1, 2)] * 4)
|
299 |
+
|
300 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, None)]))
|
301 |
+
assert_equal(lp_cleaned.bounds, [(1, np.inf)] * 4)
|
302 |
+
|
303 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, 1)]))
|
304 |
+
assert_equal(lp_cleaned.bounds, [(-np.inf, 1)] * 4)
|
305 |
+
|
306 |
+
lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, None),
|
307 |
+
(-np.inf, None),
|
308 |
+
(None, np.inf),
|
309 |
+
(-np.inf, np.inf)]))
|
310 |
+
assert_equal(lp_cleaned.bounds, [(-np.inf, np.inf)] * 4)
|
venv/lib/python3.10/site-packages/scipy/optimize/tests/test__numdiff.py
ADDED
@@ -0,0 +1,815 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
from itertools import product
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
from numpy.testing import assert_allclose, assert_equal, assert_
|
6 |
+
from pytest import raises as assert_raises
|
7 |
+
|
8 |
+
from scipy.sparse import csr_matrix, csc_matrix, lil_matrix
|
9 |
+
|
10 |
+
from scipy.optimize._numdiff import (
|
11 |
+
_adjust_scheme_to_bounds, approx_derivative, check_derivative,
|
12 |
+
group_columns, _eps_for_method, _compute_absolute_step)
|
13 |
+
|
14 |
+
|
15 |
+
def test_group_columns():
|
16 |
+
structure = [
|
17 |
+
[1, 1, 0, 0, 0, 0],
|
18 |
+
[1, 1, 1, 0, 0, 0],
|
19 |
+
[0, 1, 1, 1, 0, 0],
|
20 |
+
[0, 0, 1, 1, 1, 0],
|
21 |
+
[0, 0, 0, 1, 1, 1],
|
22 |
+
[0, 0, 0, 0, 1, 1],
|
23 |
+
[0, 0, 0, 0, 0, 0]
|
24 |
+
]
|
25 |
+
for transform in [np.asarray, csr_matrix, csc_matrix, lil_matrix]:
|
26 |
+
A = transform(structure)
|
27 |
+
order = np.arange(6)
|
28 |
+
groups_true = np.array([0, 1, 2, 0, 1, 2])
|
29 |
+
groups = group_columns(A, order)
|
30 |
+
assert_equal(groups, groups_true)
|
31 |
+
|
32 |
+
order = [1, 2, 4, 3, 5, 0]
|
33 |
+
groups_true = np.array([2, 0, 1, 2, 0, 1])
|
34 |
+
groups = group_columns(A, order)
|
35 |
+
assert_equal(groups, groups_true)
|
36 |
+
|
37 |
+
# Test repeatability.
|
38 |
+
groups_1 = group_columns(A)
|
39 |
+
groups_2 = group_columns(A)
|
40 |
+
assert_equal(groups_1, groups_2)
|
41 |
+
|
42 |
+
|
43 |
+
def test_correct_fp_eps():
|
44 |
+
# check that relative step size is correct for FP size
|
45 |
+
EPS = np.finfo(np.float64).eps
|
46 |
+
relative_step = {"2-point": EPS**0.5,
|
47 |
+
"3-point": EPS**(1/3),
|
48 |
+
"cs": EPS**0.5}
|
49 |
+
for method in ['2-point', '3-point', 'cs']:
|
50 |
+
assert_allclose(
|
51 |
+
_eps_for_method(np.float64, np.float64, method),
|
52 |
+
relative_step[method])
|
53 |
+
assert_allclose(
|
54 |
+
_eps_for_method(np.complex128, np.complex128, method),
|
55 |
+
relative_step[method]
|
56 |
+
)
|
57 |
+
|
58 |
+
# check another FP size
|
59 |
+
EPS = np.finfo(np.float32).eps
|
60 |
+
relative_step = {"2-point": EPS**0.5,
|
61 |
+
"3-point": EPS**(1/3),
|
62 |
+
"cs": EPS**0.5}
|
63 |
+
|
64 |
+
for method in ['2-point', '3-point', 'cs']:
|
65 |
+
assert_allclose(
|
66 |
+
_eps_for_method(np.float64, np.float32, method),
|
67 |
+
relative_step[method]
|
68 |
+
)
|
69 |
+
assert_allclose(
|
70 |
+
_eps_for_method(np.float32, np.float64, method),
|
71 |
+
relative_step[method]
|
72 |
+
)
|
73 |
+
assert_allclose(
|
74 |
+
_eps_for_method(np.float32, np.float32, method),
|
75 |
+
relative_step[method]
|
76 |
+
)
|
77 |
+
|
78 |
+
|
79 |
+
class TestAdjustSchemeToBounds:
|
80 |
+
def test_no_bounds(self):
|
81 |
+
x0 = np.zeros(3)
|
82 |
+
h = np.full(3, 1e-2)
|
83 |
+
inf_lower = np.empty_like(x0)
|
84 |
+
inf_upper = np.empty_like(x0)
|
85 |
+
inf_lower.fill(-np.inf)
|
86 |
+
inf_upper.fill(np.inf)
|
87 |
+
|
88 |
+
h_adjusted, one_sided = _adjust_scheme_to_bounds(
|
89 |
+
x0, h, 1, '1-sided', inf_lower, inf_upper)
|
90 |
+
assert_allclose(h_adjusted, h)
|
91 |
+
assert_(np.all(one_sided))
|
92 |
+
|
93 |
+
h_adjusted, one_sided = _adjust_scheme_to_bounds(
|
94 |
+
x0, h, 2, '1-sided', inf_lower, inf_upper)
|
95 |
+
assert_allclose(h_adjusted, h)
|
96 |
+
assert_(np.all(one_sided))
|
97 |
+
|
98 |
+
h_adjusted, one_sided = _adjust_scheme_to_bounds(
|
99 |
+
x0, h, 1, '2-sided', inf_lower, inf_upper)
|
100 |
+
assert_allclose(h_adjusted, h)
|
101 |
+
assert_(np.all(~one_sided))
|
102 |
+
|
103 |
+
h_adjusted, one_sided = _adjust_scheme_to_bounds(
|
104 |
+
x0, h, 2, '2-sided', inf_lower, inf_upper)
|
105 |
+
assert_allclose(h_adjusted, h)
|
106 |
+
assert_(np.all(~one_sided))
|
107 |
+
|
108 |
+
def test_with_bound(self):
|
109 |
+
x0 = np.array([0.0, 0.85, -0.85])
|
110 |
+
lb = -np.ones(3)
|
111 |
+
ub = np.ones(3)
|
112 |
+
h = np.array([1, 1, -1]) * 1e-1
|
113 |
+
|
114 |
+
h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 1, '1-sided', lb, ub)
|
115 |
+
assert_allclose(h_adjusted, h)
|
116 |
+
|
117 |
+
h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 2, '1-sided', lb, ub)
|
118 |
+
assert_allclose(h_adjusted, np.array([1, -1, 1]) * 1e-1)
|
119 |
+
|
120 |
+
h_adjusted, one_sided = _adjust_scheme_to_bounds(
|
121 |
+
x0, h, 1, '2-sided', lb, ub)
|
122 |
+
assert_allclose(h_adjusted, np.abs(h))
|
123 |
+
assert_(np.all(~one_sided))
|
124 |
+
|
125 |
+
h_adjusted, one_sided = _adjust_scheme_to_bounds(
|
126 |
+
x0, h, 2, '2-sided', lb, ub)
|
127 |
+
assert_allclose(h_adjusted, np.array([1, -1, 1]) * 1e-1)
|
128 |
+
assert_equal(one_sided, np.array([False, True, True]))
|
129 |
+
|
130 |
+
def test_tight_bounds(self):
|
131 |
+
lb = np.array([-0.03, -0.03])
|
132 |
+
ub = np.array([0.05, 0.05])
|
133 |
+
x0 = np.array([0.0, 0.03])
|
134 |
+
h = np.array([-0.1, -0.1])
|
135 |
+
|
136 |
+
h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 1, '1-sided', lb, ub)
|
137 |
+
assert_allclose(h_adjusted, np.array([0.05, -0.06]))
|
138 |
+
|
139 |
+
h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 2, '1-sided', lb, ub)
|
140 |
+
assert_allclose(h_adjusted, np.array([0.025, -0.03]))
|
141 |
+
|
142 |
+
h_adjusted, one_sided = _adjust_scheme_to_bounds(
|
143 |
+
x0, h, 1, '2-sided', lb, ub)
|
144 |
+
assert_allclose(h_adjusted, np.array([0.03, -0.03]))
|
145 |
+
assert_equal(one_sided, np.array([False, True]))
|
146 |
+
|
147 |
+
h_adjusted, one_sided = _adjust_scheme_to_bounds(
|
148 |
+
x0, h, 2, '2-sided', lb, ub)
|
149 |
+
assert_allclose(h_adjusted, np.array([0.015, -0.015]))
|
150 |
+
assert_equal(one_sided, np.array([False, True]))
|
151 |
+
|
152 |
+
|
153 |
+
class TestApproxDerivativesDense:
|
154 |
+
def fun_scalar_scalar(self, x):
|
155 |
+
return np.sinh(x)
|
156 |
+
|
157 |
+
def jac_scalar_scalar(self, x):
|
158 |
+
return np.cosh(x)
|
159 |
+
|
160 |
+
def fun_scalar_vector(self, x):
|
161 |
+
return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])])
|
162 |
+
|
163 |
+
def jac_scalar_vector(self, x):
|
164 |
+
return np.array(
|
165 |
+
[2 * x[0], np.cos(x[0]) ** -2, np.exp(x[0])]).reshape(-1, 1)
|
166 |
+
|
167 |
+
def fun_vector_scalar(self, x):
|
168 |
+
return np.sin(x[0] * x[1]) * np.log(x[0])
|
169 |
+
|
170 |
+
def wrong_dimensions_fun(self, x):
|
171 |
+
return np.array([x**2, np.tan(x), np.exp(x)])
|
172 |
+
|
173 |
+
def jac_vector_scalar(self, x):
|
174 |
+
return np.array([
|
175 |
+
x[1] * np.cos(x[0] * x[1]) * np.log(x[0]) +
|
176 |
+
np.sin(x[0] * x[1]) / x[0],
|
177 |
+
x[0] * np.cos(x[0] * x[1]) * np.log(x[0])
|
178 |
+
])
|
179 |
+
|
180 |
+
def fun_vector_vector(self, x):
|
181 |
+
return np.array([
|
182 |
+
x[0] * np.sin(x[1]),
|
183 |
+
x[1] * np.cos(x[0]),
|
184 |
+
x[0] ** 3 * x[1] ** -0.5
|
185 |
+
])
|
186 |
+
|
187 |
+
def jac_vector_vector(self, x):
|
188 |
+
return np.array([
|
189 |
+
[np.sin(x[1]), x[0] * np.cos(x[1])],
|
190 |
+
[-x[1] * np.sin(x[0]), np.cos(x[0])],
|
191 |
+
[3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5]
|
192 |
+
])
|
193 |
+
|
194 |
+
def fun_parametrized(self, x, c0, c1=1.0):
|
195 |
+
return np.array([np.exp(c0 * x[0]), np.exp(c1 * x[1])])
|
196 |
+
|
197 |
+
def jac_parametrized(self, x, c0, c1=0.1):
|
198 |
+
return np.array([
|
199 |
+
[c0 * np.exp(c0 * x[0]), 0],
|
200 |
+
[0, c1 * np.exp(c1 * x[1])]
|
201 |
+
])
|
202 |
+
|
203 |
+
def fun_with_nan(self, x):
|
204 |
+
return x if np.abs(x) <= 1e-8 else np.nan
|
205 |
+
|
206 |
+
def jac_with_nan(self, x):
|
207 |
+
return 1.0 if np.abs(x) <= 1e-8 else np.nan
|
208 |
+
|
209 |
+
def fun_zero_jacobian(self, x):
|
210 |
+
return np.array([x[0] * x[1], np.cos(x[0] * x[1])])
|
211 |
+
|
212 |
+
def jac_zero_jacobian(self, x):
|
213 |
+
return np.array([
|
214 |
+
[x[1], x[0]],
|
215 |
+
[-x[1] * np.sin(x[0] * x[1]), -x[0] * np.sin(x[0] * x[1])]
|
216 |
+
])
|
217 |
+
|
218 |
+
def jac_non_numpy(self, x):
|
219 |
+
# x can be a scalar or an array [val].
|
220 |
+
# Cast to true scalar before handing over to math.exp
|
221 |
+
xp = np.asarray(x).item()
|
222 |
+
return math.exp(xp)
|
223 |
+
|
224 |
+
def test_scalar_scalar(self):
|
225 |
+
x0 = 1.0
|
226 |
+
jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0,
|
227 |
+
method='2-point')
|
228 |
+
jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0)
|
229 |
+
jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0,
|
230 |
+
method='cs')
|
231 |
+
jac_true = self.jac_scalar_scalar(x0)
|
232 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
|
233 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
|
234 |
+
assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
|
235 |
+
|
236 |
+
def test_scalar_scalar_abs_step(self):
|
237 |
+
# can approx_derivative use abs_step?
|
238 |
+
x0 = 1.0
|
239 |
+
jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0,
|
240 |
+
method='2-point', abs_step=1.49e-8)
|
241 |
+
jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0,
|
242 |
+
abs_step=1.49e-8)
|
243 |
+
jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0,
|
244 |
+
method='cs', abs_step=1.49e-8)
|
245 |
+
jac_true = self.jac_scalar_scalar(x0)
|
246 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
|
247 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
|
248 |
+
assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
|
249 |
+
|
250 |
+
def test_scalar_vector(self):
|
251 |
+
x0 = 0.5
|
252 |
+
jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0,
|
253 |
+
method='2-point')
|
254 |
+
jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0)
|
255 |
+
jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0,
|
256 |
+
method='cs')
|
257 |
+
jac_true = self.jac_scalar_vector(np.atleast_1d(x0))
|
258 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
|
259 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
|
260 |
+
assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
|
261 |
+
|
262 |
+
def test_vector_scalar(self):
|
263 |
+
x0 = np.array([100.0, -0.5])
|
264 |
+
jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0,
|
265 |
+
method='2-point')
|
266 |
+
jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0)
|
267 |
+
jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0,
|
268 |
+
method='cs')
|
269 |
+
jac_true = self.jac_vector_scalar(x0)
|
270 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
|
271 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-7)
|
272 |
+
assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
|
273 |
+
|
274 |
+
def test_vector_scalar_abs_step(self):
|
275 |
+
# can approx_derivative use abs_step?
|
276 |
+
x0 = np.array([100.0, -0.5])
|
277 |
+
jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0,
|
278 |
+
method='2-point', abs_step=1.49e-8)
|
279 |
+
jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0,
|
280 |
+
abs_step=1.49e-8, rel_step=np.inf)
|
281 |
+
jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0,
|
282 |
+
method='cs', abs_step=1.49e-8)
|
283 |
+
jac_true = self.jac_vector_scalar(x0)
|
284 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
|
285 |
+
assert_allclose(jac_diff_3, jac_true, rtol=3e-9)
|
286 |
+
assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
|
287 |
+
|
288 |
+
def test_vector_vector(self):
|
289 |
+
x0 = np.array([-100.0, 0.2])
|
290 |
+
jac_diff_2 = approx_derivative(self.fun_vector_vector, x0,
|
291 |
+
method='2-point')
|
292 |
+
jac_diff_3 = approx_derivative(self.fun_vector_vector, x0)
|
293 |
+
jac_diff_4 = approx_derivative(self.fun_vector_vector, x0,
|
294 |
+
method='cs')
|
295 |
+
jac_true = self.jac_vector_vector(x0)
|
296 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-5)
|
297 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-6)
|
298 |
+
assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
|
299 |
+
|
300 |
+
def test_wrong_dimensions(self):
|
301 |
+
x0 = 1.0
|
302 |
+
assert_raises(RuntimeError, approx_derivative,
|
303 |
+
self.wrong_dimensions_fun, x0)
|
304 |
+
f0 = self.wrong_dimensions_fun(np.atleast_1d(x0))
|
305 |
+
assert_raises(ValueError, approx_derivative,
|
306 |
+
self.wrong_dimensions_fun, x0, f0=f0)
|
307 |
+
|
308 |
+
def test_custom_rel_step(self):
|
309 |
+
x0 = np.array([-0.1, 0.1])
|
310 |
+
jac_diff_2 = approx_derivative(self.fun_vector_vector, x0,
|
311 |
+
method='2-point', rel_step=1e-4)
|
312 |
+
jac_diff_3 = approx_derivative(self.fun_vector_vector, x0,
|
313 |
+
rel_step=1e-4)
|
314 |
+
jac_true = self.jac_vector_vector(x0)
|
315 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-2)
|
316 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-4)
|
317 |
+
|
318 |
+
def test_options(self):
|
319 |
+
x0 = np.array([1.0, 1.0])
|
320 |
+
c0 = -1.0
|
321 |
+
c1 = 1.0
|
322 |
+
lb = 0.0
|
323 |
+
ub = 2.0
|
324 |
+
f0 = self.fun_parametrized(x0, c0, c1=c1)
|
325 |
+
rel_step = np.array([-1e-6, 1e-7])
|
326 |
+
jac_true = self.jac_parametrized(x0, c0, c1)
|
327 |
+
jac_diff_2 = approx_derivative(
|
328 |
+
self.fun_parametrized, x0, method='2-point', rel_step=rel_step,
|
329 |
+
f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub))
|
330 |
+
jac_diff_3 = approx_derivative(
|
331 |
+
self.fun_parametrized, x0, rel_step=rel_step,
|
332 |
+
f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub))
|
333 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
|
334 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
|
335 |
+
|
336 |
+
def test_with_bounds_2_point(self):
|
337 |
+
lb = -np.ones(2)
|
338 |
+
ub = np.ones(2)
|
339 |
+
|
340 |
+
x0 = np.array([-2.0, 0.2])
|
341 |
+
assert_raises(ValueError, approx_derivative,
|
342 |
+
self.fun_vector_vector, x0, bounds=(lb, ub))
|
343 |
+
|
344 |
+
x0 = np.array([-1.0, 1.0])
|
345 |
+
jac_diff = approx_derivative(self.fun_vector_vector, x0,
|
346 |
+
method='2-point', bounds=(lb, ub))
|
347 |
+
jac_true = self.jac_vector_vector(x0)
|
348 |
+
assert_allclose(jac_diff, jac_true, rtol=1e-6)
|
349 |
+
|
350 |
+
def test_with_bounds_3_point(self):
|
351 |
+
lb = np.array([1.0, 1.0])
|
352 |
+
ub = np.array([2.0, 2.0])
|
353 |
+
|
354 |
+
x0 = np.array([1.0, 2.0])
|
355 |
+
jac_true = self.jac_vector_vector(x0)
|
356 |
+
|
357 |
+
jac_diff = approx_derivative(self.fun_vector_vector, x0)
|
358 |
+
assert_allclose(jac_diff, jac_true, rtol=1e-9)
|
359 |
+
|
360 |
+
jac_diff = approx_derivative(self.fun_vector_vector, x0,
|
361 |
+
bounds=(lb, np.inf))
|
362 |
+
assert_allclose(jac_diff, jac_true, rtol=1e-9)
|
363 |
+
|
364 |
+
jac_diff = approx_derivative(self.fun_vector_vector, x0,
|
365 |
+
bounds=(-np.inf, ub))
|
366 |
+
assert_allclose(jac_diff, jac_true, rtol=1e-9)
|
367 |
+
|
368 |
+
jac_diff = approx_derivative(self.fun_vector_vector, x0,
|
369 |
+
bounds=(lb, ub))
|
370 |
+
assert_allclose(jac_diff, jac_true, rtol=1e-9)
|
371 |
+
|
372 |
+
def test_tight_bounds(self):
|
373 |
+
x0 = np.array([10.0, 10.0])
|
374 |
+
lb = x0 - 3e-9
|
375 |
+
ub = x0 + 2e-9
|
376 |
+
jac_true = self.jac_vector_vector(x0)
|
377 |
+
jac_diff = approx_derivative(
|
378 |
+
self.fun_vector_vector, x0, method='2-point', bounds=(lb, ub))
|
379 |
+
assert_allclose(jac_diff, jac_true, rtol=1e-6)
|
380 |
+
jac_diff = approx_derivative(
|
381 |
+
self.fun_vector_vector, x0, method='2-point',
|
382 |
+
rel_step=1e-6, bounds=(lb, ub))
|
383 |
+
assert_allclose(jac_diff, jac_true, rtol=1e-6)
|
384 |
+
|
385 |
+
jac_diff = approx_derivative(
|
386 |
+
self.fun_vector_vector, x0, bounds=(lb, ub))
|
387 |
+
assert_allclose(jac_diff, jac_true, rtol=1e-6)
|
388 |
+
jac_diff = approx_derivative(
|
389 |
+
self.fun_vector_vector, x0, rel_step=1e-6, bounds=(lb, ub))
|
390 |
+
assert_allclose(jac_true, jac_diff, rtol=1e-6)
|
391 |
+
|
392 |
+
def test_bound_switches(self):
|
393 |
+
lb = -1e-8
|
394 |
+
ub = 1e-8
|
395 |
+
x0 = 0.0
|
396 |
+
jac_true = self.jac_with_nan(x0)
|
397 |
+
jac_diff_2 = approx_derivative(
|
398 |
+
self.fun_with_nan, x0, method='2-point', rel_step=1e-6,
|
399 |
+
bounds=(lb, ub))
|
400 |
+
jac_diff_3 = approx_derivative(
|
401 |
+
self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub))
|
402 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
|
403 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
|
404 |
+
|
405 |
+
x0 = 1e-8
|
406 |
+
jac_true = self.jac_with_nan(x0)
|
407 |
+
jac_diff_2 = approx_derivative(
|
408 |
+
self.fun_with_nan, x0, method='2-point', rel_step=1e-6,
|
409 |
+
bounds=(lb, ub))
|
410 |
+
jac_diff_3 = approx_derivative(
|
411 |
+
self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub))
|
412 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
|
413 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
|
414 |
+
|
415 |
+
def test_non_numpy(self):
|
416 |
+
x0 = 1.0
|
417 |
+
jac_true = self.jac_non_numpy(x0)
|
418 |
+
jac_diff_2 = approx_derivative(self.jac_non_numpy, x0,
|
419 |
+
method='2-point')
|
420 |
+
jac_diff_3 = approx_derivative(self.jac_non_numpy, x0)
|
421 |
+
assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
|
422 |
+
assert_allclose(jac_diff_3, jac_true, rtol=1e-8)
|
423 |
+
|
424 |
+
# math.exp cannot handle complex arguments, hence this raises
|
425 |
+
assert_raises(TypeError, approx_derivative, self.jac_non_numpy, x0,
|
426 |
+
**dict(method='cs'))
|
427 |
+
|
428 |
+
def test_fp(self):
|
429 |
+
# checks that approx_derivative works for FP size other than 64.
|
430 |
+
# Example is derived from the minimal working example in gh12991.
|
431 |
+
np.random.seed(1)
|
432 |
+
|
433 |
+
def func(p, x):
|
434 |
+
return p[0] + p[1] * x
|
435 |
+
|
436 |
+
def err(p, x, y):
|
437 |
+
return func(p, x) - y
|
438 |
+
|
439 |
+
x = np.linspace(0, 1, 100, dtype=np.float64)
|
440 |
+
y = np.random.random(100).astype(np.float64)
|
441 |
+
p0 = np.array([-1.0, -1.0])
|
442 |
+
|
443 |
+
jac_fp64 = approx_derivative(err, p0, method='2-point', args=(x, y))
|
444 |
+
|
445 |
+
# parameter vector is float32, func output is float64
|
446 |
+
jac_fp = approx_derivative(err, p0.astype(np.float32),
|
447 |
+
method='2-point', args=(x, y))
|
448 |
+
assert err(p0, x, y).dtype == np.float64
|
449 |
+
assert_allclose(jac_fp, jac_fp64, atol=1e-3)
|
450 |
+
|
451 |
+
# parameter vector is float64, func output is float32
|
452 |
+
def err_fp32(p):
|
453 |
+
assert p.dtype == np.float32
|
454 |
+
return err(p, x, y).astype(np.float32)
|
455 |
+
|
456 |
+
jac_fp = approx_derivative(err_fp32, p0.astype(np.float32),
|
457 |
+
method='2-point')
|
458 |
+
assert_allclose(jac_fp, jac_fp64, atol=1e-3)
|
459 |
+
|
460 |
+
# check upper bound of error on the derivative for 2-point
|
461 |
+
def f(x):
|
462 |
+
return np.sin(x)
|
463 |
+
def g(x):
|
464 |
+
return np.cos(x)
|
465 |
+
def hess(x):
|
466 |
+
return -np.sin(x)
|
467 |
+
|
468 |
+
def calc_atol(h, x0, f, hess, EPS):
|
469 |
+
# truncation error
|
470 |
+
t0 = h / 2 * max(np.abs(hess(x0)), np.abs(hess(x0 + h)))
|
471 |
+
# roundoff error. There may be a divisor (>1) missing from
|
472 |
+
# the following line, so this contribution is possibly
|
473 |
+
# overestimated
|
474 |
+
t1 = EPS / h * max(np.abs(f(x0)), np.abs(f(x0 + h)))
|
475 |
+
return t0 + t1
|
476 |
+
|
477 |
+
for dtype in [np.float16, np.float32, np.float64]:
|
478 |
+
EPS = np.finfo(dtype).eps
|
479 |
+
x0 = np.array(1.0).astype(dtype)
|
480 |
+
h = _compute_absolute_step(None, x0, f(x0), '2-point')
|
481 |
+
atol = calc_atol(h, x0, f, hess, EPS)
|
482 |
+
err = approx_derivative(f, x0, method='2-point',
|
483 |
+
abs_step=h) - g(x0)
|
484 |
+
assert abs(err) < atol
|
485 |
+
|
486 |
+
def test_check_derivative(self):
|
487 |
+
x0 = np.array([-10.0, 10])
|
488 |
+
accuracy = check_derivative(self.fun_vector_vector,
|
489 |
+
self.jac_vector_vector, x0)
|
490 |
+
assert_(accuracy < 1e-9)
|
491 |
+
accuracy = check_derivative(self.fun_vector_vector,
|
492 |
+
self.jac_vector_vector, x0)
|
493 |
+
assert_(accuracy < 1e-6)
|
494 |
+
|
495 |
+
x0 = np.array([0.0, 0.0])
|
496 |
+
accuracy = check_derivative(self.fun_zero_jacobian,
|
497 |
+
self.jac_zero_jacobian, x0)
|
498 |
+
assert_(accuracy == 0)
|
499 |
+
accuracy = check_derivative(self.fun_zero_jacobian,
|
500 |
+
self.jac_zero_jacobian, x0)
|
501 |
+
assert_(accuracy == 0)
|
502 |
+
|
503 |
+
|
504 |
+
class TestApproxDerivativeSparse:
|
505 |
+
# Example from Numerical Optimization 2nd edition, p. 198.
|
506 |
+
def setup_method(self):
|
507 |
+
np.random.seed(0)
|
508 |
+
self.n = 50
|
509 |
+
self.lb = -0.1 * (1 + np.arange(self.n))
|
510 |
+
self.ub = 0.1 * (1 + np.arange(self.n))
|
511 |
+
self.x0 = np.empty(self.n)
|
512 |
+
self.x0[::2] = (1 - 1e-7) * self.lb[::2]
|
513 |
+
self.x0[1::2] = (1 - 1e-7) * self.ub[1::2]
|
514 |
+
|
515 |
+
self.J_true = self.jac(self.x0)
|
516 |
+
|
517 |
+
def fun(self, x):
|
518 |
+
e = x[1:]**3 - x[:-1]**2
|
519 |
+
return np.hstack((0, 3 * e)) + np.hstack((2 * e, 0))
|
520 |
+
|
521 |
+
def jac(self, x):
|
522 |
+
n = x.size
|
523 |
+
J = np.zeros((n, n))
|
524 |
+
J[0, 0] = -4 * x[0]
|
525 |
+
J[0, 1] = 6 * x[1]**2
|
526 |
+
for i in range(1, n - 1):
|
527 |
+
J[i, i - 1] = -6 * x[i-1]
|
528 |
+
J[i, i] = 9 * x[i]**2 - 4 * x[i]
|
529 |
+
J[i, i + 1] = 6 * x[i+1]**2
|
530 |
+
J[-1, -1] = 9 * x[-1]**2
|
531 |
+
J[-1, -2] = -6 * x[-2]
|
532 |
+
|
533 |
+
return J
|
534 |
+
|
535 |
+
def structure(self, n):
|
536 |
+
A = np.zeros((n, n), dtype=int)
|
537 |
+
A[0, 0] = 1
|
538 |
+
A[0, 1] = 1
|
539 |
+
for i in range(1, n - 1):
|
540 |
+
A[i, i - 1: i + 2] = 1
|
541 |
+
A[-1, -1] = 1
|
542 |
+
A[-1, -2] = 1
|
543 |
+
|
544 |
+
return A
|
545 |
+
|
546 |
+
def test_all(self):
|
547 |
+
A = self.structure(self.n)
|
548 |
+
order = np.arange(self.n)
|
549 |
+
groups_1 = group_columns(A, order)
|
550 |
+
np.random.shuffle(order)
|
551 |
+
groups_2 = group_columns(A, order)
|
552 |
+
|
553 |
+
for method, groups, l, u in product(
|
554 |
+
['2-point', '3-point', 'cs'], [groups_1, groups_2],
|
555 |
+
[-np.inf, self.lb], [np.inf, self.ub]):
|
556 |
+
J = approx_derivative(self.fun, self.x0, method=method,
|
557 |
+
bounds=(l, u), sparsity=(A, groups))
|
558 |
+
assert_(isinstance(J, csr_matrix))
|
559 |
+
assert_allclose(J.toarray(), self.J_true, rtol=1e-6)
|
560 |
+
|
561 |
+
rel_step = np.full_like(self.x0, 1e-8)
|
562 |
+
rel_step[::2] *= -1
|
563 |
+
J = approx_derivative(self.fun, self.x0, method=method,
|
564 |
+
rel_step=rel_step, sparsity=(A, groups))
|
565 |
+
assert_allclose(J.toarray(), self.J_true, rtol=1e-5)
|
566 |
+
|
567 |
+
def test_no_precomputed_groups(self):
|
568 |
+
A = self.structure(self.n)
|
569 |
+
J = approx_derivative(self.fun, self.x0, sparsity=A)
|
570 |
+
assert_allclose(J.toarray(), self.J_true, rtol=1e-6)
|
571 |
+
|
572 |
+
def test_equivalence(self):
|
573 |
+
structure = np.ones((self.n, self.n), dtype=int)
|
574 |
+
groups = np.arange(self.n)
|
575 |
+
for method in ['2-point', '3-point', 'cs']:
|
576 |
+
J_dense = approx_derivative(self.fun, self.x0, method=method)
|
577 |
+
J_sparse = approx_derivative(
|
578 |
+
self.fun, self.x0, sparsity=(structure, groups), method=method)
|
579 |
+
assert_allclose(J_dense, J_sparse.toarray(),
|
580 |
+
rtol=5e-16, atol=7e-15)
|
581 |
+
|
582 |
+
def test_check_derivative(self):
|
583 |
+
def jac(x):
|
584 |
+
return csr_matrix(self.jac(x))
|
585 |
+
|
586 |
+
accuracy = check_derivative(self.fun, jac, self.x0,
|
587 |
+
bounds=(self.lb, self.ub))
|
588 |
+
assert_(accuracy < 1e-9)
|
589 |
+
|
590 |
+
accuracy = check_derivative(self.fun, jac, self.x0,
|
591 |
+
bounds=(self.lb, self.ub))
|
592 |
+
assert_(accuracy < 1e-9)
|
593 |
+
|
594 |
+
|
595 |
+
class TestApproxDerivativeLinearOperator:
|
596 |
+
|
597 |
+
def fun_scalar_scalar(self, x):
|
598 |
+
return np.sinh(x)
|
599 |
+
|
600 |
+
def jac_scalar_scalar(self, x):
|
601 |
+
return np.cosh(x)
|
602 |
+
|
603 |
+
def fun_scalar_vector(self, x):
|
604 |
+
return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])])
|
605 |
+
|
606 |
+
def jac_scalar_vector(self, x):
|
607 |
+
return np.array(
|
608 |
+
[2 * x[0], np.cos(x[0]) ** -2, np.exp(x[0])]).reshape(-1, 1)
|
609 |
+
|
610 |
+
def fun_vector_scalar(self, x):
|
611 |
+
return np.sin(x[0] * x[1]) * np.log(x[0])
|
612 |
+
|
613 |
+
def jac_vector_scalar(self, x):
|
614 |
+
return np.array([
|
615 |
+
x[1] * np.cos(x[0] * x[1]) * np.log(x[0]) +
|
616 |
+
np.sin(x[0] * x[1]) / x[0],
|
617 |
+
x[0] * np.cos(x[0] * x[1]) * np.log(x[0])
|
618 |
+
])
|
619 |
+
|
620 |
+
def fun_vector_vector(self, x):
|
621 |
+
return np.array([
|
622 |
+
x[0] * np.sin(x[1]),
|
623 |
+
x[1] * np.cos(x[0]),
|
624 |
+
x[0] ** 3 * x[1] ** -0.5
|
625 |
+
])
|
626 |
+
|
627 |
+
def jac_vector_vector(self, x):
|
628 |
+
return np.array([
|
629 |
+
[np.sin(x[1]), x[0] * np.cos(x[1])],
|
630 |
+
[-x[1] * np.sin(x[0]), np.cos(x[0])],
|
631 |
+
[3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5]
|
632 |
+
])
|
633 |
+
|
634 |
+
def test_scalar_scalar(self):
|
635 |
+
x0 = 1.0
|
636 |
+
jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0,
|
637 |
+
method='2-point',
|
638 |
+
as_linear_operator=True)
|
639 |
+
jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0,
|
640 |
+
as_linear_operator=True)
|
641 |
+
jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0,
|
642 |
+
method='cs',
|
643 |
+
as_linear_operator=True)
|
644 |
+
jac_true = self.jac_scalar_scalar(x0)
|
645 |
+
np.random.seed(1)
|
646 |
+
for i in range(10):
|
647 |
+
p = np.random.uniform(-10, 10, size=(1,))
|
648 |
+
assert_allclose(jac_diff_2.dot(p), jac_true*p,
|
649 |
+
rtol=1e-5)
|
650 |
+
assert_allclose(jac_diff_3.dot(p), jac_true*p,
|
651 |
+
rtol=5e-6)
|
652 |
+
assert_allclose(jac_diff_4.dot(p), jac_true*p,
|
653 |
+
rtol=5e-6)
|
654 |
+
|
655 |
+
def test_scalar_vector(self):
|
656 |
+
x0 = 0.5
|
657 |
+
jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0,
|
658 |
+
method='2-point',
|
659 |
+
as_linear_operator=True)
|
660 |
+
jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0,
|
661 |
+
as_linear_operator=True)
|
662 |
+
jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0,
|
663 |
+
method='cs',
|
664 |
+
as_linear_operator=True)
|
665 |
+
jac_true = self.jac_scalar_vector(np.atleast_1d(x0))
|
666 |
+
np.random.seed(1)
|
667 |
+
for i in range(10):
|
668 |
+
p = np.random.uniform(-10, 10, size=(1,))
|
669 |
+
assert_allclose(jac_diff_2.dot(p), jac_true.dot(p),
|
670 |
+
rtol=1e-5)
|
671 |
+
assert_allclose(jac_diff_3.dot(p), jac_true.dot(p),
|
672 |
+
rtol=5e-6)
|
673 |
+
assert_allclose(jac_diff_4.dot(p), jac_true.dot(p),
|
674 |
+
rtol=5e-6)
|
675 |
+
|
676 |
+
def test_vector_scalar(self):
|
677 |
+
x0 = np.array([100.0, -0.5])
|
678 |
+
jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0,
|
679 |
+
method='2-point',
|
680 |
+
as_linear_operator=True)
|
681 |
+
jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0,
|
682 |
+
as_linear_operator=True)
|
683 |
+
jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0,
|
684 |
+
method='cs',
|
685 |
+
as_linear_operator=True)
|
686 |
+
jac_true = self.jac_vector_scalar(x0)
|
687 |
+
np.random.seed(1)
|
688 |
+
for i in range(10):
|
689 |
+
p = np.random.uniform(-10, 10, size=x0.shape)
|
690 |
+
assert_allclose(jac_diff_2.dot(p), np.atleast_1d(jac_true.dot(p)),
|
691 |
+
rtol=1e-5)
|
692 |
+
assert_allclose(jac_diff_3.dot(p), np.atleast_1d(jac_true.dot(p)),
|
693 |
+
rtol=5e-6)
|
694 |
+
assert_allclose(jac_diff_4.dot(p), np.atleast_1d(jac_true.dot(p)),
|
695 |
+
rtol=1e-7)
|
696 |
+
|
697 |
+
def test_vector_vector(self):
|
698 |
+
x0 = np.array([-100.0, 0.2])
|
699 |
+
jac_diff_2 = approx_derivative(self.fun_vector_vector, x0,
|
700 |
+
method='2-point',
|
701 |
+
as_linear_operator=True)
|
702 |
+
jac_diff_3 = approx_derivative(self.fun_vector_vector, x0,
|
703 |
+
as_linear_operator=True)
|
704 |
+
jac_diff_4 = approx_derivative(self.fun_vector_vector, x0,
|
705 |
+
method='cs',
|
706 |
+
as_linear_operator=True)
|
707 |
+
jac_true = self.jac_vector_vector(x0)
|
708 |
+
np.random.seed(1)
|
709 |
+
for i in range(10):
|
710 |
+
p = np.random.uniform(-10, 10, size=x0.shape)
|
711 |
+
assert_allclose(jac_diff_2.dot(p), jac_true.dot(p), rtol=1e-5)
|
712 |
+
assert_allclose(jac_diff_3.dot(p), jac_true.dot(p), rtol=1e-6)
|
713 |
+
assert_allclose(jac_diff_4.dot(p), jac_true.dot(p), rtol=1e-7)
|
714 |
+
|
715 |
+
def test_exception(self):
|
716 |
+
x0 = np.array([-100.0, 0.2])
|
717 |
+
assert_raises(ValueError, approx_derivative,
|
718 |
+
self.fun_vector_vector, x0,
|
719 |
+
method='2-point', bounds=(1, np.inf))
|
720 |
+
|
721 |
+
|
722 |
+
def test_absolute_step_sign():
|
723 |
+
# test for gh12487
|
724 |
+
# if an absolute step is specified for 2-point differences make sure that
|
725 |
+
# the side corresponds to the step. i.e. if step is positive then forward
|
726 |
+
# differences should be used, if step is negative then backwards
|
727 |
+
# differences should be used.
|
728 |
+
|
729 |
+
# function has double discontinuity at x = [-1, -1]
|
730 |
+
# first component is \/, second component is /\
|
731 |
+
def f(x):
|
732 |
+
return -np.abs(x[0] + 1) + np.abs(x[1] + 1)
|
733 |
+
|
734 |
+
# check that the forward difference is used
|
735 |
+
grad = approx_derivative(f, [-1, -1], method='2-point', abs_step=1e-8)
|
736 |
+
assert_allclose(grad, [-1.0, 1.0])
|
737 |
+
|
738 |
+
# check that the backwards difference is used
|
739 |
+
grad = approx_derivative(f, [-1, -1], method='2-point', abs_step=-1e-8)
|
740 |
+
assert_allclose(grad, [1.0, -1.0])
|
741 |
+
|
742 |
+
# check that the forwards difference is used with a step for both
|
743 |
+
# parameters
|
744 |
+
grad = approx_derivative(
|
745 |
+
f, [-1, -1], method='2-point', abs_step=[1e-8, 1e-8]
|
746 |
+
)
|
747 |
+
assert_allclose(grad, [-1.0, 1.0])
|
748 |
+
|
749 |
+
# check that we can mix forward/backwards steps.
|
750 |
+
grad = approx_derivative(
|
751 |
+
f, [-1, -1], method='2-point', abs_step=[1e-8, -1e-8]
|
752 |
+
)
|
753 |
+
assert_allclose(grad, [-1.0, -1.0])
|
754 |
+
grad = approx_derivative(
|
755 |
+
f, [-1, -1], method='2-point', abs_step=[-1e-8, 1e-8]
|
756 |
+
)
|
757 |
+
assert_allclose(grad, [1.0, 1.0])
|
758 |
+
|
759 |
+
# the forward step should reverse to a backwards step if it runs into a
|
760 |
+
# bound
|
761 |
+
# This is kind of tested in TestAdjustSchemeToBounds, but only for a lower level
|
762 |
+
# function.
|
763 |
+
grad = approx_derivative(
|
764 |
+
f, [-1, -1], method='2-point', abs_step=1e-8,
|
765 |
+
bounds=(-np.inf, -1)
|
766 |
+
)
|
767 |
+
assert_allclose(grad, [1.0, -1.0])
|
768 |
+
|
769 |
+
grad = approx_derivative(
|
770 |
+
f, [-1, -1], method='2-point', abs_step=-1e-8, bounds=(-1, np.inf)
|
771 |
+
)
|
772 |
+
assert_allclose(grad, [-1.0, 1.0])
|
773 |
+
|
774 |
+
|
775 |
+
def test__compute_absolute_step():
|
776 |
+
# tests calculation of absolute step from rel_step
|
777 |
+
methods = ['2-point', '3-point', 'cs']
|
778 |
+
|
779 |
+
x0 = np.array([1e-5, 0, 1, 1e5])
|
780 |
+
|
781 |
+
EPS = np.finfo(np.float64).eps
|
782 |
+
relative_step = {
|
783 |
+
"2-point": EPS**0.5,
|
784 |
+
"3-point": EPS**(1/3),
|
785 |
+
"cs": EPS**0.5
|
786 |
+
}
|
787 |
+
f0 = np.array(1.0)
|
788 |
+
|
789 |
+
for method in methods:
|
790 |
+
rel_step = relative_step[method]
|
791 |
+
correct_step = np.array([rel_step,
|
792 |
+
rel_step * 1.,
|
793 |
+
rel_step * 1.,
|
794 |
+
rel_step * np.abs(x0[3])])
|
795 |
+
|
796 |
+
abs_step = _compute_absolute_step(None, x0, f0, method)
|
797 |
+
assert_allclose(abs_step, correct_step)
|
798 |
+
|
799 |
+
sign_x0 = (-x0 >= 0).astype(float) * 2 - 1
|
800 |
+
abs_step = _compute_absolute_step(None, -x0, f0, method)
|
801 |
+
assert_allclose(abs_step, sign_x0 * correct_step)
|
802 |
+
|
803 |
+
# if a relative step is provided it should be used
|
804 |
+
rel_step = np.array([0.1, 1, 10, 100])
|
805 |
+
correct_step = np.array([rel_step[0] * x0[0],
|
806 |
+
relative_step['2-point'],
|
807 |
+
rel_step[2] * 1.,
|
808 |
+
rel_step[3] * np.abs(x0[3])])
|
809 |
+
|
810 |
+
abs_step = _compute_absolute_step(rel_step, x0, f0, '2-point')
|
811 |
+
assert_allclose(abs_step, correct_step)
|
812 |
+
|
813 |
+
sign_x0 = (-x0 >= 0).astype(float) * 2 - 1
|
814 |
+
abs_step = _compute_absolute_step(rel_step, -x0, f0, '2-point')
|
815 |
+
assert_allclose(abs_step, sign_x0 * correct_step)
|