chiark / gitweb /
strip
[nlopt.git] / test / t_python.py
1 #!/usr/bin/env python
2
3 from __future__ import print_function
4 import nlopt
5 import numpy as np
6
7
8 def myfunc(x, grad):
9     if grad.size > 0:
10         grad[0] = 0.0
11         grad[1] = 0.5 / np.sqrt(x[1])
12     return np.sqrt(x[1])
13
14 def myconstraint(x, grad, a, b):
15     if grad.size > 0:
16         grad[0] = 3 * a * (a*x[0] + b)**2
17         grad[1] = -1.0
18     return (a*x[0] + b)**3 - x[1]
19
20 opt = nlopt.opt(nlopt.LD_MMA, 2)
21 opt.set_lower_bounds([-float('inf'), 0])
22 opt.set_min_objective(myfunc)
23 opt.add_inequality_constraint(lambda x, grad: myconstraint(x,grad, 2, 0), 1e-8)
24 opt.add_inequality_constraint(lambda x, grad: myconstraint(x,grad, -1, 1), 1e-8)
25 opt.set_xtol_rel(1e-4)
26 x = opt.optimize([1.234, 5.678])
27 minf = opt.last_optimum_value()
28 print('optimum at ', x[0], x[1])
29 print('minimum value = ', minf)
30 print('result code = ', opt.last_optimize_result())
31 print('nevals = ', opt.get_numevals())