-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy path_algorithm_test.py
636 lines (505 loc) · 20.4 KB
/
_algorithm_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
# Copyright 2020, 2021 PaGMO development team
#
# This file is part of the pygmo library.
#
# This Source Code Form is subject to the terms of the Mozilla
# Public License v. 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
import unittest as _ut
class _algo(object):
def evolve(self, pop):
return pop
class algorithm_test_case(_ut.TestCase):
"""Test case for the :class:`~pygmo.algorithm` class."""
def runTest(self):
self.run_basic_tests()
self.run_extract_tests()
self.run_seed_tests()
self.run_verbosity_tests()
self.run_name_info_tests()
self.run_thread_safety_tests()
self.run_pickle_tests()
self.run_scipy_wrapper_tests()
def run_basic_tests(self):
# Tests for minimal algorithm, and mandatory methods.
from .core import algorithm, de, population, null_problem, null_algorithm
from . import thread_safety as ts
# Def construction.
a = algorithm()
self.assertTrue(a.extract(null_algorithm) is not None)
self.assertTrue(a.extract(de) is None)
# First a few non-algos.
self.assertRaises(NotImplementedError, lambda: algorithm(1))
self.assertRaises(NotImplementedError, lambda: algorithm("hello world"))
self.assertRaises(NotImplementedError, lambda: algorithm([]))
self.assertRaises(TypeError, lambda: algorithm(int))
# Some algorithms missing methods, wrong arity, etc.
class na0(object):
pass
self.assertRaises(NotImplementedError, lambda: algorithm(na0()))
class na1(object):
evolve = 45
self.assertRaises(NotImplementedError, lambda: algorithm(na1()))
# The minimal good citizen.
glob = []
class a(object):
def __init__(self, g):
self.g = g
def evolve(self, pop):
self.g.append(1)
return pop
a_inst = a(glob)
algo = algorithm(a_inst)
# Test the keyword arg.
algo = algorithm(uda=de())
algo = algorithm(uda=a_inst)
# Check a few algo properties.
self.assertEqual(algo.is_stochastic(), False)
self.assertEqual(algo.has_set_seed(), False)
self.assertEqual(algo.has_set_verbosity(), False)
self.assertEqual(algo.get_thread_safety(), ts.none)
self.assertEqual(algo.get_extra_info(), "")
self.assertRaises(NotImplementedError, lambda: algo.set_seed(123))
self.assertRaises(NotImplementedError, lambda: algo.set_verbosity(1))
self.assertTrue(algo.extract(int) is None)
self.assertTrue(algo.extract(de) is None)
self.assertFalse(algo.extract(a) is None)
self.assertTrue(algo.is_(a))
self.assertTrue(isinstance(algo.evolve(population()), population))
# Assert that a_inst was deep-copied into algo:
# the instance in algo will have its own copy of glob
# and it will not be a reference the outside object.
self.assertEqual(len(glob), 0)
self.assertEqual(len(algo.extract(a).g), 1)
algo = algorithm(de())
self.assertEqual(algo.is_stochastic(), True)
self.assertEqual(algo.has_set_seed(), True)
self.assertEqual(algo.has_set_verbosity(), True)
self.assertEqual(algo.get_thread_safety(), ts.basic)
self.assertTrue(algo.get_extra_info() != "")
self.assertTrue(algo.extract(int) is None)
self.assertTrue(algo.extract(a) is None)
self.assertFalse(algo.extract(de) is None)
self.assertTrue(algo.is_(de))
algo.set_seed(123)
algo.set_verbosity(0)
self.assertTrue(
isinstance(algo.evolve(population(null_problem(), 5)), population)
)
# Wrong retval for evolve().
class a(object):
def evolve(self, pop):
return 3
algo = algorithm(a())
self.assertRaises(
RuntimeError, lambda: algo.evolve(population(null_problem(), 5))
)
# Test that construction from another pygmo.algorithm fails.
with self.assertRaises(TypeError) as cm:
algorithm(algo)
err = cm.exception
self.assertTrue(
"a pygmo.algorithm cannot be used as a UDA for another pygmo.algorithm (if you need to copy an algorithm please use the standard Python copy()/deepcopy() functions)"
in str(err)
)
def run_extract_tests(self):
from .core import algorithm, _test_algorithm, mbh, de
import sys
# First we try with a C++ test algo.
p = algorithm(_test_algorithm())
# Verify the refcount of p is increased after extract().
rc = sys.getrefcount(p)
tprob = p.extract(_test_algorithm)
self.assertTrue(sys.getrefcount(p) == rc + 1)
del tprob
self.assertTrue(sys.getrefcount(p) == rc)
# Verify we are modifying the inner object.
p.extract(_test_algorithm).set_n(5)
self.assertTrue(p.extract(_test_algorithm).get_n() == 5)
# Chain extracts.
t = mbh(_test_algorithm(), stop=5, perturb=[0.4])
pt = algorithm(t)
rc = sys.getrefcount(pt)
talgo = pt.extract(mbh)
# Verify that extraction of mbh from the algo
# increases the refecount of pt.
self.assertTrue(sys.getrefcount(pt) == rc + 1)
# Extract the _test_algorithm from mbh.
rc2 = sys.getrefcount(talgo)
ttalgo = talgo.inner_algorithm.extract(_test_algorithm)
# The refcount of pt is not affected.
self.assertTrue(sys.getrefcount(pt) == rc + 1)
# The refcount of talgo has increased.
self.assertTrue(sys.getrefcount(talgo) == rc2 + 1)
del talgo
# We can still access ttalgo.
self.assertTrue(ttalgo.get_n() == 1)
self.assertTrue(sys.getrefcount(pt) == rc + 1)
del ttalgo
# Now the refcount of pt decreases, because deleting
# ttalgo eliminates the last ref to talgo, which in turn
# decreases the refcount of pt.
self.assertTrue(sys.getrefcount(pt) == rc)
class talgorithm(object):
def __init__(self):
self._n = 1
def get_n(self):
return self._n
def set_n(self, n):
self._n = n
def evolve(self, pop):
return pop
# Test with Python algo.
p = algorithm(talgorithm())
rc = sys.getrefcount(p)
talgo = p.extract(talgorithm)
# Reference count does not increase because
# talgorithm is stored as a proper Python object
# with its own refcount.
self.assertTrue(sys.getrefcount(p) == rc)
self.assertTrue(talgo.get_n() == 1)
talgo.set_n(12)
self.assertTrue(p.extract(talgorithm).get_n() == 12)
# Check that we can extract Python UDAs also via Python's object type.
a = algorithm(talgorithm())
self.assertTrue(not a.extract(object) is None)
# Check we are referring to the same object.
self.assertEqual(id(a.extract(object)), id(a.extract(talgorithm)))
# Check that it will not work with exposed C++ algorithms.
a = algorithm(de())
self.assertTrue(a.extract(object) is None)
self.assertTrue(not a.extract(de) is None)
def run_seed_tests(self):
from .core import algorithm
class a(object):
def evolve(self, pop):
return pop
self.assertTrue(not algorithm(a()).has_set_seed())
self.assertRaises(NotImplementedError, lambda: algorithm(a()).set_seed(12))
class a(object):
def evolve(self, pop):
return pop
def has_set_seed(self):
return True
self.assertTrue(not algorithm(a()).has_set_seed())
self.assertRaises(NotImplementedError, lambda: algorithm(a()).set_seed(12))
class a(object):
def evolve(self, pop):
return pop
def set_seed(self, seed):
pass
self.assertTrue(algorithm(a()).has_set_seed())
algorithm(a()).set_seed(87)
class a(object):
def evolve(self, pop):
return pop
def set_seed(self, seed):
pass
def has_set_seed(self):
return False
self.assertTrue(not algorithm(a()).has_set_seed())
class a(object):
def evolve(self, pop):
return pop
def set_seed(self, seed):
pass
def has_set_seed(self):
return True
self.assertTrue(algorithm(a()).has_set_seed())
algorithm(a()).set_seed(0)
algorithm(a()).set_seed(87)
self.assertRaises(TypeError, lambda: algorithm(a()).set_seed(-1))
def run_verbosity_tests(self):
from .core import algorithm
class a(object):
def evolve(self, pop):
return pop
self.assertTrue(not algorithm(a()).has_set_verbosity())
self.assertRaises(NotImplementedError, lambda: algorithm(a()).set_verbosity(12))
class a(object):
def evolve(self, pop):
return pop
def has_set_verbosity(self):
return True
self.assertTrue(not algorithm(a()).has_set_verbosity())
self.assertRaises(NotImplementedError, lambda: algorithm(a()).set_verbosity(12))
class a(object):
def evolve(self, pop):
return pop
def set_verbosity(self, level):
pass
self.assertTrue(algorithm(a()).has_set_verbosity())
algorithm(a()).set_verbosity(87)
class a(object):
def evolve(self, pop):
return pop
def set_verbosity(self, level):
pass
def has_set_verbosity(self):
return False
self.assertTrue(not algorithm(a()).has_set_verbosity())
class a(object):
def evolve(self, pop):
return pop
def set_verbosity(self, level):
pass
def has_set_verbosity(self):
return True
self.assertTrue(algorithm(a()).has_set_verbosity())
algorithm(a()).set_verbosity(0)
algorithm(a()).set_verbosity(87)
self.assertRaises(TypeError, lambda: algorithm(a()).set_verbosity(-1))
def run_name_info_tests(self):
from .core import algorithm
class a(object):
def evolve(self, pop):
return pop
algo = algorithm(a())
self.assertTrue(algo.get_name() != "")
self.assertTrue(algo.get_extra_info() == "")
class a(object):
def evolve(self, pop):
return pop
def get_name(self):
return "pippo"
algo = algorithm(a())
self.assertTrue(algo.get_name() == "pippo")
self.assertTrue(algo.get_extra_info() == "")
class a(object):
def evolve(self, pop):
return pop
def get_extra_info(self):
return "pluto"
algo = algorithm(a())
self.assertTrue(algo.get_name() != "")
self.assertTrue(algo.get_extra_info() == "pluto")
class a(object):
def evolve(self, pop):
return pop
def get_name(self):
return "pippo"
def get_extra_info(self):
return "pluto"
algo = algorithm(a())
self.assertTrue(algo.get_name() == "pippo")
self.assertTrue(algo.get_extra_info() == "pluto")
def run_thread_safety_tests(self):
from .core import algorithm, de, _tu_test_algorithm, mbh
from . import thread_safety as ts
class a(object):
def evolve(self, pop):
return pop
self.assertTrue(algorithm(a()).get_thread_safety() == ts.none)
self.assertTrue(algorithm(de()).get_thread_safety() == ts.basic)
self.assertTrue(algorithm(_tu_test_algorithm()).get_thread_safety() == ts.none)
self.assertTrue(
algorithm(
mbh(_tu_test_algorithm(), stop=5, perturb=0.4)
).get_thread_safety()
== ts.none
)
self.assertTrue(
algorithm(mbh(a(), stop=5, perturb=0.4)).get_thread_safety() == ts.none
)
self.assertTrue(
algorithm(mbh(de(), stop=5, perturb=0.4)).get_thread_safety() == ts.basic
)
def run_pickle_tests(self):
from .core import algorithm, de, mbh
from pickle import dumps, loads
a_ = algorithm(de())
a = loads(dumps(a_))
self.assertEqual(repr(a), repr(a_))
self.assertTrue(a.is_(de))
a_ = algorithm(mbh(de(), 10, 0.1))
a = loads(dumps(a_))
self.assertEqual(repr(a), repr(a_))
self.assertTrue(a.is_(mbh))
self.assertTrue(a.extract(mbh).inner_algorithm.is_(de))
a_ = algorithm(_algo())
a = loads(dumps(a_))
self.assertEqual(repr(a), repr(a_))
self.assertTrue(a.is_(_algo))
a_ = algorithm(mbh(_algo(), 10, 0.1))
a = loads(dumps(a_))
self.assertEqual(repr(a), repr(a_))
self.assertTrue(a.is_(mbh))
self.assertTrue(a.extract(mbh).inner_algorithm.is_(_algo))
def run_scipy_wrapper_tests(self):
from . import (
ackley,
algorithm,
golomb_ruler,
hock_schittkowski_71,
luksan_vlcek1,
minlp_rastrigin,
population,
problem,
rastrigin,
rosenbrock,
s_policy,
select_best,
scipy_optimize,
)
from copy import deepcopy
# testing invalid method
self.assertRaises(ValueError, lambda: scipy_optimize(method="foo"))
# simple test with ackley, a problem without gradients or constraints
methods = ["L-BFGS-B", "TNC", "SLSQP", None]
prob = problem(ackley(10))
pop = population(prob=prob, size=1, seed=0)
init = pop.champion_f
for m in methods:
popc = deepcopy(pop)
scp = algorithm(scipy_optimize(method=m))
result = scp.evolve(popc).champion_f
self.assertTrue(result[0] <= init[0])
self.assertTrue(popc.problem.get_fevals() > 1)
# simple test with rosenbrock, a problem with a gradient
methods = ["L-BFGS-B", "TNC", "SLSQP", "trust-constr", None]
prob = problem(rosenbrock(10))
pop = population(prob=prob, size=1, seed=0)
init = pop.champion_f
for m in methods:
popc = deepcopy(pop)
scp = algorithm(scipy_optimize(method=m))
result = scp.evolve(popc).champion_f
self.assertTrue(result[0] <= init[0])
self.assertTrue(popc.problem.get_fevals() > 1)
self.assertTrue(popc.problem.get_gevals() > 1)
# testing Hessian and Hessian sparsity
methods = ["trust-constr", "trust-exact", "trust-krylov", None]
problems = [problem(rastrigin(10)), problem(minlp_rastrigin(10))]
for inst in problems:
pop = population(prob=inst, size=1, seed=0)
init = pop.champion_f
for m in methods:
popc = deepcopy(pop)
scp = algorithm(scipy_optimize(method=m))
result = scp.evolve(popc).champion_f
self.assertTrue(result[0] <= init[0])
self.assertTrue(popc.problem.get_fevals() > 1)
self.assertTrue(popc.problem.get_gevals() > 0)
if m is not None:
self.assertTrue(popc.problem.get_hevals() > 0)
# testing constraints without Hessians
methods = ["SLSQP", "trust-constr", None]
raw_probs = [luksan_vlcek1(10), golomb_ruler(2, 10)]
instances = [problem(prob) for prob in raw_probs]
for inst in instances:
pop = population(prob=inst, size=1, seed=0)
init = pop.champion_f
for m in methods:
popc = deepcopy(pop)
# print(m, ": ", end="")
scp = algorithm(scipy_optimize(method=m))
result = scp.evolve(popc).champion_f
self.assertTrue(result[0] <= init[0])
self.assertTrue(popc.problem.get_fevals() > 1)
# TODO: test that result fulfills constraints
# testing constraints with gradients and Hessians
methods = ["trust-constr", None]
prob = problem(hock_schittkowski_71())
pop = population(prob=prob, size=1, seed=0)
init = pop.champion_f
for m in methods:
popc = deepcopy(pop)
scp = algorithm(scipy_optimize(method=m))
result = scp.evolve(popc).champion_f
self.assertTrue(result[0] <= init[0])
self.assertTrue(popc.problem.get_fevals() > 1)
self.assertTrue(popc.problem.get_gevals() > 0)
if m is not None:
self.assertTrue(popc.problem.get_hevals() > 0)
# testing verbosity
method_list = [
"Nelder-Mead",
"Powell",
"CG",
"BFGS",
"Newton-CG",
"L-BFGS-B",
"TNC",
"COBYLA",
"SLSQP",
"trust-constr",
"dogleg",
"trust-ncg",
"trust-exact",
"trust-krylov",
None,
]
for m in method_list:
scp = algorithm(scipy_optimize(method=m))
scp.set_verbosity(1)
scp.get_name()
scp.set_verbosity(0)
# testing constrained problem on incompatible methods
prob = problem(luksan_vlcek1(10))
pop = population(prob=prob, size=1, seed=0)
methods = [
"Nelder-Mead",
"Powell",
"CG",
"BFGS",
"Newton-CG",
"L-BFGS-B",
"TNC",
"dogleg",
"trust-ncg",
"trust-exact",
"trust-krylov",
]
for m in methods:
popc = deepcopy(pop)
scp = algorithm(scipy_optimize(method=m))
self.assertRaises(ValueError, lambda: scp.evolve(popc))
# testing invalid selection policy
prob = problem(luksan_vlcek1(10))
pop = population(prob=prob, size=10, seed=0)
scp = algorithm(scipy_optimize(selection=s_policy(select_best(rate=2))))
self.assertRaises(ValueError, lambda: scp.evolve(pop))
# testing callback
class callback_counter:
value = 0
def increment(self, *args, **kwargs):
callback_counter.value += 1
prob = problem(luksan_vlcek1(10))
pop = population(prob=prob, size=10, seed=0)
counter = callback_counter()
scp = algorithm(scipy_optimize(callback=counter.increment))
scp.evolve(pop)
self.assertTrue(counter.value > 0)
# testing gradient wrapper generator
from numpy import array
prob = problem(luksan_vlcek1(10))
prob.gradient([0] * prob.get_nx())
wrapper = scipy_optimize._fitness_wrapper(prob)
for i in range(prob.get_nobj() + prob.get_nc()):
f = wrapper._generate_gradient_sparsity_wrapper(i)
self.assertEqual(len(f(array([0] * prob.get_nx()))), prob.get_nx())
# testing invalid index for gradient wrapper
self.assertRaises(
ValueError, lambda: wrapper._generate_gradient_sparsity_wrapper(9)
)
# testing gradient function of wrong dimension
smallerProb = problem(luksan_vlcek1(8))
wrapped_gradient = scipy_optimize._fitness_wrapper(
smallerProb
)._generate_gradient_sparsity_wrapper(0)
self.assertRaises(
ValueError, lambda: wrapped_gradient(array([0] * prob.get_nx()))
)
# testing hessian wrapper generator
prob = problem(rastrigin(10))
f = scipy_optimize._fitness_wrapper(prob)._generate_hessian_sparsity_wrapper(0)
hessian = f(array([0] * prob.get_nx()))
self.assertEqual(len(hessian), prob.get_nx())
self.assertEqual(len(hessian[0]), prob.get_nx())
# testing invalid index for hessian wrapper
self.assertRaises(
ValueError,
lambda: scipy_optimize._fitness_wrapper(
prob
)._generate_hessian_sparsity_wrapper(5),
)