|
| 1 | +""" |
| 2 | +Copyright, the CVXPY authors |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +""" |
| 16 | +import numpy as np |
| 17 | +import pytest |
| 18 | + |
| 19 | +import cvxpy as cp |
| 20 | +from cvxpy.reductions.solvers.defines import INSTALLED_SOLVERS |
| 21 | + |
| 22 | +pytestmark = pytest.mark.skipif( |
| 23 | + 'IPOPT' not in INSTALLED_SOLVERS, |
| 24 | + reason="IPOPT is not installed") |
| 25 | + |
| 26 | + |
| 27 | +class TestNLPParameters: |
| 28 | + |
| 29 | + def test_scalar_parameter(self): |
| 30 | + """min p * x^2 + x, analytical solution: val = -1/(4p).""" |
| 31 | + x = cp.Variable() |
| 32 | + p = cp.Parameter(value=2.0) |
| 33 | + prob = cp.Problem(cp.Minimize(p * x**2 + x), [x >= -5]) |
| 34 | + |
| 35 | + prob.solve(nlp=True, solver='IPOPT') |
| 36 | + assert np.isclose(prob.value, -1.0 / (4 * 2.0), atol=1e-4) |
| 37 | + |
| 38 | + p.value = 4.0 |
| 39 | + prob.solve(nlp=True, solver='IPOPT') |
| 40 | + assert np.isclose(prob.value, -1.0 / (4 * 4.0), atol=1e-4) |
| 41 | + |
| 42 | + def test_vector_parameter(self): |
| 43 | + """min p @ x with simplex constraint.""" |
| 44 | + x = cp.Variable(2) |
| 45 | + p = cp.Parameter(2, value=[1.0, 2.0]) |
| 46 | + prob = cp.Problem(cp.Minimize(p @ x), [x >= 0, cp.sum(x) == 1]) |
| 47 | + |
| 48 | + prob.solve(nlp=True, solver='IPOPT') |
| 49 | + assert np.isclose(prob.value, 1.0, atol=1e-4) |
| 50 | + assert np.allclose(x.value, [1.0, 0.0], atol=1e-3) |
| 51 | + |
| 52 | + p.value = [3.0, 1.0] |
| 53 | + prob.solve(nlp=True, solver='IPOPT') |
| 54 | + assert np.isclose(prob.value, 1.0, atol=1e-4) |
| 55 | + assert np.allclose(x.value, [0.0, 1.0], atol=1e-3) |
| 56 | + |
| 57 | + def test_matrix_parameter(self): |
| 58 | + """min ||A @ x - b||^2 with parametric A.""" |
| 59 | + A = cp.Parameter((2, 2), value=np.eye(2)) |
| 60 | + x = cp.Variable(2) |
| 61 | + b = np.array([1.0, 2.0]) |
| 62 | + prob = cp.Problem( |
| 63 | + cp.Minimize(cp.sum_squares(A @ x - b)), |
| 64 | + [x >= -10, x <= 10]) |
| 65 | + |
| 66 | + prob.solve(nlp=True, solver='IPOPT') |
| 67 | + assert np.allclose(x.value, [1.0, 2.0], atol=1e-3) |
| 68 | + |
| 69 | + A.value = np.array([[0.0, 1.0], [1.0, 0.0]]) |
| 70 | + prob.solve(nlp=True, solver='IPOPT') |
| 71 | + assert np.allclose(x.value, [2.0, 1.0], atol=1e-3) |
0 commit comments