Skip to content

Commit f22c8bd

Browse files
committed
Test: Rework Python test
1 parent 04498ce commit f22c8bd

File tree

2 files changed

+21
-11
lines changed

2 files changed

+21
-11
lines changed

test/CMakeLists.txt

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,12 @@ if (Python_FOUND AND NUMPY_FOUND AND (SWIG_FOUND OR (EXISTS ${PROJECT_SOURCE_DIR
5959
set (PYINSTALLCHECK_ENVIRONMENT "LD_LIBRARY_PATH=${PROJECT_BINARY_DIR}/src/swig"
6060
"PYTHONPATH=${PROJECT_BINARY_DIR}/src/swig"
6161
)
62-
add_test (NAME test_python COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/t_python.py)
63-
set_tests_properties (test_python PROPERTIES ENVIRONMENT "${PYINSTALLCHECK_ENVIRONMENT}")
62+
63+
foreach (algo_index 24 25 31 40)
64+
add_test (NAME test_python${algo_index} COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/t_python.py ${algo_index})
65+
set_tests_properties (test_python${algo_index} PROPERTIES ENVIRONMENT "${PYINSTALLCHECK_ENVIRONMENT}")
66+
endforeach()
67+
6468
endif ()
6569

6670
if (OCTAVE_FOUND)

test/t_python.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import nlopt
44
import math as m
5+
import sys
56

67

78
def myfunc(x, grad):
@@ -10,23 +11,28 @@ def myfunc(x, grad):
1011
grad[1] = 0.5 / m.sqrt(x[1])
1112
return m.sqrt(x[1])
1213

14+
1315
def myconstraint(x, grad, a, b):
1416
if grad.size > 0:
1517
grad[0] = 3 * a * (a*x[0] + b)**2
1618
grad[1] = -1.0
1719
return (a*x[0] + b)**3 - x[1]
1820

19-
opt = nlopt.opt(nlopt.LD_MMA, 2)
20-
opt.set_lower_bounds([-float('inf'), 0])
21+
22+
algo = nlopt.LD_MMA if len(sys.argv) < 2 else int(sys.argv[1])
23+
opt = nlopt.opt(algo, 2)
24+
print(f"algo: {opt.get_algorithm_name()}")
25+
opt.set_lower_bounds([-float('inf'), 1e-6])
2126
opt.set_min_objective(myfunc)
22-
opt.add_inequality_constraint(lambda x, grad: myconstraint(x,grad, 2, 0), 1e-8)
23-
opt.add_inequality_constraint(lambda x, grad: myconstraint(x,grad, -1, 1), 1e-8)
27+
opt.add_inequality_constraint(lambda x, grad: myconstraint(x, grad, 2, 0), 1e-8)
28+
opt.add_inequality_constraint(lambda x, grad: myconstraint(x, grad, -1, 1), 1e-8)
2429
opt.set_xtol_rel(1e-4)
2530
x0 = [1.234, 5.678]
2631
x = opt.optimize(x0)
2732
minf = opt.last_optimum_value()
28-
print('optimum at ', x)
29-
print('minimum value = ', minf)
30-
print('result code = ', opt.last_optimize_result())
31-
print('nevals = ', opt.get_numevals())
32-
print('initial step =', opt.get_initial_step(x0))
33+
print(f"optimum at {x}")
34+
print(f"minimum value: {minf:.7g}")
35+
print(f"result code: {opt.last_optimize_result()}")
36+
print(f"nevals: {opt.get_numevals()}")
37+
print(f"initial step: {opt.get_initial_step(x0)}")
38+
assert m.fabs(minf - 0.544331) < 1e-3, "wrong optimum"

0 commit comments

Comments
 (0)