Last active
August 13, 2017 13:40
-
-
Save antonior92/f3a37a2f23ca02aa7138ee5a98904a61 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example | |
from __future__ import division, print_function, absolute_import | |
import numpy as np | |
from scipy.optimize import minimize_constrained, NonlinearConstraint, BoxConstraint | |
# Define objective function and derivatives | |
fun = lambda x: 1/2*(x[0] - 2)**2 + 1/2*(x[1] - 1/2)**2 | |
grad = lambda x: np.array([x[0] - 2, x[1] - 1/2]) | |
hess = lambda x: np.eye(2) | |
# Define nonlinear constraint | |
c = lambda x: np.array([1/(x[0] + 1) - x[1] - 1/4,]) | |
c_jac = lambda x: np.array([[-1/(x[0] + 1)**2, -1]]) | |
c_hess = lambda x, v: 2*v[0]*np.array([[1/(x[0] + 1)**3, 0], [0, 0]]) | |
nonlinear = NonlinearConstraint(c, c_jac, c_hess, ("greater", [0])) | |
# Define box constraint | |
box = BoxConstraint(("greater", [0, 0])) | |
# Define initial point | |
x0 = np.array([0, 0]) | |
# Apply solver | |
result = minimize_constrained(fun, x0, grad, hess, (nonlinear, box)) | |
# Print results | |
print('x* = ' + str(result.x)) | |
print('optimality = ' + str(result.optimality)) | |
print('c violation = ' + str(result.constr_violation)) | |
print('niter = ' + str(result.niter)) | |
print('f evals = ' + str(result.nfev)) | |
print('CG iters = ' + str(result.cg_niter)) | |
print('total time = ' + str(result.execution_time)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment