Skip to content

Commit

Permalink
Test: Rework Python test
Browse files Browse the repository at this point in the history
  • Loading branch information
jschueller committed Oct 25, 2024
1 parent 7905a5d commit 10e104a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
8 changes: 6 additions & 2 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,12 @@ if (Python_FOUND AND NUMPY_FOUND AND (SWIG_FOUND OR (EXISTS ${PROJECT_SOURCE_DIR
set (PYINSTALLCHECK_ENVIRONMENT "LD_LIBRARY_PATH=${PROJECT_BINARY_DIR}/src/swig"
"PYTHONPATH=${PROJECT_BINARY_DIR}/src/swig"
)
add_test (NAME test_python COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/t_python.py)
set_tests_properties (test_python PROPERTIES ENVIRONMENT "${PYINSTALLCHECK_ENVIRONMENT}")

foreach (algo_index 24 25 31 40)
add_test (NAME test_python${algo_index} COMMAND ${Python_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/t_python.py ${algo_index})
set_tests_properties (test_python${algo_index} PROPERTIES ENVIRONMENT "${PYINSTALLCHECK_ENVIRONMENT}")
endforeach()

endif ()

if (OCTAVE_FOUND)
Expand Down
18 changes: 11 additions & 7 deletions test/t_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import nlopt
import math as m
import sys


def myfunc(x, grad):
Expand All @@ -16,17 +17,20 @@ def myconstraint(x, grad, a, b):
grad[1] = -1.0
return (a*x[0] + b)**3 - x[1]

opt = nlopt.opt(nlopt.LD_MMA, 2)
opt.set_lower_bounds([-float('inf'), 0])
algo = nlopt.LD_MMA if len(sys.argv) < 2 else int(sys.argv[1])
opt = nlopt.opt(algo, 2)
print(f"algo: {opt.get_algorithm_name()}")
opt.set_lower_bounds([-float('inf'), 1e-6])
opt.set_min_objective(myfunc)
opt.add_inequality_constraint(lambda x, grad: myconstraint(x,grad, 2, 0), 1e-8)
opt.add_inequality_constraint(lambda x, grad: myconstraint(x,grad, -1, 1), 1e-8)
opt.set_xtol_rel(1e-4)
x0 = [1.234, 5.678]
x = opt.optimize(x0)
minf = opt.last_optimum_value()
print('optimum at ', x)
print('minimum value = ', minf)
print('result code = ', opt.last_optimize_result())
print('nevals = ', opt.get_numevals())
print('initial step =', opt.get_initial_step(x0))
print(f"optimum at {x}")
print(f"minimum value: {minf:.7g}")
print(f"result code: {opt.last_optimize_result()}")
print(f"nevals: {opt.get_numevals()}")
print(f"initial step: {opt.get_initial_step(x0)}")
assert m.fabs(minf - 0.5443310474) < 1e-3, "wrong optimum"

0 comments on commit 10e104a

Please sign in to comment.