test__differential_evolution.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. """
  2. Unit tests for the differential global minimization algorithm.
  3. """
  4. import multiprocessing
  5. from scipy.optimize import _differentialevolution
  6. from scipy.optimize._differentialevolution import DifferentialEvolutionSolver
  7. from scipy.optimize import differential_evolution
  8. import numpy as np
  9. from scipy.optimize import rosen
  10. from numpy.testing import (assert_equal, assert_allclose,
  11. assert_almost_equal,
  12. assert_string_equal, assert_)
  13. from pytest import raises as assert_raises, warns
  14. class TestDifferentialEvolutionSolver(object):
  15. def setup_method(self):
  16. self.old_seterr = np.seterr(invalid='raise')
  17. self.limits = np.array([[0., 0.],
  18. [2., 2.]])
  19. self.bounds = [(0., 2.), (0., 2.)]
  20. self.dummy_solver = DifferentialEvolutionSolver(self.quadratic,
  21. [(0, 100)])
  22. # dummy_solver2 will be used to test mutation strategies
  23. self.dummy_solver2 = DifferentialEvolutionSolver(self.quadratic,
  24. [(0, 1)],
  25. popsize=7,
  26. mutation=0.5)
  27. # create a population that's only 7 members long
  28. # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
  29. population = np.atleast_2d(np.arange(0.1, 0.8, 0.1)).T
  30. self.dummy_solver2.population = population
  31. def teardown_method(self):
  32. np.seterr(**self.old_seterr)
  33. def quadratic(self, x):
  34. return x[0]**2
  35. def test__strategy_resolves(self):
  36. # test that the correct mutation function is resolved by
  37. # different requested strategy arguments
  38. solver = DifferentialEvolutionSolver(rosen,
  39. self.bounds,
  40. strategy='best1exp')
  41. assert_equal(solver.strategy, 'best1exp')
  42. assert_equal(solver.mutation_func.__name__, '_best1')
  43. solver = DifferentialEvolutionSolver(rosen,
  44. self.bounds,
  45. strategy='best1bin')
  46. assert_equal(solver.strategy, 'best1bin')
  47. assert_equal(solver.mutation_func.__name__, '_best1')
  48. solver = DifferentialEvolutionSolver(rosen,
  49. self.bounds,
  50. strategy='rand1bin')
  51. assert_equal(solver.strategy, 'rand1bin')
  52. assert_equal(solver.mutation_func.__name__, '_rand1')
  53. solver = DifferentialEvolutionSolver(rosen,
  54. self.bounds,
  55. strategy='rand1exp')
  56. assert_equal(solver.strategy, 'rand1exp')
  57. assert_equal(solver.mutation_func.__name__, '_rand1')
  58. solver = DifferentialEvolutionSolver(rosen,
  59. self.bounds,
  60. strategy='rand2exp')
  61. assert_equal(solver.strategy, 'rand2exp')
  62. assert_equal(solver.mutation_func.__name__, '_rand2')
  63. solver = DifferentialEvolutionSolver(rosen,
  64. self.bounds,
  65. strategy='best2bin')
  66. assert_equal(solver.strategy, 'best2bin')
  67. assert_equal(solver.mutation_func.__name__, '_best2')
  68. solver = DifferentialEvolutionSolver(rosen,
  69. self.bounds,
  70. strategy='rand2bin')
  71. assert_equal(solver.strategy, 'rand2bin')
  72. assert_equal(solver.mutation_func.__name__, '_rand2')
  73. solver = DifferentialEvolutionSolver(rosen,
  74. self.bounds,
  75. strategy='rand2exp')
  76. assert_equal(solver.strategy, 'rand2exp')
  77. assert_equal(solver.mutation_func.__name__, '_rand2')
  78. solver = DifferentialEvolutionSolver(rosen,
  79. self.bounds,
  80. strategy='randtobest1bin')
  81. assert_equal(solver.strategy, 'randtobest1bin')
  82. assert_equal(solver.mutation_func.__name__, '_randtobest1')
  83. solver = DifferentialEvolutionSolver(rosen,
  84. self.bounds,
  85. strategy='randtobest1exp')
  86. assert_equal(solver.strategy, 'randtobest1exp')
  87. assert_equal(solver.mutation_func.__name__, '_randtobest1')
  88. solver = DifferentialEvolutionSolver(rosen,
  89. self.bounds,
  90. strategy='currenttobest1bin')
  91. assert_equal(solver.strategy, 'currenttobest1bin')
  92. assert_equal(solver.mutation_func.__name__, '_currenttobest1')
  93. solver = DifferentialEvolutionSolver(rosen,
  94. self.bounds,
  95. strategy='currenttobest1exp')
  96. assert_equal(solver.strategy, 'currenttobest1exp')
  97. assert_equal(solver.mutation_func.__name__, '_currenttobest1')
  98. def test__mutate1(self):
  99. # strategies */1/*, i.e. rand/1/bin, best/1/exp, etc.
  100. result = np.array([0.05])
  101. trial = self.dummy_solver2._best1((2, 3, 4, 5, 6))
  102. assert_allclose(trial, result)
  103. result = np.array([0.25])
  104. trial = self.dummy_solver2._rand1((2, 3, 4, 5, 6))
  105. assert_allclose(trial, result)
  106. def test__mutate2(self):
  107. # strategies */2/*, i.e. rand/2/bin, best/2/exp, etc.
  108. # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
  109. result = np.array([-0.1])
  110. trial = self.dummy_solver2._best2((2, 3, 4, 5, 6))
  111. assert_allclose(trial, result)
  112. result = np.array([0.1])
  113. trial = self.dummy_solver2._rand2((2, 3, 4, 5, 6))
  114. assert_allclose(trial, result)
  115. def test__randtobest1(self):
  116. # strategies randtobest/1/*
  117. result = np.array([0.15])
  118. trial = self.dummy_solver2._randtobest1((2, 3, 4, 5, 6))
  119. assert_allclose(trial, result)
  120. def test__currenttobest1(self):
  121. # strategies currenttobest/1/*
  122. result = np.array([0.1])
  123. trial = self.dummy_solver2._currenttobest1(1, (2, 3, 4, 5, 6))
  124. assert_allclose(trial, result)
  125. def test_can_init_with_dithering(self):
  126. mutation = (0.5, 1)
  127. solver = DifferentialEvolutionSolver(self.quadratic,
  128. self.bounds,
  129. mutation=mutation)
  130. assert_equal(solver.dither, list(mutation))
  131. def test_invalid_mutation_values_arent_accepted(self):
  132. func = rosen
  133. mutation = (0.5, 3)
  134. assert_raises(ValueError,
  135. DifferentialEvolutionSolver,
  136. func,
  137. self.bounds,
  138. mutation=mutation)
  139. mutation = (-1, 1)
  140. assert_raises(ValueError,
  141. DifferentialEvolutionSolver,
  142. func,
  143. self.bounds,
  144. mutation=mutation)
  145. mutation = (0.1, np.nan)
  146. assert_raises(ValueError,
  147. DifferentialEvolutionSolver,
  148. func,
  149. self.bounds,
  150. mutation=mutation)
  151. mutation = 0.5
  152. solver = DifferentialEvolutionSolver(func,
  153. self.bounds,
  154. mutation=mutation)
  155. assert_equal(0.5, solver.scale)
  156. assert_equal(None, solver.dither)
  157. def test__scale_parameters(self):
  158. trial = np.array([0.3])
  159. assert_equal(30, self.dummy_solver._scale_parameters(trial))
  160. # it should also work with the limits reversed
  161. self.dummy_solver.limits = np.array([[100], [0.]])
  162. assert_equal(30, self.dummy_solver._scale_parameters(trial))
  163. def test__unscale_parameters(self):
  164. trial = np.array([30])
  165. assert_equal(0.3, self.dummy_solver._unscale_parameters(trial))
  166. # it should also work with the limits reversed
  167. self.dummy_solver.limits = np.array([[100], [0.]])
  168. assert_equal(0.3, self.dummy_solver._unscale_parameters(trial))
  169. def test__ensure_constraint(self):
  170. trial = np.array([1.1, -100, 0.9, 2., 300., -0.00001])
  171. self.dummy_solver._ensure_constraint(trial)
  172. assert_equal(trial[2], 0.9)
  173. assert_(np.logical_and(trial >= 0, trial <= 1).all())
  174. def test_differential_evolution(self):
  175. # test that the Jmin of DifferentialEvolutionSolver
  176. # is the same as the function evaluation
  177. solver = DifferentialEvolutionSolver(self.quadratic, [(-2, 2)])
  178. result = solver.solve()
  179. assert_almost_equal(result.fun, self.quadratic(result.x))
  180. def test_best_solution_retrieval(self):
  181. # test that the getter property method for the best solution works.
  182. solver = DifferentialEvolutionSolver(self.quadratic, [(-2, 2)])
  183. result = solver.solve()
  184. assert_almost_equal(result.x, solver.x)
  185. def test_callback_terminates(self):
  186. # test that if the callback returns true, then the minimization halts
  187. bounds = [(0, 2), (0, 2)]
  188. def callback(param, convergence=0.):
  189. return True
  190. result = differential_evolution(rosen, bounds, callback=callback)
  191. assert_string_equal(result.message,
  192. 'callback function requested stop early '
  193. 'by returning True')
  194. def test_args_tuple_is_passed(self):
  195. # test that the args tuple is passed to the cost function properly.
  196. bounds = [(-10, 10)]
  197. args = (1., 2., 3.)
  198. def quadratic(x, *args):
  199. if type(args) != tuple:
  200. raise ValueError('args should be a tuple')
  201. return args[0] + args[1] * x + args[2] * x**2.
  202. result = differential_evolution(quadratic,
  203. bounds,
  204. args=args,
  205. polish=True)
  206. assert_almost_equal(result.fun, 2 / 3.)
  207. def test_init_with_invalid_strategy(self):
  208. # test that passing an invalid strategy raises ValueError
  209. func = rosen
  210. bounds = [(-3, 3)]
  211. assert_raises(ValueError,
  212. differential_evolution,
  213. func,
  214. bounds,
  215. strategy='abc')
  216. def test_bounds_checking(self):
  217. # test that the bounds checking works
  218. func = rosen
  219. bounds = [(-3, None)]
  220. assert_raises(ValueError,
  221. differential_evolution,
  222. func,
  223. bounds)
  224. bounds = [(-3)]
  225. assert_raises(ValueError,
  226. differential_evolution,
  227. func,
  228. bounds)
  229. bounds = [(-3, 3), (3, 4, 5)]
  230. assert_raises(ValueError,
  231. differential_evolution,
  232. func,
  233. bounds)
  234. def test_select_samples(self):
  235. # select_samples should return 5 separate random numbers.
  236. limits = np.arange(12., dtype='float64').reshape(2, 6)
  237. bounds = list(zip(limits[0, :], limits[1, :]))
  238. solver = DifferentialEvolutionSolver(None, bounds, popsize=1)
  239. candidate = 0
  240. r1, r2, r3, r4, r5 = solver._select_samples(candidate, 5)
  241. assert_equal(
  242. len(np.unique(np.array([candidate, r1, r2, r3, r4, r5]))), 6)
  243. def test_maxiter_stops_solve(self):
  244. # test that if the maximum number of iterations is exceeded
  245. # the solver stops.
  246. solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=1)
  247. result = solver.solve()
  248. assert_equal(result.success, False)
  249. assert_equal(result.message,
  250. 'Maximum number of iterations has been exceeded.')
  251. def test_maxfun_stops_solve(self):
  252. # test that if the maximum number of function evaluations is exceeded
  253. # during initialisation the solver stops
  254. solver = DifferentialEvolutionSolver(rosen, self.bounds, maxfun=1,
  255. polish=False)
  256. result = solver.solve()
  257. assert_equal(result.nfev, 2)
  258. assert_equal(result.success, False)
  259. assert_equal(result.message,
  260. 'Maximum number of function evaluations has '
  261. 'been exceeded.')
  262. # test that if the maximum number of function evaluations is exceeded
  263. # during the actual minimisation, then the solver stops.
  264. # Have to turn polishing off, as this will still occur even if maxfun
  265. # is reached. For popsize=5 and len(bounds)=2, then there are only 10
  266. # function evaluations during initialisation.
  267. solver = DifferentialEvolutionSolver(rosen,
  268. self.bounds,
  269. popsize=5,
  270. polish=False,
  271. maxfun=40)
  272. result = solver.solve()
  273. assert_equal(result.nfev, 41)
  274. assert_equal(result.success, False)
  275. assert_equal(result.message,
  276. 'Maximum number of function evaluations has '
  277. 'been exceeded.')
  278. # now repeat for updating='deferred version
  279. solver = DifferentialEvolutionSolver(rosen,
  280. self.bounds,
  281. popsize=5,
  282. polish=False,
  283. maxfun=40,
  284. updating='deferred')
  285. result = solver.solve()
  286. assert_equal(result.nfev, 40)
  287. assert_equal(result.success, False)
  288. assert_equal(result.message,
  289. 'Maximum number of function evaluations has '
  290. 'been reached.')
  291. def test_quadratic(self):
  292. # test the quadratic function from object
  293. solver = DifferentialEvolutionSolver(self.quadratic,
  294. [(-100, 100)],
  295. tol=0.02)
  296. solver.solve()
  297. assert_equal(np.argmin(solver.population_energies), 0)
  298. def test_quadratic_from_diff_ev(self):
  299. # test the quadratic function from differential_evolution function
  300. differential_evolution(self.quadratic,
  301. [(-100, 100)],
  302. tol=0.02)
  303. def test_seed_gives_repeatability(self):
  304. result = differential_evolution(self.quadratic,
  305. [(-100, 100)],
  306. polish=False,
  307. seed=1,
  308. tol=0.5)
  309. result2 = differential_evolution(self.quadratic,
  310. [(-100, 100)],
  311. polish=False,
  312. seed=1,
  313. tol=0.5)
  314. assert_equal(result.x, result2.x)
  315. assert_equal(result.nfev, result2.nfev)
  316. def test_exp_runs(self):
  317. # test whether exponential mutation loop runs
  318. solver = DifferentialEvolutionSolver(rosen,
  319. self.bounds,
  320. strategy='best1exp',
  321. maxiter=1)
  322. solver.solve()
  323. def test_gh_4511_regression(self):
  324. # This modification of the differential evolution docstring example
  325. # uses a custom popsize that had triggered an off-by-one error.
  326. # Because we do not care about solving the optimization problem in
  327. # this test, we use maxiter=1 to reduce the testing time.
  328. bounds = [(-5, 5), (-5, 5)]
  329. result = differential_evolution(rosen, bounds, popsize=1815, maxiter=1)
  330. def test_calculate_population_energies(self):
  331. # if popsize is 3 then the overall generation has size (6,)
  332. solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3)
  333. solver._calculate_population_energies(solver.population)
  334. solver._promote_lowest_energy()
  335. assert_equal(np.argmin(solver.population_energies), 0)
  336. # initial calculation of the energies should require 6 nfev.
  337. assert_equal(solver._nfev, 6)
  338. def test_iteration(self):
  339. # test that DifferentialEvolutionSolver is iterable
  340. # if popsize is 3 then the overall generation has size (6,)
  341. solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3,
  342. maxfun=12)
  343. x, fun = next(solver)
  344. assert_equal(np.size(x, 0), 2)
  345. # 6 nfev are required for initial calculation of energies, 6 nfev are
  346. # required for the evolution of the 6 population members.
  347. assert_equal(solver._nfev, 12)
  348. # the next generation should halt because it exceeds maxfun
  349. assert_raises(StopIteration, next, solver)
  350. # check a proper minimisation can be done by an iterable solver
  351. solver = DifferentialEvolutionSolver(rosen, self.bounds)
  352. for i, soln in enumerate(solver):
  353. x_current, fun_current = soln
  354. # need to have this otherwise the solver would never stop.
  355. if i == 1000:
  356. break
  357. assert_almost_equal(fun_current, 0)
  358. def test_convergence(self):
  359. solver = DifferentialEvolutionSolver(rosen, self.bounds, tol=0.2,
  360. polish=False)
  361. solver.solve()
  362. assert_(solver.convergence < 0.2)
  363. def test_maxiter_none_GH5731(self):
  364. # Pre 0.17 the previous default for maxiter and maxfun was None.
  365. # the numerical defaults are now 1000 and np.inf. However, some scripts
  366. # will still supply None for both of those, this will raise a TypeError
  367. # in the solve method.
  368. solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=None,
  369. maxfun=None)
  370. solver.solve()
  371. def test_population_initiation(self):
  372. # test the different modes of population initiation
  373. # init must be either 'latinhypercube' or 'random'
  374. # raising ValueError is something else is passed in
  375. assert_raises(ValueError,
  376. DifferentialEvolutionSolver,
  377. *(rosen, self.bounds),
  378. **{'init': 'rubbish'})
  379. solver = DifferentialEvolutionSolver(rosen, self.bounds)
  380. # check that population initiation:
  381. # 1) resets _nfev to 0
  382. # 2) all population energies are np.inf
  383. solver.init_population_random()
  384. assert_equal(solver._nfev, 0)
  385. assert_(np.all(np.isinf(solver.population_energies)))
  386. solver.init_population_lhs()
  387. assert_equal(solver._nfev, 0)
  388. assert_(np.all(np.isinf(solver.population_energies)))
  389. # we should be able to initialise with our own array
  390. population = np.linspace(-1, 3, 10).reshape(5, 2)
  391. solver = DifferentialEvolutionSolver(rosen, self.bounds,
  392. init=population,
  393. strategy='best2bin',
  394. atol=0.01, seed=1, popsize=5)
  395. assert_equal(solver._nfev, 0)
  396. assert_(np.all(np.isinf(solver.population_energies)))
  397. assert_(solver.num_population_members == 5)
  398. assert_(solver.population_shape == (5, 2))
  399. # check that the population was initialised correctly
  400. unscaled_population = np.clip(solver._unscale_parameters(population),
  401. 0, 1)
  402. assert_almost_equal(solver.population[:5], unscaled_population)
  403. # population values need to be clipped to bounds
  404. assert_almost_equal(np.min(solver.population[:5]), 0)
  405. assert_almost_equal(np.max(solver.population[:5]), 1)
  406. # shouldn't be able to initialise with an array if it's the wrong shape
  407. # this would have too many parameters
  408. population = np.linspace(-1, 3, 15).reshape(5, 3)
  409. assert_raises(ValueError,
  410. DifferentialEvolutionSolver,
  411. *(rosen, self.bounds),
  412. **{'init': population})
  413. def test_infinite_objective_function(self):
  414. # Test that there are no problems if the objective function
  415. # returns inf on some runs
  416. def sometimes_inf(x):
  417. if x[0] < .5:
  418. return np.inf
  419. return x[1]
  420. bounds = [(0, 1), (0, 1)]
  421. x_fit = differential_evolution(sometimes_inf,
  422. bounds=[(0, 1), (0, 1)],
  423. disp=False)
  424. def test_deferred_updating(self):
  425. # check setting of deferred updating, with default workers
  426. bounds = [(0., 2.), (0., 2.), (0, 2), (0, 2)]
  427. solver = DifferentialEvolutionSolver(rosen, bounds, updating='deferred')
  428. assert_(solver._updating == 'deferred')
  429. assert_(solver._mapwrapper._mapfunc is map)
  430. solver.solve()
  431. def test_immediate_updating(self):
  432. # check setting of immediate updating, with default workers
  433. bounds = [(0., 2.), (0., 2.)]
  434. solver = DifferentialEvolutionSolver(rosen, bounds)
  435. assert_(solver._updating == 'immediate')
  436. # should raise a UserWarning because the updating='immediate'
  437. # is being overriden by the workers keyword
  438. with warns(UserWarning):
  439. solver = DifferentialEvolutionSolver(rosen, bounds, workers=2)
  440. assert_(solver._updating == 'deferred')
  441. def test_parallel(self):
  442. # smoke test for parallelisation with deferred updating
  443. bounds = [(0., 2.), (0., 2.)]
  444. try:
  445. p = multiprocessing.Pool(2)
  446. with DifferentialEvolutionSolver(rosen, bounds,
  447. updating='deferred',
  448. workers=p.map) as solver:
  449. assert_(solver._mapwrapper.pool is not None)
  450. assert_(solver._updating == 'deferred')
  451. solver.solve()
  452. finally:
  453. p.close()
  454. with DifferentialEvolutionSolver(rosen, bounds, updating='deferred',
  455. workers=2) as solver:
  456. assert_(solver._mapwrapper.pool is not None)
  457. assert_(solver._updating == 'deferred')
  458. solver.solve()
  459. def test_converged(self):
  460. solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)])
  461. solver.solve()
  462. assert_(solver.converged())