-
Notifications
You must be signed in to change notification settings - Fork 181
/
Copy pathevolution_strategy.py
4555 lines (4009 loc) · 211 KB
/
evolution_strategy.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""CMA-ES (evolution strategy), the main sub-module of `cma` providing
in particular `CMAOptions`, `CMAEvolutionStrategy`, and `fmin`
"""
# TODO (mainly done): remove separable CMA within the code (keep as sampler only)
# TODO (low): implement a (deep enough) copy-constructor for class
# CMAEvolutionStrategy to repeat the same step in different
# configurations for online-adaptation of meta parameters
# TODO (complex): reconsider geno-pheno transformation. Can it be a
# separate module that operates inbetween optimizer and objective?
# Can we still propagate a repair of solutions to the optimizer?
# A repair-only internal geno-pheno transformation is less
# problematic, given the repair is idempotent. In any case, consider
# passing a repair function in the interface instead.
# How about gradients (should be fine)?
# Must be *thoroughly* explored before to switch, in particular the
# order of application of repair and other transformations, as the
# internal repair can only operate on the internal representation.
# TODO: split tell into a variable transformation part and the "pure"
# functionality
# usecase: es.tell_geno(X, [func(es.pheno(x)) for x in X])
# genotypic repair is not part of tell_geno
# TODO: self.opts['mindx'] is checked without sigma_vec, which is a little
# inconcise. Cheap solution: project sigma_vec on smallest eigenvector?
# TODO: class _CMAStopDict implementation looks way too complicated,
# design generically from scratch?
# TODO: separate display and logging options, those CMAEvolutionStrategy
# instances don't use themselves (probably all?)
# TODO: check scitools.easyviz and how big the adaptation would be
# TODO: separate initialize==reset_state from __init__
# TODO: keep best ten solutions
# TODO: implement constraints handling
# TODO: eigh(): thorough testing would not hurt
# TODO: (partly done) apply style guide
# WON'T FIX ANYTIME SOON (done within fmin): implement bipop in a separate
# algorithm as meta portfolio algorithm of IPOP and a local restart
# option to be implemented
# in fmin (e.g. option restart_mode in [IPOP, local])
# DONE: extend function unitdoctest, or use unittest?
# DONE: copy_always optional parameter does not make much sense,
# as one can always copy the input argument first. Similar,
# copy_if_changed should be keep_arg_unchanged or just copy
# DONE: expand/generalize to dynamically read "signals" from a file
# see import ConfigParser, DictFromTagsInString,
# function read_properties, or myproperties.py (to be called after
# tell()), signals_filename, if given, is parsed in stop()
# DONE: switch to np.loadtxt
#
# typical parameters in scipy.optimize: disp, xtol, ftol, maxiter, maxfun,
# callback=None
# maxfev, diag (A sequency of N positive entries that serve as
# scale factors for the variables.)
# full_output -- non-zero to return all optional outputs.
# If xtol < 0.0, xtol is set to sqrt(machine_precision)
# 'infot -- a dictionary of optional outputs with the keys:
# 'nfev': the number of function calls...
#
# see eg fmin_powell
# typical returns
# x, f, dictionary d
# (xopt, {fopt, gopt, Hopt, func_calls, grad_calls, warnflag},
# <allvecs>)
#
# changes:
# 20/04/xx: no negative weights for injected solutions
# 16/10/xx: versatile options are read from signals_filename
# RecombinationWeights refined and work without numpy
# new options: recombination_weights, timeout,
# integer_variable with basic integer handling
# step size parameters removed from CMAEvolutionStrategy class
# ComposedFunction class implements function composition
# 16/10/02: copy_always parameter is gone everywhere, use
# np.array(., copy=True)
# 16/xx/xx: revised doctests with doctest: +ELLIPSIS option, test call(s)
# moved all test related to test.py, is quite clean now
# "python -m cma.test" is how it works now
# 16/xx/xx: cleaning up, all kind of larger changes.
# 16/xx/xx: single file cma.py broken into pieces such that cma has now
# become a package.
# 15/02/xx: (v1.2) sampling from the distribution sampling refactorized
# in class Sampler which also does the (natural gradient)
# update. New AdaptiveDecoding class for sigma_vec.
# 15/01/26: bug fix in multiplyC with sep/diagonal option
# 15/01/20: larger condition numbers for C realized by using tf_pheno
# of GenoPheno attribute gp.
# 15/01/19: injection method, first implementation, short injections
# and long injections with good fitness need to be addressed yet
# 15/01/xx: _prepare_injection_directions to simplify/centralize injected
# solutions from mirroring and TPA
# 14/12/26: bug fix in correlation_matrix computation if np.diag is a view
# 14/12/06: meta_parameters now only as annotations in ## comments
# 14/12/03: unified use of base class constructor call, now always
# super(ThisClass, self).__init__(args_for_base_class_constructor)
# 14/11/29: termination via "stop now" in file cmaes_signals.par
# 14/11/28: bug fix initialization of C took place before setting the
# seed. Now in some dimensions (e.g. 10) results are (still) not
# determistic due to np.linalg.eigh, in some dimensions (<9, 12)
# they seem to be deterministic.
# 14/11/23: bipop option integration, contributed by Petr Baudis
# 14/09/30: initial_elitism option added to fmin
# 14/08/1x: developing fitness wrappers in FFWrappers class
# 14/08/xx: return value of OOOptimizer.optimize changed to self.
# CMAOptions now need to uniquely match an *initial substring*
# only (via method corrected_key).
# Bug fix in CMAEvolutionStrategy.stop: termination conditions
# are now recomputed iff check and self.countiter > 0.
# Doc corrected that self.gp.geno _is_ applied to x0
# Vaste reorganization/modularization/improvements of plotting
# 14/08/01: bug fix to guaranty pos. def. in active CMA
# 14/06/04: gradient of f can now be used with fmin and/or ask
# 14/05/11: global rcParams['font.size'] not permanently changed anymore,
# a little nicer annotations for the plots
# 14/05/07: added method result_pretty to pretty print optimization result
# 14/05/06: associated show() everywhere with ion() which should solve the
# blocked terminal problem
# 14/05/05: all instances of "unicode" removed (was incompatible to 3.x)
# 14/05/05: replaced type(x) == y with isinstance(x, y), reorganized the
# comments before the code starts
# 14/05/xx: change the order of kwargs of OOOptimizer.optimize,
# remove prepare method in AdaptSigma classes, various changes/cleaning
# 14/03/01: bug fix BoundaryHandlerBase.has_bounds didn't check lower bounds correctly
# bug fix in BoundPenalty.repair len(bounds[0]) was used instead of len(bounds[1])
# bug fix in GenoPheno.pheno, where x was not copied when only boundary-repair was applied
# 14/02/27: bug fixed when BoundPenalty was combined with fixed variables.
# 13/xx/xx: step-size adaptation becomes a class derived from CMAAdaptSigmaBase,
# to make testing different adaptation rules (much) easier
# 12/12/14: separated CMAOptions and arguments to fmin
# 12/10/25: removed useless check_points from fmin interface
# 12/10/17: bug fix printing number of infeasible samples, moved not-in-use methods
# timesCroot and divCroot to the right class
# 12/10/16 (0.92.00): various changes commit: bug bound[0] -> bounds[0], more_to_write fixed,
# sigma_vec introduced, restart from elitist, trace normalization, max(mu,popsize/2)
# is used for weight calculation.
# 12/07/23: (bug:) BoundPenalty.update respects now genotype-phenotype transformation
# 12/07/21: convert value True for noisehandling into 1 making the output compatible
# 12/01/30: class Solution and more old stuff removed r3101
# 12/01/29: class Solution is depreciated, GenoPheno and SolutionDict do the job (v0.91.00, r3100)
# 12/01/06: CMA_eigenmethod option now takes a function (integer still works)
# 11/09/30: flat fitness termination checks also history length
# 11/09/30: elitist option (using method clip_or_fit_solutions)
# 11/09/xx: method clip_or_fit_solutions for check_points option for all sorts of
# injected or modified solutions and even reliable adaptive encoding
# 11/08/19: fixed: scaling and typical_x type clashes 1 vs array(1) vs ones(dim) vs dim * [1]
# 11/07/25: fixed: fmin wrote first and last line even with verb_log==0
# fixed: method settableOptionsList, also renamed to versatileOptions
# default seed depends on time now
# 11/07/xx (0.9.92): added: active CMA, selective mirrored sampling, noise/uncertainty handling
# fixed: output argument ordering in fmin, print now only used as function
# removed: parallel option in fmin
# 11/07/01: another try to get rid of the memory leak by replacing self.unrepaired = self[:]
# 11/07/01: major clean-up and reworking of abstract base classes and of the documentation,
# also the return value of fmin changed and attribute stop is now a method.
# 11/04/22: bug-fix: option fixed_variables in combination with scaling
# 11/04/21: stopdict is not a copy anymore
# 11/04/15: option fixed_variables implemented
# 11/03/23: bug-fix boundary update was computed even without boundaries
# 11/03/12: bug-fix of variable annotation in plots
# 11/02/05: work around a memory leak in numpy
# 11/02/05: plotting routines improved
# 10/10/17: cleaning up, now version 0.9.30
# 10/10/17: bug-fix: return values of fmin now use phenotyp (relevant
# if input scaling_of_variables is given)
# 08/10/01: option evalparallel introduced,
# bug-fix for scaling being a vector
# 08/09/26: option CMAseparable becomes CMA_diagonal
# 08/10/18: some names change, test functions go into a class
# 08/10/24: more refactorizing
# 10/03/09: upper bound np.exp(min(1,...)) for step-size control
from __future__ import (absolute_import, division, print_function,
) # unicode_literals, with_statement)
# from builtins import ...
from .utilities.python3for2 import range # redefine range in Python 2
import sys
import os
import time # not really essential
import warnings # catch numpy warnings
import ast # for literal_eval
try:
import collections # not available in Python 2.5
except ImportError:
pass
import math
import numpy as np
# arange, cos, size, eye, inf, dot, floor, outer, zeros, linalg.eigh,
# sort, argsort, random, ones,...
from numpy import inf, array
# to access the built-in sum fct: ``__builtins__.sum`` or ``del sum``
# removes the imported sum and recovers the shadowed build-in
# import logging
# logging.basicConfig(level=logging.INFO) # only works before logging is used
# logging.info('message') # prints INFO:root:message on red background
# logger = logging.getLogger(__name__) # should not be done during import
# logger.info('message') # prints INFO:cma...:message on red background
# see https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/
from . import interfaces
from . import transformations
from . import optimization_tools as ot
from . import sampler
from .constraints_handler import BoundNone, BoundPenalty, BoundTransform, AugmentedLagrangian
from .recombination_weights import RecombinationWeights
from .logger import CMADataLogger # , disp, plot
from .utilities.utils import BlancClass as _BlancClass
from .utilities.utils import rglen #, global_verbosity
from .utilities.utils import pprint
from .utilities.utils import seval as eval
from .utilities.utils import SolutionDict as _SolutionDict
from .utilities.math import Mh
from .sigma_adaptation import *
from . import restricted_gaussian_sampler as _rgs
_where = np.nonzero # to make pypy work, this is how where is used here anyway
del division, print_function, absolute_import #, unicode_literals, with_statement
class InjectionWarning(UserWarning):
"""Injected solutions are not passed to tell as expected"""
# use_archives uses collections
use_archives = sys.version_info[0] >= 3 or sys.version_info[1] >= 6
# use_archives = False # on False some unit tests fail
"""speed up for very large population size. `use_archives` prevents the
need for an inverse gp-transformation, relies on collections module,
not sure what happens if set to ``False``. """
class MetaParameters(object):
"""collection of many meta parameters.
Meta parameters are either annotated constants or refer to
options from `CMAOptions` or are arguments to `fmin` or to the
`NoiseHandler` class constructor.
`MetaParameters` take only effect if the source code is modified by
a meta parameter weaver module searching for ## meta_parameters....
and modifying the next line.
Details
-------
This code contains a single class instance `meta_parameters`
Some interfaces rely on parameters being either `int` or
`float` only. More sophisticated choices are implemented via
``choice_value = {1: 'this', 2: 'or that'}[int_param_value]`` here.
CAVEAT
------
`meta_parameters` should not be used to determine default
arguments, because these are assigned only once and for all during
module import.
"""
def __init__(self):
"""assign settings to be used"""
self.sigma0 = None ## [~0.01, ~10] # no default available
# learning rates and back-ward time horizons
self.CMA_cmean = 1.0 ## [~0.1, ~10] #
self.c1_multiplier = 1.0 ## [~1e-4, ~20] l
self.cmu_multiplier = 2.0 ## [~1e-4, ~30] l # zero means off
self.CMA_active = 1.0 ## [~1e-4, ~10] l # 0 means off, was CMA_activefac
self.cc_multiplier = 1.0 ## [~0.01, ~20] l
self.cs_multiplier = 1.0 ## [~0.01, ~10] l # learning rate for cs
self.CSA_dampfac = 1.0 ## [~0.01, ~10]
self.CMA_dampsvec_fac = None ## [~0.01, ~100] # def=np.Inf or 0.5, not clear whether this is a log parameter
self.CMA_dampsvec_fade = 0.1 ## [0, ~2]
# exponents for learning rates
self.c1_exponent = 2.0 ## [~1.25, 2]
self.cmu_exponent = 2.0 ## [~1.25, 2]
self.cact_exponent = 1.5 ## [~1.25, 2]
self.cc_exponent = 1.0 ## [~0.25, ~1.25]
self.cs_exponent = 1.0 ## [~0.25, ~1.75] # upper bound depends on CSA_clip_length_value
# selection related parameters
self.lambda_exponent = 0.0 ## [0, ~2.5] # usually <= 2, used by adding N**lambda_exponent to popsize-1
self.CMA_elitist = 0 ## [0, 2] i # a choice variable
self.CMA_mirrors = 0.0 ## [0, 0.5) # values <0.5 are interpreted as fraction, values >1 as numbers (rounded), otherwise about 0.16 is used',
# sampling strategies
# self.CMA_sample_on_sphere_surface = 0 ## [0, 1] i # boolean
self.mean_shift_line_samples = 0 ## [0, 1] i # boolean
self.pc_line_samples = 0 ## [0, 1] i # boolean
# step-size adapation related parameters
self.CSA_damp_mueff_exponent = 0.5 ## [~0.25, ~1.5] # zero would mean no dependency of damping on mueff, useful with CSA_disregard_length option',
self.CSA_disregard_length = 0 ## [0, 1] i
self.CSA_squared = 0 ## [0, 1] i
self.CSA_clip_length_value = None ## [0, ~20] # None reflects inf
# noise handling
self.noise_reeval_multiplier = 1.0 ## [0.2, 4] # usually 2 offspring are reevaluated
self.noise_choose_reeval = 1 ## [1, 3] i # which ones to reevaluate
self.noise_theta = 0.5 ## [~0.05, ~0.9]
self.noise_alphasigma = 2.0 ## [0, 10]
self.noise_alphaevals = 2.0 ## [0, 10]
self.noise_alphaevalsdown_exponent = -0.25 ## [-1.5, 0]
self.noise_aggregate = None ## [1, 2] i # None and 0 == default or user option choice, 1 == median, 2 == mean
# TODO: more noise handling options (maxreevals...)
# restarts
self.restarts = 0 ## [0, ~30] # but depends on popsize inc
self.restart_from_best = 0 ## [0, 1] i # bool
self.incpopsize = 2.0 ## [~1, ~5]
# termination conditions (for restarts)
self.maxiter_multiplier = 1.0 ## [~0.01, ~100] l
self.mindx = 0.0 ## [1e-17, ~1e-3] l #v minimal std in any direction, cave interference with tol*',
self.minstd = 0.0 ## [1e-17, ~1e-3] l #v minimal std in any coordinate direction, cave interference with tol*',
self.maxstd = None ## [~1, ~1e9] l #v maximal std in any coordinate direction, default is inf',
self.tolfacupx = 1e3 ## [~10, ~1e9] l #v termination when step-size increases by tolfacupx (diverges). That is, the initial step-size was chosen far too small and better solutions were found far away from the initial solution x0',
self.tolupsigma = 1e20 ## [~100, ~1e99] l #v sigma/sigma0 > tolupsigma * max(sqrt(eivenvals(C))) indicates "creeping behavior" with usually minor improvements',
self.tolx = 1e-11 ## [1e-17, ~1e-3] l #v termination criterion: tolerance in x-changes',
self.tolfun = 1e-11 ## [1e-17, ~1e-3] l #v termination criterion: tolerance in function value, quite useful',
self.tolfunrel = 0 ## [1e-17, ~1e-2] l #v termination criterion: relative tolerance in function value',
self.tolfunhist = 1e-12 ## [1e-17, ~1e-3] l #v termination criterion: tolerance in function value history',
self.tolstagnation_multiplier = 1.0 ## [0.01, ~100] # ': 'int(100 + 100 * N**1.5 / popsize) #v termination if no improvement over tolstagnation iterations',
# abandoned:
# self.noise_change_sigma_exponent = 1.0 ## [0, 2]
# self.noise_epsilon = 1e-7 ## [0, ~1e-2] l #
# self.maxfevals = None ## [1, ~1e11] l # is not a performance parameter
# self.lambda_log_multiplier = 3 ## [0, ~10]
# self.lambda_multiplier = 0 ## (0, ~10]
meta_parameters = MetaParameters()
def is_feasible(x, f):
"""default to check feasibility of f-values.
Used for rejection sampling in method `ask_and_eval`.
:See also: CMAOptions, ``CMAOptions('feas')``.
"""
return f is not None and not np.isnan(f)
if use_archives:
class _CMASolutionDict(_SolutionDict):
def __init__(self, *args, **kwargs):
# _SolutionDict.__init__(self, *args, **kwargs)
super(_CMASolutionDict, self).__init__(*args, **kwargs)
self.last_solution_index = 0
# TODO: insert takes 30% of the overall CPU time, mostly in def key()
# with about 15% of the overall CPU time
def insert(self, key, geno=None, iteration=None, fitness=None,
value=None, cma_norm=None):
"""insert an entry with key ``key`` and value
``value if value is not None else {'geno':key}`` and
``self[key]['kwarg'] = kwarg if kwarg is not None`` for the further kwargs.
"""
# archive returned solutions, first clean up archive
if iteration is not None and iteration > self.last_iteration and (iteration % 10) < 1:
self.truncate(300, iteration - 3)
elif value is not None and value.get('iteration'):
iteration = value['iteration']
if (iteration % 10) < 1:
self.truncate(300, iteration - 3)
self.last_solution_index += 1
if value is not None:
try:
iteration = value['iteration']
except:
pass
if iteration is not None:
if iteration > self.last_iteration:
self.last_solution_index = 0
self.last_iteration = iteration
else:
iteration = self.last_iteration + 0.5 # a hack to get a somewhat reasonable value
if value is not None:
self[key] = value
else:
self[key] = {'pheno': key}
if geno is not None:
self[key]['geno'] = geno
if iteration is not None:
self[key]['iteration'] = iteration
if fitness is not None:
self[key]['fitness'] = fitness
if cma_norm is not None:
self[key]['cma_norm'] = cma_norm
return self[key]
else: # if not use_archives:
class _CMASolutionDict(dict):
"""a hack to get most code examples running"""
def insert(self, *args, **kwargs):
pass
def get(self, key):
return None
def __getitem__(self, key):
return None
def __setitem__(self, key, value):
pass
# ____________________________________________________________
# ____________________________________________________________
# check out built-in package abc: class ABCMeta, abstractmethod, abstractproperty...
# see http://docs.python.org/whatsnew/2.6.html PEP 3119 abstract base classes
#
_debugging = False # not in use
_new_injections = True
_assertions_quadratic = True # issue warnings
_assertions_cubic = True
_depreciated = True
def cma_default_options_( # to get keyword completion back
# the follow string arguments are evaluated if they do not contain "filename"
AdaptSigma='True # or False or any CMAAdaptSigmaBase class e.g. CMAAdaptSigmaTPA, CMAAdaptSigmaCSA',
CMA_active='True # negative update, conducted after the original update',
# CMA_activefac='1 # learning rate multiplier for active update',
CMA_cmean='1 # learning rate for the mean value',
CMA_const_trace='False # normalize trace, 1, True, "arithm", "geom", "aeig", "geig" are valid',
CMA_diagonal='0*100*N/popsize**0.5 # nb of iterations with diagonal covariance matrix, True for always', # TODO 4/ccov_separable?
CMA_eigenmethod='np.linalg.eigh # or cma.utilities.math.eig or pygsl.eigen.eigenvectors',
CMA_elitist='False #v or "initial" or True, elitism likely impairs global search performance',
CMA_injections_threshold_keep_len='1 #v keep length if Mahalanobis length is below the given relative threshold',
CMA_mirrors='popsize < 6 # values <0.5 are interpreted as fraction, values >1 as numbers (rounded), otherwise about 0.16 is used',
CMA_mirrormethod='2 # 0=unconditional, 1=selective, 2=selective with delay',
CMA_mu='None # parents selection parameter, default is popsize // 2',
CMA_on='1 # multiplier for all covariance matrix updates',
# CMA_sample_on_sphere_surface='False #v replaced with option randn=cma.utilities.math.randhss, all mutation vectors have the same length, currently (with new_sampling) not in effect',
CMA_sampler='None # a class or instance that implements the interface of `cma.interfaces.StatisticalModelSamplerWithZeroMeanBaseClass`',
CMA_sampler_options='{} # options passed to `CMA_sampler` class init as keyword arguments',
CMA_rankmu='1.0 # multiplier for rank-mu update learning rate of covariance matrix',
CMA_rankone='1.0 # multiplier for rank-one update learning rate of covariance matrix',
CMA_recombination_weights='None # a list, see class RecombinationWeights, overwrites CMA_mu and popsize options',
CMA_dampsvec_fac='np.Inf # tentative and subject to changes, 0.5 would be a "default" damping for sigma vector update',
CMA_dampsvec_fade='0.1 # tentative fading out parameter for sigma vector update',
CMA_teststds='None # factors for non-isotropic initial distr. of C, mainly for test purpose, see CMA_stds for production',
CMA_stds='None # multipliers for sigma0 in each coordinate, not represented in C, makes scaling_of_variables obsolete',
# CMA_AII='False # not yet tested',
CSA_dampfac='1 #v positive multiplier for step-size damping, 0.3 is close to optimal on the sphere',
CSA_damp_mueff_exponent='0.5 # zero would mean no dependency of damping on mueff, useful with CSA_disregard_length option',
CSA_disregard_length='False #v True is untested, also changes respective parameters',
CSA_clip_length_value='None #v poorly tested, [0, 0] means const length N**0.5, [-1, 1] allows a variation of +- N/(N+2), etc.',
CSA_squared='False #v use squared length for sigma-adaptation ',
BoundaryHandler='BoundTransform # or BoundPenalty, unused when ``bounds in (None, [None, None])``',
bounds='[None, None] # lower (=bounds[0]) and upper domain boundaries, each a scalar or a list/vector',
# , eval_parallel2='not in use {"processes": None, "timeout": 12, "is_feasible": lambda x: True} # distributes function calls to processes processes'
# 'callback='None # function or list of functions called as callback(self) at the end of the iteration (end of tell)', # only necessary in fmin and optimize
conditioncov_alleviate='[1e8, 1e12] # when to alleviate the condition in the coordinates and in main axes',
eval_final_mean='True # evaluate the final mean, which is a favorite return candidate',
fixed_variables='None # dictionary with index-value pairs like {0:1.1, 2:0.1} that are not optimized',
ftarget='-inf #v target function value, minimization',
integer_variables='[] # index list, invokes basic integer handling: prevent std dev to become too small in the given variables',
is_feasible='is_feasible #v a function that computes feasibility, by default lambda x, f: f not in (None, np.NaN)',
maxfevals='inf #v maximum number of function evaluations',
maxiter='100 + 150 * (N+3)**2 // popsize**0.5 #v maximum number of iterations',
mean_shift_line_samples='False #v sample two new solutions colinear to previous mean shift',
mindx='0 #v minimal std in any arbitrary direction, cave interference with tol*',
minstd='0 #v minimal std (scalar or vector) in any coordinate direction, cave interference with tol*',
maxstd='inf #v maximal std in any coordinate direction',
pc_line_samples='False #v one line sample along the evolution path pc',
popsize='4+int(3*np.log(N)) # population size, AKA lambda, number of new solution per iteration',
randn='np.random.randn #v randn(lam, N) must return an np.array of shape (lam, N), see also cma.utilities.math.randhss',
scaling_of_variables='''None # deprecated, rather use fitness_transformations.ScaleCoordinates instead (or possibly CMA_stds).
Scale for each variable in that effective_sigma0 = sigma0*scaling. Internally the variables are divided by
scaling_of_variables and sigma is unchanged, default is `np.ones(N)`''',
seed='time # random number seed for `numpy.random`; `None` and `0` equate to `time`, `np.nan` means "do nothing", see also option "randn"',
signals_filename='cma_signals.in # read versatile options from this file (use `None` or `""` for no file) which contains a single options dict, e.g. ``{"timeout": 0}`` to stop, string-values are evaluated, e.g. "np.inf" is valid',
termination_callback='[] #v a function or list of functions returning True for termination, called in `stop` with `self` as argument, could be abused for side effects',
timeout='inf #v stop if timeout seconds are exceeded, the string "2.5 * 60**2" evaluates to 2 hours and 30 minutes',
tolconditioncov='1e14 #v stop if the condition of the covariance matrix is above `tolconditioncov`',
tolfacupx='1e3 #v termination when step-size increases by tolfacupx (diverges). That is, the initial step-size was chosen far too small and better solutions were found far away from the initial solution x0',
tolupsigma='1e20 #v sigma/sigma0 > tolupsigma * max(eivenvals(C)**0.5) indicates "creeping behavior" with usually minor improvements',
tolflatfitness='1 #v iterations tolerated with flat fitness before termination',
tolfun='1e-11 #v termination criterion: tolerance in function value, quite useful',
tolfunhist='1e-12 #v termination criterion: tolerance in function value history',
tolfunrel='0 #v termination criterion: relative tolerance in function value: Delta f current < tolfunrel * (median0 - median_min)',
tolstagnation='int(100 + 100 * N**1.5 / popsize) #v termination if no improvement over tolstagnation iterations',
tolx='1e-11 #v termination criterion: tolerance in x-changes',
transformation='''None # depreciated, use cma.fitness_transformations.FitnessTransformation instead.
[t0, t1] are two mappings, t0 transforms solutions from CMA-representation to f-representation (tf_pheno),
t1 is the (optional) back transformation, see class GenoPheno''',
typical_x='None # used with scaling_of_variables',
updatecovwait='None #v number of iterations without distribution update, name is subject to future changes', # TODO: rename: iterwaitupdatedistribution?
verbose='3 #v verbosity e.g. of initial/final message, -1 is very quiet, -9 maximally quiet, may not be fully implemented',
verb_append='0 # initial evaluation counter, if append, do not overwrite output files',
verb_disp='100 #v verbosity: display console output every verb_disp iteration',
verb_filenameprefix=CMADataLogger.default_prefix + ' # output path and filenames prefix',
verb_log='1 #v verbosity: write data to files every verb_log iteration, writing can be time critical on fast to evaluate functions',
verb_log_expensive='N * (N <= 50) # allow to execute eigendecomposition for logging every verb_log_expensive iteration, 0 or False for never',
verb_plot='0 #v in fmin(): plot() is called every verb_plot iteration',
verb_time='True #v output timings on console',
vv='{} #? versatile set or dictionary for hacking purposes, value found in self.opts["vv"]'
):
"""use this function to get keyword completion for `CMAOptions`.
``cma.CMAOptions('substr')`` provides even substring search.
returns default options as a `dict` (not a `cma.CMAOptions` `dict`).
"""
return dict(locals()) # is defined before and used by CMAOptions, so it can't return CMAOptions
cma_default_options = cma_default_options_() # will later be reassigned as CMAOptions(dict)
cma_versatile_options = tuple(sorted(k for (k, v) in cma_default_options.items()
if v.find(' #v ') > 0))
cma_allowed_options_keys = dict([s.lower(), s] for s in cma_default_options)
class CMAOptions(dict):
"""a dictionary with the available options and their default values
for class `CMAEvolutionStrategy`.
``CMAOptions()`` returns a `dict` with all available options and their
default values with a comment string.
``CMAOptions('verb')`` returns a subset of recognized options that
contain 'verb' in there keyword name or (default) value or
description.
``CMAOptions(opts)`` returns the subset of recognized options in
``dict(opts)``.
Option values can be "written" in a string and, when passed to `fmin`
or `CMAEvolutionStrategy`, are evaluated using "N" and "popsize" as
known values for dimension and population size (sample size, number
of new solutions per iteration). All default option values are given
as such a string.
Details
-------
`CMAOptions` entries starting with ``tol`` are termination
"tolerances".
For `tolstagnation`, the median over the first and the second half
of at least `tolstagnation` iterations are compared for both, the
per-iteration best and per-iteration median function value.
Example
-------
::
import cma
cma.CMAOptions('tol')
is a shortcut for ``cma.CMAOptions().match('tol')`` that returns all
options that contain 'tol' in their name or description.
To set an option::
import cma
opts = cma.CMAOptions()
opts.set('tolfun', 1e-12)
opts['tolx'] = 1e-11
todo: this class is overly complex and should be re-written, possibly
with reduced functionality.
:See also: `fmin` (), `CMAEvolutionStrategy`, `_CMAParameters`
"""
# @classmethod # self is the class, not the instance
# @property
# def default(self):
# """returns all options with defaults"""
# return fmin([],[])
@staticmethod
def defaults():
"""return a dictionary with default option values and description"""
return cma_default_options
# return dict((str(k), str(v)) for k, v in cma_default_options_().items())
# getting rid of the u of u"name" by str(u"name")
# return dict(cma_default_options)
@staticmethod
def versatile_options():
"""return list of options that can be changed at any time (not
only be initialized).
Consider that this list might not be entirely up
to date.
The string ' #v ' in the default value indicates a versatile
option that can be changed any time, however a string will not
necessarily be evaluated again.
"""
return cma_versatile_options
# return tuple(sorted(i[0] for i in list(CMAOptions.defaults().items()) if i[1].find(' #v ') > 0))
def check(self, options=None):
"""check for ambiguous keys and move attributes into dict"""
self.check_values(options)
self.check_attributes(options)
self.check_values(options)
return self
def check_values(self, options=None):
corrected_key = CMAOptions().corrected_key # caveat: infinite recursion
validated_keys = []
original_keys = []
if options is None:
options = self
for key in options:
correct_key = corrected_key(key)
if correct_key is None:
raise ValueError("""%s is not a valid option.\n"""
'Valid options are %s' %
(key, str(list(cma_default_options))))
if correct_key in validated_keys:
if key == correct_key:
key = original_keys[validated_keys.index(key)]
raise ValueError("%s was not a unique key for %s option"
% (key, correct_key))
validated_keys.append(correct_key)
original_keys.append(key)
return options
def check_attributes(self, opts=None):
"""check for attributes and moves them into the dictionary"""
if opts is None:
opts = self
if 11 < 3:
if hasattr(opts, '__dict__'):
for key in opts.__dict__:
if key not in self._attributes:
raise ValueError("""
Assign options with ``opts['%s']``
instead of ``opts.%s``
""" % (opts.__dict__.keys()[0],
opts.__dict__.keys()[0]))
return self
else:
# the problem with merge is that ``opts['ftarget'] = new_value``
# would be overwritten by the old ``opts.ftarget``.
# The solution here is to empty opts.__dict__ after the merge
if hasattr(opts, '__dict__'):
for key in list(opts.__dict__):
if key in self._attributes:
continue
utils.print_warning(
"""
An option attribute has been merged into the dictionary,
thereby possibly overwriting the dictionary value, and the
attribute has been removed. Assign options with
``opts['%s'] = value`` # dictionary assignment
or use
``opts.set('%s', value) # here isinstance(opts, CMAOptions)
instead of
``opts.%s = value`` # attribute assignment
""" % (key, key, key), 'check', 'CMAOptions')
opts[key] = opts.__dict__[key] # getattr(opts, key)
delattr(opts, key) # is that cosher?
# delattr is necessary to prevent that the attribute
# overwrites the dict entry later again
return opts
def __init__(self, s=None, **kwargs):
"""return an `CMAOptions` instance.
Return default options if ``s is None and not kwargs``,
or all options whose name or description contains `s`, if
`s` is a (search) string (case is disregarded in the match),
or with entries from dictionary `s` as options,
or with kwargs as options if ``s is None``,
in any of the latter cases not complemented with default options
or settings.
Returns: see above.
Details: as several options start with ``'s'``, ``s=value`` is
not valid as an option setting.
"""
# if not CMAOptions.defaults: # this is different from self.defaults!!!
# CMAOptions.defaults = fmin([],[])
if s is None and not kwargs:
super(CMAOptions, self).__init__(CMAOptions.defaults()) # dict.__init__(self, CMAOptions.defaults()) should be the same
# self = CMAOptions.defaults()
s = 'nocheck'
elif utils.is_str(s) and not s.startswith('unchecked'):
super(CMAOptions, self).__init__(CMAOptions().match(s))
# we could return here
s = 'nocheck'
elif isinstance(s, dict):
if kwargs:
raise ValueError('Dictionary argument must be the only argument')
super(CMAOptions, self).__init__(s)
elif kwargs and (s is None or s.startswith('unchecked')):
super(CMAOptions, self).__init__(kwargs)
else:
raise ValueError('The first argument must be a string or a dict or a keyword argument or `None`')
if not utils.is_str(s) or not s.startswith(('unchecked', 'nocheck')):
# was main offender
self.check() # caveat: infinite recursion
for key in list(self.keys()):
correct_key = self.corrected_key(key)
if correct_key not in CMAOptions.defaults():
utils.print_warning('invalid key ``' + str(key) +
'`` removed', '__init__', 'CMAOptions')
self.pop(key)
elif key != correct_key:
self[correct_key] = self.pop(key)
# self.evaluated = False # would become an option entry
self._lock_setting = False
self._attributes = self.__dict__.copy() # are not valid keys
self._attributes['_attributes'] = len(self._attributes)
def init(self, dict_or_str, val=None, warn=True):
"""initialize one or several options.
Arguments
---------
`dict_or_str`
a dictionary if ``val is None``, otherwise a key.
If `val` is provided `dict_or_str` must be a valid key.
`val`
value for key
Details
-------
Only known keys are accepted. Known keys are in `CMAOptions.defaults()`
"""
# dic = dict_or_key if val is None else {dict_or_key:val}
self.check(dict_or_str)
dic = dict_or_str
if val is not None:
dic = {dict_or_str:val}
for key, val in dic.items():
key = self.corrected_key(key)
if key not in CMAOptions.defaults():
# TODO: find a better solution?
if warn:
print('Warning in cma.CMAOptions.init(): key ' +
str(key) + ' ignored')
else:
self[key] = val
return self
def set(self, dic, val=None, force=False):
"""assign versatile options.
Method `CMAOptions.versatile_options` () gives the versatile
options, use `init()` to set the others.
Arguments
---------
`dic`
either a dictionary or a key. In the latter
case, `val` must be provided
`val`
value for `key`, approximate match is sufficient
`force`
force setting of non-versatile options, use with caution
This method will be most probably used with the ``opts`` attribute of
a `CMAEvolutionStrategy` instance.
"""
if val is not None: # dic is a key in this case
dic = {dic:val} # compose a dictionary
for key_original, val in list(dict(dic).items()):
key = self.corrected_key(key_original)
if (not self._lock_setting or
key in CMAOptions.versatile_options() or
force):
self[key] = val
else:
utils.print_warning('key ' + str(key_original) +
' ignored (not recognized as versatile)',
'set', 'CMAOptions')
return self # to allow o = CMAOptions(o).set(new)
def complement(self):
"""add all missing options with their default values"""
# add meta-parameters, given options have priority
self.check()
for key in CMAOptions.defaults():
if key not in self:
self[key] = CMAOptions.defaults()[key]
return self
@property
def settable(self):
"""return the subset of those options that are settable at any
time.
Settable options are in `versatile_options` (), but the
list might be incomplete.
"""
return CMAOptions(dict(i for i in list(self.items())
if i[0] in CMAOptions.versatile_options()))
def __call__(self, key, default=None, loc=None):
"""evaluate and return the value of option `key` on the fly, or
return those options whose name or description contains `key`,
case disregarded.
Details
-------
Keys that contain `filename` are not evaluated.
For ``loc==None``, `self` is used as environment
but this does not define ``N``.
:See: `eval()`, `evalall()`
"""
try:
val = self[key]
except:
return self.match(key)
if loc is None:
loc = self # TODO: this hack is not so useful: popsize could be there, but N is missing
try:
if utils.is_str(val):
val = val.split('#')[0].strip() # remove comments
if key.find('filename') < 0:
# and key.find('mindx') < 0:
val = eval(val, globals(), loc)
# invoke default
# TODO: val in ... fails with array type, because it is applied element wise!
# elif val in (None,(),[],{}) and default is not None:
elif val is None and default is not None:
val = eval(str(default), globals(), loc)
except:
pass # slighly optimistic: the previous is bug-free
return val
def corrected_key(self, key):
"""return the matching valid key, if ``key.lower()`` is a unique
starting sequence to identify the valid key, ``else None``
"""
matching_keys = []
key = key.lower() # this was somewhat slow, so it is speed optimized now
if key in cma_allowed_options_keys:
return cma_allowed_options_keys[key]
for allowed_key in cma_allowed_options_keys:
if allowed_key.startswith(key):
if len(matching_keys) > 0:
return None
matching_keys.append(allowed_key)
return matching_keys[0] if len(matching_keys) == 1 else None
def eval(self, key, default=None, loc=None, correct_key=True):
"""Evaluates and sets the specified option value in
environment `loc`. Many options need ``N`` to be defined in
`loc`, some need `popsize`.
Details
-------
Keys that contain 'filename' are not evaluated.
For `loc` is None, the self-dict is used as environment
:See: `evalall()`, `__call__`
"""
# TODO: try: loc['dim'] = loc['N'] etc
if correct_key:
# in_key = key # for debugging only
key = self.corrected_key(key)
self[key] = self(key, default, loc)
return self[key]
def evalall(self, loc=None, defaults=None):
"""Evaluates all option values in environment `loc`.
:See: `eval()`
"""
self.check()
if defaults is None:
defaults = cma_default_options_()
# TODO: this needs rather the parameter N instead of loc
if 'N' in loc: # TODO: __init__ of CMA can be simplified
popsize = self('popsize', defaults['popsize'], loc)
for k in list(self.keys()):
k = self.corrected_key(k)
self.eval(k, defaults[k],
{'N':loc['N'], 'popsize':popsize})
self._lock_setting = True
return self
def match(self, s=''):
"""return all options that match, in the name or the description,
with string `s`, case is disregarded.
Example: ``cma.CMAOptions().match('verb')`` returns the verbosity
options.
"""
match = s.lower()
res = {}
for k in sorted(self):
s = str(k) + '=\'' + str(self[k]) + '\''
if match in s.lower():
res[k] = self[k]
return CMAOptions(res)
@property
def to_namedtuple(self):
"""return options as const attributes of the returned object,
only useful for inspection. """
raise NotImplementedError
# return collections.namedtuple('CMAOptionsNamedTuple',
# self.keys())(**self)
def from_namedtuple(self, t):
"""update options from a `collections.namedtuple`.
:See also: `to_namedtuple`
"""
return self.update(t._asdict())
def pprint(self, linebreak=80):
for i in sorted(self.items()):
s = str(i[0]) + "='" + str(i[1]) + "'"
a = s.split(' ')
# print s in chunks
l = '' # start entire to the left
while a:
while a and len(l) + len(a[0]) < linebreak:
l += ' ' + a.pop(0)
print(l)
l = ' ' # tab for subsequent lines
try:
collections.namedtuple
except:
pass
else:
class CMAEvolutionStrategyResult(collections.namedtuple(
'CMAEvolutionStrategyResult', [
'xbest',
'fbest',
'evals_best',
'evaluations',
'iterations',
'xfavorite',
'stds',
'stop',
])):
"""A results tuple from `CMAEvolutionStrategy` property ``result``.
This tuple contains in the given position and as attribute
- 0 ``xbest`` best solution evaluated
- 1 ``fbest`` objective function value of best solution
- 2 ``evals_best`` evaluation count when ``xbest`` was evaluated
- 3 ``evaluations`` evaluations overall done
- 4 ``iterations``
- 5 ``xfavorite`` distribution mean in "phenotype" space, to be
considered as current best estimate of the optimum
- 6 ``stds`` effective standard deviations, can be used to
compute a lower bound on the expected coordinate-wise distance
to the true optimum, which is (very) approximately stds[i] *
dimension**0.5 / min(mueff, dimension) / 1.5 / 5 ~ std_i *
dimension**0.5 / min(popsize / 2, dimension) / 5, where
dimension = CMAEvolutionStrategy.N and mueff =
CMAEvolutionStrategy.sp.weights.mueff ~ 0.3 * popsize.
- 7 ``stop`` termination conditions in a dictionary
The penalized best solution of the last completed iteration can be
accessed via attribute ``pop_sorted[0]`` of `CMAEvolutionStrategy`
and the respective objective function value via ``fit.fit[0]``.
Details:
- This class is of purely declarative nature and for providing
this docstring. It does not provide any further functionality.
- ``list(fit.fit).find(0)`` is the index of the first sampled
solution of the last completed iteration in ``pop_sorted``.
"""
cma_default_options = CMAOptions(cma_default_options_())
class _CMAEvolutionStrategyResult(tuple):
"""A results tuple from `CMAEvolutionStrategy` property ``result``.
This tuple contains in the given position
- 0 best solution evaluated, ``xbest``
- 1 objective function value of best solution, ``f(xbest)``
- 2 evaluation count when ``xbest`` was evaluated
- 3 evaluations overall done
- 4 iterations
- 5 distribution mean in "phenotype" space, to be considered as
current best estimate of the optimum
- 6 effective standard deviations, give a lower bound on the expected