test_direct.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. """
  2. Unit test for DIRECT optimization algorithm.
  3. """
  4. from numpy.testing import (assert_allclose,
  5. assert_array_less)
  6. import pytest
  7. import numpy as np
  8. from scipy.optimize import direct, Bounds
  9. class TestDIRECT:
  10. def setup_method(self):
  11. self.fun_calls = 0
  12. self.bounds_sphere = 4*[(-2, 3)]
  13. self.optimum_sphere_pos = np.zeros((4, ))
  14. self.optimum_sphere = 0.0
  15. self.bounds_stylinski_tang = Bounds([-4., -4.], [4., 4.])
  16. self.maxiter = 1000
  17. # test functions
  18. def sphere(self, x):
  19. self.fun_calls += 1
  20. return np.square(x).sum()
  21. def inv(self, x):
  22. if np.sum(x) == 0:
  23. raise ZeroDivisionError()
  24. return 1/np.sum(x)
  25. def nan_fun(self, x):
  26. return np.nan
  27. def inf_fun(self, x):
  28. return np.inf
  29. def styblinski_tang(self, pos):
  30. x, y = pos
  31. return 0.5 * (x**4 - 16 * x**2 + 5 * x + y**4 - 16 * y**2 + 5 * y)
  32. @pytest.mark.parametrize("locally_biased", [True, False])
  33. def test_direct(self, locally_biased):
  34. res = direct(self.sphere, self.bounds_sphere,
  35. locally_biased=locally_biased)
  36. # test accuracy
  37. assert_allclose(res.x, self.optimum_sphere_pos,
  38. rtol=1e-3, atol=1e-3)
  39. assert_allclose(res.fun, self.optimum_sphere, atol=1e-5, rtol=1e-5)
  40. # test that result lies within bounds
  41. _bounds = np.asarray(self.bounds_sphere)
  42. assert_array_less(_bounds[:, 0], res.x)
  43. assert_array_less(res.x, _bounds[:, 1])
  44. # test number of function evaluations. Original DIRECT overshoots by
  45. # up to 500 evaluations in last iteration
  46. assert res.nfev <= 1000 * (len(self.bounds_sphere) + 1)
  47. # test that number of function evaluations is correct
  48. assert res.nfev == self.fun_calls
  49. # test that number of iterations is below supplied maximum
  50. assert res.nit <= self.maxiter
  51. @pytest.mark.parametrize("locally_biased", [True, False])
  52. def test_direct_callback(self, locally_biased):
  53. # test that callback does not change the result
  54. res = direct(self.sphere, self.bounds_sphere,
  55. locally_biased=locally_biased)
  56. def callback(x):
  57. x = 2*x
  58. dummy = np.square(x)
  59. print("DIRECT minimization algorithm callback test")
  60. return dummy
  61. res_callback = direct(self.sphere, self.bounds_sphere,
  62. locally_biased=locally_biased,
  63. callback=callback)
  64. assert_allclose(res.x, res_callback.x)
  65. assert res.nit == res_callback.nit
  66. assert res.nfev == res_callback.nfev
  67. assert res.status == res_callback.status
  68. assert res.success == res_callback.success
  69. assert res.fun == res_callback.fun
  70. assert_allclose(res.x, res_callback.x)
  71. assert res.message == res_callback.message
  72. # test accuracy
  73. assert_allclose(res_callback.x, self.optimum_sphere_pos,
  74. rtol=1e-3, atol=1e-3)
  75. assert_allclose(res_callback.fun, self.optimum_sphere,
  76. atol=1e-5, rtol=1e-5)
  77. @pytest.mark.parametrize("locally_biased", [True, False])
  78. def test_exception(self, locally_biased):
  79. bounds = 4*[(-10, 10)]
  80. with pytest.raises(ZeroDivisionError):
  81. direct(self.inv, bounds=bounds,
  82. locally_biased=locally_biased)
  83. @pytest.mark.parametrize("locally_biased", [True, False])
  84. def test_nan(self, locally_biased):
  85. bounds = 4*[(-10, 10)]
  86. direct(self.nan_fun, bounds=bounds,
  87. locally_biased=locally_biased)
  88. @pytest.mark.parametrize("len_tol", [1e-3, 1e-4])
  89. @pytest.mark.parametrize("locally_biased", [True, False])
  90. def test_len_tol(self, len_tol, locally_biased):
  91. bounds = 4*[(-10., 10.)]
  92. res = direct(self.sphere, bounds=bounds, len_tol=len_tol,
  93. vol_tol=1e-30, locally_biased=locally_biased)
  94. assert res.status == 5
  95. assert res.success
  96. assert_allclose(res.x, np.zeros((4, )))
  97. message = ("The side length measure of the hyperrectangle containing "
  98. "the lowest function value found is below "
  99. f"len_tol={len_tol}")
  100. assert res.message == message
  101. @pytest.mark.parametrize("vol_tol", [1e-6, 1e-8])
  102. @pytest.mark.parametrize("locally_biased", [True, False])
  103. def test_vol_tol(self, vol_tol, locally_biased):
  104. bounds = 4*[(-10., 10.)]
  105. res = direct(self.sphere, bounds=bounds, vol_tol=vol_tol,
  106. len_tol=0., locally_biased=locally_biased)
  107. assert res.status == 4
  108. assert res.success
  109. assert_allclose(res.x, np.zeros((4, )))
  110. message = ("The volume of the hyperrectangle containing the lowest "
  111. f"function value found is below vol_tol={vol_tol}")
  112. assert res.message == message
  113. @pytest.mark.parametrize("f_min_rtol", [1e-3, 1e-5, 1e-7])
  114. @pytest.mark.parametrize("locally_biased", [True, False])
  115. def test_f_min(self, f_min_rtol, locally_biased):
  116. # test that desired function value is reached within
  117. # relative tolerance of f_min_rtol
  118. f_min = 1.
  119. bounds = 4*[(-2., 10.)]
  120. res = direct(self.sphere, bounds=bounds, f_min=f_min,
  121. f_min_rtol=f_min_rtol,
  122. locally_biased=locally_biased)
  123. assert res.status == 3
  124. assert res.success
  125. assert res.fun < f_min * (1. + f_min_rtol)
  126. message = ("The best function value found is within a relative "
  127. f"error={f_min_rtol} of the (known) global optimum f_min")
  128. assert res.message == message
  129. def circle_with_args(self, x, a, b):
  130. return np.square(x[0] - a) + np.square(x[1] - b).sum()
  131. @pytest.mark.parametrize("locally_biased", [True, False])
  132. def test_f_circle_with_args(self, locally_biased):
  133. bounds = 2*[(-2.0, 2.0)]
  134. res = direct(self.circle_with_args, bounds, args=(1, 1), maxfun=1250,
  135. locally_biased=locally_biased)
  136. assert_allclose(res.x, np.array([1., 1.]), rtol=1e-5)
  137. @pytest.mark.parametrize("locally_biased", [True, False])
  138. def test_failure_maxfun(self, locally_biased):
  139. # test that if optimization runs for the maximal number of
  140. # evaluations, success = False is returned
  141. maxfun = 100
  142. result = direct(self.styblinski_tang, self.bounds_stylinski_tang,
  143. maxfun=maxfun, locally_biased=locally_biased)
  144. assert result.success is False
  145. assert result.status == 1
  146. assert result.nfev >= maxfun
  147. message = ("Number of function evaluations done is "
  148. f"larger than maxfun={maxfun}")
  149. assert result.message == message
  150. @pytest.mark.parametrize("locally_biased", [True, False])
  151. def test_failure_maxiter(self, locally_biased):
  152. # test that if optimization runs for the maximal number of
  153. # iterations, success = False is returned
  154. maxiter = 10
  155. result = direct(self.styblinski_tang, self.bounds_stylinski_tang,
  156. maxiter=maxiter, locally_biased=locally_biased)
  157. assert result.success is False
  158. assert result.status == 2
  159. assert result.nit >= maxiter
  160. message = f"Number of iterations is larger than maxiter={maxiter}"
  161. assert result.message == message
  162. @pytest.mark.parametrize("locally_biased", [True, False])
  163. def test_bounds_variants(self, locally_biased):
  164. # test that new and old bounds yield same result
  165. lb = [-6., 1., -5.]
  166. ub = [-1., 3., 5.]
  167. x_opt = np.array([-1., 1., 0.])
  168. bounds_old = list(zip(lb, ub))
  169. bounds_new = Bounds(lb, ub)
  170. res_old_bounds = direct(self.sphere, bounds_old,
  171. locally_biased=locally_biased)
  172. res_new_bounds = direct(self.sphere, bounds_new,
  173. locally_biased=locally_biased)
  174. assert res_new_bounds.nfev == res_old_bounds.nfev
  175. assert res_new_bounds.message == res_old_bounds.message
  176. assert res_new_bounds.success == res_old_bounds.success
  177. assert res_new_bounds.nit == res_old_bounds.nit
  178. assert_allclose(res_new_bounds.x, res_old_bounds.x)
  179. assert_allclose(res_new_bounds.x, x_opt, rtol=1e-2)
  180. @pytest.mark.parametrize("locally_biased", [True, False])
  181. @pytest.mark.parametrize("eps", [1e-5, 1e-4, 1e-3])
  182. def test_epsilon(self, eps, locally_biased):
  183. result = direct(self.styblinski_tang, self.bounds_stylinski_tang,
  184. eps=eps, vol_tol=1e-6,
  185. locally_biased=locally_biased)
  186. assert result.status == 4
  187. assert result.success
  188. @pytest.mark.xslow
  189. @pytest.mark.parametrize("locally_biased", [True, False])
  190. def test_no_segmentation_fault(self, locally_biased):
  191. # test that an excessive number of function evaluations
  192. # does not result in segmentation fault
  193. bounds = [(-5., 20.)] * 100
  194. result = direct(self.sphere, bounds, maxfun=10000000,
  195. maxiter=1000000, locally_biased=locally_biased)
  196. assert result is not None
  197. @pytest.mark.parametrize("locally_biased", [True, False])
  198. def test_inf_fun(self, locally_biased):
  199. # test that an objective value of infinity does not crash DIRECT
  200. bounds = [(-5., 5.)] * 2
  201. result = direct(self.inf_fun, bounds,
  202. locally_biased=locally_biased)
  203. assert result is not None
  204. @pytest.mark.parametrize("len_tol", [-1, 2])
  205. def test_len_tol_validation(self, len_tol):
  206. error_msg = "len_tol must be between 0 and 1."
  207. with pytest.raises(ValueError, match=error_msg):
  208. direct(self.styblinski_tang, self.bounds_stylinski_tang,
  209. len_tol=len_tol)
  210. @pytest.mark.parametrize("vol_tol", [-1, 2])
  211. def test_vol_tol_validation(self, vol_tol):
  212. error_msg = "vol_tol must be between 0 and 1."
  213. with pytest.raises(ValueError, match=error_msg):
  214. direct(self.styblinski_tang, self.bounds_stylinski_tang,
  215. vol_tol=vol_tol)
  216. @pytest.mark.parametrize("f_min_rtol", [-1, 2])
  217. def test_fmin_rtol_validation(self, f_min_rtol):
  218. error_msg = "f_min_rtol must be between 0 and 1."
  219. with pytest.raises(ValueError, match=error_msg):
  220. direct(self.styblinski_tang, self.bounds_stylinski_tang,
  221. f_min_rtol=f_min_rtol, f_min=0.)
  222. @pytest.mark.parametrize("maxfun", [1.5, "string", (1, 2)])
  223. def test_maxfun_wrong_type(self, maxfun):
  224. error_msg = "maxfun must be of type int."
  225. with pytest.raises(ValueError, match=error_msg):
  226. direct(self.styblinski_tang, self.bounds_stylinski_tang,
  227. maxfun=maxfun)
  228. @pytest.mark.parametrize("maxiter", [1.5, "string", (1, 2)])
  229. def test_maxiter_wrong_type(self, maxiter):
  230. error_msg = "maxiter must be of type int."
  231. with pytest.raises(ValueError, match=error_msg):
  232. direct(self.styblinski_tang, self.bounds_stylinski_tang,
  233. maxiter=maxiter)
  234. def test_negative_maxiter(self):
  235. error_msg = "maxiter must be > 0."
  236. with pytest.raises(ValueError, match=error_msg):
  237. direct(self.styblinski_tang, self.bounds_stylinski_tang,
  238. maxiter=-1)
  239. def test_negative_maxfun(self):
  240. error_msg = "maxfun must be > 0."
  241. with pytest.raises(ValueError, match=error_msg):
  242. direct(self.styblinski_tang, self.bounds_stylinski_tang,
  243. maxfun=-1)
  244. @pytest.mark.parametrize("bounds", ["bounds", 2., 0])
  245. def test_invalid_bounds_type(self, bounds):
  246. error_msg = ("bounds must be a sequence or "
  247. "instance of Bounds class")
  248. with pytest.raises(ValueError, match=error_msg):
  249. direct(self.styblinski_tang, bounds)
  250. @pytest.mark.parametrize("bounds",
  251. [Bounds([-1., -1], [-2, 1]),
  252. Bounds([-np.nan, -1], [-2, np.nan]),
  253. ]
  254. )
  255. def test_incorrect_bounds(self, bounds):
  256. error_msg = 'Bounds are not consistent min < max'
  257. with pytest.raises(ValueError, match=error_msg):
  258. direct(self.styblinski_tang, bounds)
  259. def test_inf_bounds(self):
  260. error_msg = 'Bounds must not be inf.'
  261. bounds = Bounds([-np.inf, -1], [-2, np.inf])
  262. with pytest.raises(ValueError, match=error_msg):
  263. direct(self.styblinski_tang, bounds)
  264. @pytest.mark.parametrize("locally_biased", ["bias", [0, 0], 2.])
  265. def test_locally_biased_validation(self, locally_biased):
  266. error_msg = 'locally_biased must be True or False.'
  267. with pytest.raises(ValueError, match=error_msg):
  268. direct(self.styblinski_tang, self.bounds_stylinski_tang,
  269. locally_biased=locally_biased)