-
Notifications
You must be signed in to change notification settings - Fork 0
/
bbobbenchmarks.py
2189 lines (1790 loc) · 69.2 KB
/
bbobbenchmarks.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""BBOB noiseless testbed.
The optimisation test functions are represented as classes `F1` to
`F24` (and `F101` to `F130`).
This module implements the class `BBOBFunction` and
sub-classes:
* class `BBOBNfreeFunction` which have all the methods common to the
classes `F1` to `F24`
* classes `BBOBGaussFunction`, `BBOBCauchyFunction`,
`BBOBUniformFunction` which have methods in classes from
`F101` to `F130`
Module attributes:
* `dictbbob` is a dictionary such that dictbbob[2] contains
the test function class F2 and f2 = dictbbob[2]() returns
the instance 0 of the test function that can be
called as f2([1,2,3]).
* `nfreeIDs` == range(1,25) indices for the noiseless functions that can be
found in dictbbob
* `noisyIDs` == range(101, 131) indices for the noisy functions that can be
found in dictbbob. We have nfreeIDs + noisyIDs == sorted(dictbbob.keys())
* `nfreeinfos` function infos
Examples:
>>> from cma import bbobbenchmarks as bn
>>> for s in bn.nfreeinfos:
... print(s)
1: Noise-free Sphere function
2: Separable ellipsoid with monotone transformation
<BLANKLINE>
Parameter: condition number (default 1e6)
<BLANKLINE>
<BLANKLINE>
3: Rastrigin with monotone transformation separable "condition" 10
4: skew Rastrigin-Bueche, condition 10, skew-"condition" 100
5: Linear slope
6: Attractive sector function
7: Step-ellipsoid, condition 100, noise-free
8: Rosenbrock noise-free
9: Rosenbrock, rotated
10: Ellipsoid with monotone transformation, condition 1e6
11: Discus (tablet) with monotone transformation, condition 1e6
12: Bent cigar with asymmetric space distortion, condition 1e6
13: Sharp ridge
14: Sum of different powers, between x^2 and x^6, noise-free
15: Rastrigin with asymmetric non-linear distortion, "condition" 10
16: Weierstrass, condition 100
17: Schaffers F7 with asymmetric non-linear transformation, condition 10
18: Schaffers F7 with asymmetric non-linear transformation, condition 1000
19: F8F2 sum of Griewank-Rosenbrock 2-D blocks, noise-free
20: Schwefel with tridiagonal variable transformation
21: Gallagher with 101 Gaussian peaks, condition up to 1000, one global rotation, noise-free
22: Gallagher with 21 Gaussian peaks, condition up to 1000, one global rotation
23: Katsuura function
24: Lunacek bi-Rastrigin, condition 100
<BLANKLINE>
in PPSN 2008, Rastrigin part rotated and scaled
<BLANKLINE>
<BLANKLINE>
>>> f3 = bn.F3(13) # instantiate instance 13 of function f3
>>> f3([0, 1, 2]) # short-cut for f3.evaluate([0, 1, 2]) # doctest:+ELLIPSIS
59.8733529...
>>> print(bn.instantiate(5)[1]) # returns function instance and optimal f-value
51.53
>>> print(bn.nfreeIDs) # list noise-free functions
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
>>> for i in bn.nfreeIDs: # evaluate all noiseless functions once
... print(bn.instantiate(i)[0]([0., 0., 0., 0.])) # doctest:+ELLIPSIS
-77.2745459...
6180022.8217...
92.987750752...
92.987750752...
140.51011761...
70877.955412...
-72.550520219...
33355.792472...
-339.94
4374717.4934...
15631566.348...
4715481.086...
550.59978390...
-17.299175622...
27.363312851...
-227.82783352...
-24.330591878...
131.42015934...
40.710373742...
6160.8178292...
376.74688954...
107.83042676...
220.48226655...
106.09476738...
"""
# TODO: define interface for this module.
# TODO: funId is expected to be a number since it is used as rseed.
from __future__ import print_function
try:
xrange
except NameError:
xrange = range
import warnings
from pdb import set_trace
import numpy as np
from math import floor as floor
from numpy import dot, linspace, diag, tile, zeros, sign, resize
from numpy.random import standard_normal as _randn # TODO: may bring confusion
from numpy.random import random as _rand # TODO: may bring confusion
"""
% VAL = BENCHMARKS(X, FUNCID)
% VAL = BENCHMARKS(X, STRFUNC)
% Input:
% X -- solution column vector or matrix of column vectors
% FUNCID -- number of function to be executed with X as input,
% by default 8.
% STRFUNC -- function as string to be executed with X as input
% Output: function value(s) of solution(s)
% Examples:
% F = BENCHMARKS([1 2 3]', 17);
% F = BENCHMARKS([1 2 3]', 'f1');
%
% NBS = BENCHMARKS()
% NBS = BENCHMARKS('FunctionIndices')
% Output:
% NBS -- array of valid benchmark function numbers,
% presumably 1:24
%
% FHS = BENCHMARKS('handles')
% Output:
% FHS -- cell array of function handles
% Examples:
% FHS = BENCHMARKS('handles');
% f = FHS{1}(x); % evaluates x on the sphere function f1
% f = feval(FHS{1}, x); % ditto
%
% see also: functions FGENERIC, BENCHMARKINFOS, BENCHMARKSNOISY
% Authors (copyright 2009): Nikolaus Hansen, Raymond Ros, Steffen Finck
% Version = 'Revision: $Revision: 1115 $'
% Last Modified: $Date: 2009-02-09 19:22:42 +0100 (Mon, 09 Feb 2009) $
% INTERFACE OF BENCHMARK FUNCTIONS
% FHS = BENCHMARKS('handles');
% FUNC = FHS{1};
%
% [FVALUE, FTRUE] = FUNC(X)
% [FVALUE, FTRUE] = FUNC(X, [], IINSTANCE)
% Input: X -- matrix of column vectors
% IINSTANCE -- instance number of the function, sets function
% instance (XOPT, FOPT, rotation matrices,...)
% up until a new number is set, or the function is
% cleared. Default is zero.
% Output: row vectors with function value for each input column
% FVALUE -- function value
% FTRUE -- noise-less, deterministic function value
% [FOPT STRFUNCTION] = FUNC('any_even_empty_string', ...)
% Output:
% FOPT -- function value at optimum
% STRFUNCTION -- not yet implemented: function description string, ID before first whitespace
% [FOPT STRFUNCTION] = FUNC('any_even_empty_string', DIM, NTRIAL)
% Sets rotation matrices and xopt depending on NTRIAL (by changing the random seed).
% Output:
% FOPT -- function value at optimum
% STRFUNCTION -- not yet implemented: function description string, ID before first whitespace
% [FOPT, XOPT] = FUNC('xopt', DIM)
% Output:
% FOPT -- function value at optimum XOPT
% XOPT -- optimal solution vector in DIM-D
% [FOPT, MATRIX] = FUNC('linearTF', DIM) % might vanish in future
% Output:
% FOPT -- function value at optimum XOPT
% MATRIX -- used transformation matrix
"""
### FUNCTION DEFINITION ###
def compute_xopt(rseed, dim):
"""Generate a random vector used as optimum argument.
Rounded by four digits, but never to zero.
"""
xopt = 8 * np.floor(1e4 * unif(dim, rseed)) / 1e4 - 4
idx = (xopt == 0)
xopt[idx] = -1e-5
return xopt
def compute_rotation(seed, dim):
"""Returns an orthogonal basis."""
B = np.reshape(gauss(dim * dim, seed), (dim, dim))
for i in range(dim):
for j in range(0, i):
B[i] = B[i] - dot(B[i], B[j]) * B[j]
B[i] = B[i] / (np.sum(B[i]**2) ** .5)
return B
def monotoneTFosc(f, osz_fac=0.49):
"""Maps [-inf,inf] to [-inf,inf] with different constants
for positive and negative part.
"""
if np.isscalar(f):
if f > 0.:
f = np.log(f) / 0.1
f = np.exp(f + osz_fac * (np.sin(f) + np.sin(0.79 * f))) ** 0.1
elif f < 0.:
f = np.log(-f) / 0.1
f = -np.exp(f + osz_fac * (np.sin(0.55 * f) + np.sin(0.31 * f))) ** 0.1
return f
else:
f = np.asarray(f)
g = f.copy()
idx = (f > 0)
g[idx] = np.log(f[idx]) / 0.1
g[idx] = np.exp(g[idx] + osz_fac * (np.sin(g[idx]) + np.sin(0.79 * g[idx])))**0.1
idx = (f < 0)
g[idx] = np.log(-f[idx]) / 0.1
g[idx] = -np.exp(g[idx] + osz_fac * (np.sin(0.55 * g[idx]) + np.sin(0.31 * g[idx])))**0.1
return g
def defaultboundaryhandling(x, fac):
"""Returns a float penalty for being outside of boundaries [-5, 5]"""
xoutside = np.maximum(0., np.abs(x) - 5) * sign(x)
fpen = fac * np.sum(xoutside**2, -1) # penalty
return fpen
def gauss(N, seed):
"""Samples N standard normally distributed numbers
being the same for a given seed
"""
r = unif(2 * N, seed)
g = np.sqrt(-2 * np.log(r[:N])) * np.cos(2 * np.pi * r[N:2*N])
if np.any(g == 0.):
g[g == 0] = 1e-99
return g
def unif(N, inseed):
"""Generates N uniform numbers with starting seed."""
# initialization
inseed = np.abs(inseed)
if inseed < 1.:
inseed = 1.
rgrand = 32 * [0.]
aktseed = inseed
for i in xrange(39, -1, -1):
tmp = floor(aktseed / 127773.)
aktseed = 16807. * (aktseed - tmp * 127773.) - 2836. * tmp
if aktseed < 0:
aktseed = aktseed + 2147483647.
if i < 32:
rgrand[i] = aktseed
aktrand = rgrand[0]
# sample numbers
r = int(N) * [0.]
for i in xrange(int(N)):
tmp = floor(aktseed / 127773.)
aktseed = 16807. * (aktseed - tmp * 127773.) - 2836. * tmp
if aktseed < 0:
aktseed = aktseed + 2147483647.
tmp = int(floor(aktrand / 67108865.))
aktrand = rgrand[tmp]
rgrand[tmp] = aktseed
r[i] = aktrand / 2.147483647e9
r = np.asarray(r)
if (r == 0).any():
warnings.warn('zero sampled(?), set to 1e-99')
r[r == 0] = 1e-99
return r
# for testing and comparing to other implementations,
# myrand and myrandn are used only for sampling the noise
# Rename to myrand and myrandn to rand and randn and
# comment lines 24 and 25.
_randomnseed = 30. # warning this is a global variable...
def _myrandn(size):
"""Normal random distribution sampling.
For testing and comparing purpose.
"""
global _randomnseed
_randomnseed = _randomnseed + 1.
if _randomnseed > 1e9:
_randomnseed = 1.
res = np.reshape(gauss(np.prod(size), _randomnseed), size)
return res
_randomseed = 30. # warning this is a global variable...
def _myrand(size):
"""Uniform random distribution sampling.
For testing and comparing purpose.
"""
global _randomseed
_randomseed = _randomseed + 1
if _randomseed > 1e9:
_randomseed = 1
res = np.reshape(unif(np.prod(size), _randomseed), size)
return res
def fGauss(ftrue, beta):
"""Returns Gaussian model noisy value."""
# expects ftrue to be a np.array
popsi = np.shape(ftrue)
fval = ftrue * np.exp(beta * _randn(popsi)) # with gauss noise
tol = 1e-8
fval = fval + 1.01 * tol
idx = ftrue < tol
try:
fval[idx] = ftrue[idx]
except (IndexError, TypeError): # fval is a scalar
if idx:
fval = ftrue
return fval
def fUniform(ftrue, alpha, beta):
"""Returns uniform model noisy value."""
# expects ftrue to be a np.array
popsi = np.shape(ftrue)
fval = (_rand(popsi) ** beta * ftrue *
np.maximum(1., (1e9 / (ftrue + 1e-99)) ** (alpha * _rand(popsi))))
tol = 1e-8
fval = fval + 1.01 * tol
idx = ftrue < tol
try:
fval[idx] = ftrue[idx]
except (IndexError, TypeError): # fval is a scalar
if idx:
fval = ftrue
return fval
def fCauchy(ftrue, alpha, p):
"""Returns Cauchy model noisy value
Cauchy with median 1e3*alpha and with p=0.2, zero otherwise
P(Cauchy > 1,10,100,1000) = 0.25, 0.032, 0.0032, 0.00032
"""
# expects ftrue to be a np.array
popsi = np.shape(ftrue)
fval = ftrue + alpha * np.maximum(0., 1e3 + (_rand(popsi) < p) *
_randn(popsi) / (np.abs(_randn(popsi)) + 1e-199))
tol = 1e-8
fval = fval + 1.01 * tol
idx = ftrue < tol
try:
fval[idx] = ftrue[idx]
except (IndexError, TypeError): # fval is a scalar
if idx:
fval = ftrue
return fval
### CLASS DEFINITION ###
class AbstractTestFunction(object):
"""Abstract class for test functions.
Defines methods to be implemented in test functions which are to be
provided to method setfun of class Logger.
In particular, (a) the attribute fopt and (b) the method _evalfull.
The _evalfull method returns two values, the possibly noisy value and
the noise-free value. The latter is only meant to be for recording purpose.
"""
def __call__(self, x): # makes the instances callable
"""Returns the objective function value of argument x.
Example:
>>> from cma import bbobbenchmarks as bn
>>> f3 = bn.F3(13) # instantiate function 3 on instance 13
>>> 59.8733529 < f3([0, 1, 2]) < 59.87335292 # call f3, same as f3.evaluate([0, 1, 2])
True
"""
if len(x.shape) > 1:
self.n_evaluations += x.shape[0]
self.evaluations += x.shape[0]
else:
self.n_evaluations += 1
self.evaluations += 1
y = self.evaluate(x)
if np.min(y) - self.getfopt() < 1e-8:
self.final_target_hit = True
return y
def evaluate(self, x):
"""Returns the objective function value (in case noisy).
"""
ftrue = self._evalfull(x)[0]
if self.step:
if len(x.shape) > 1:
ftrue = np.where(np.any(x[:, 0:self.dim-1] > 0, axis=1), ftrue + 100, ftrue)
else:
if np.any(x[0:self.dim-1] > 0):
ftrue = ftrue + 100
return ftrue
# TODO: is it better to leave evaluate out and check for hasattr('evaluate') in ExpLogger?
def _evalfull(self, x):
"""return noisy and noise-free value, the latter for recording purpose. """
raise NotImplementedError
def getfopt(self):
"""Returns the best function value of this instance of the function."""
# TODO: getfopt error:
# import bbobbenchmarks as bb
# bb.instantiate(1)[0].getfopt()
# AttributeError: F1 instance has no attribute '_fopt'
if not hasattr(self, 'iinstance'):
raise Exception('This function class has not been instantiated yet.')
return self._fopt
def setfopt(self, fopt):
try:
self._fopt = float(fopt)
except ValueError:
raise Exception('Optimal function value must be cast-able to a float.')
fopt = property(getfopt, setfopt)
class BBOBFunction(AbstractTestFunction):
"""Abstract class of BBOB test functions.
Implements some base functions that are used by the test functions
of BBOB such as initialisations of class attributes.
"""
def __init__(self, iinstance=0, zerox=False, zerof=False, param=None, **kwargs):
"""Common initialisation.
Keyword arguments:
iinstance -- instance of the function (int)
zerox -- sets xopt to [0, ..., 0]
zerof -- sets fopt to 0
param -- parameter of the function (if applicable)
kwargs -- additional attributes
"""
# Either self.rrseed or self.funId have to be defined for BBOBFunctions
# TODO: enforce
try:
rrseed = self.rrseed
except AttributeError:
rrseed = self.funId
try:
self.rseed = rrseed + 1e4 * iinstance
except TypeError:
# rrseed AND iinstance have to be float
warnings.warn('self.rseed could not be set, reset to 1 instead.')
self.rseed = 1
self.zerox = zerox
if zerof:
self.fopt = 0.
else:
self.fopt = min(1000, max(-1000, (np.round(100 * 100 * gauss(1, self.rseed)[0] / gauss(1, self.rseed + 1)[0]) / 100)))
self.iinstance = iinstance
self.dim = None
self.lastshape = None
self.param = param
self.step = False
for i, v in kwargs.items():
setattr(self, i, v)
self._xopt = None
self.n_evaluations = 0
self.evaluations = 0
self.final_target_hit = False
def shape_(self, x):
# this part is common to all evaluate function
# it is assumed x are row vectors
curshape = np.shape(x)
dim = np.shape(x)[-1]
return curshape, dim
def getiinstance(self):
"""Designates the instance of the function class.
An instance in this case means a given target function value, a
given optimal argument x, and given transformations for the
function. It needs to have a string representation. Preferably
it should be a number or a string.
"""
return self._iinstance
def setiinstance(self, iinstance):
self._iinstance = iinstance
iinstance = property(getiinstance, setiinstance)
def shortstr(self):
"""Gives a short string self representation (shorter than str(self))."""
res = 'F%s' % str(self.funId)
if hasattr(self, 'param'):
res += '_p%s' % str(self.param) # NH param -> self.param
return res
def __eq__(self, obj):
return (self.funId == obj.funId
and (not hasattr(self, 'param') or self.param == obj.param))
# TODO: make this test on other attributes than param?
# def dimensionality(self, dim):
# """Return the availability of dimensionality dim."""
# return True
# GETTERS
# def getfopt(self):
# """Optimal Function Value."""
# return self._fopt
# fopt = property(getfopt)
def _setxopt(self, xopt):
"""Return the argument of the optimum of the function."""
self._xopt = xopt
def _getxopt(self):
"""Return the argument of the optimum of the function."""
if self._xopt is None:
warnings.warn('You need to evaluate object to set dimension first.')
return self._xopt
xopt = property(_getxopt, _setxopt)
# def getrange(self):
# """Return the domain of the function."""
# #TODO: could depend on the dimension
# # TODO: return exception NotImplemented yet
# pass
# range = property(getrange)
# def getparam(self):
# """Optional parameter value."""
# return self._param
# param = property(getparam)
# def getitrial(self):
# """Instance id number."""
# return self._itrial
# itrial = property(getitrial)
# def getlinearTf(self):
# return self._linearTf
# linearTf = property(getlinearTf)
# def getrotation(self):
# return self._rotation
# rotation = property(getrotation)
class BBOBNfreeFunction(BBOBFunction):
"""Class of the noise-free functions of BBOB."""
def noise(self, ftrue):
"""Returns the noise-free function values."""
return ftrue.copy()
class BBOBGaussFunction(BBOBFunction):
"""Class of the Gauss noise functions of BBOB.
Attribute gaussbeta needs to be defined by inheriting classes.
"""
# gaussbeta = None
def noise(self, ftrue):
"""Returns the noisy function values."""
return fGauss(ftrue, self.gaussbeta)
def boundaryhandling(self, x):
return defaultboundaryhandling(x, 100.)
class BBOBUniformFunction(BBOBFunction, object):
"""Class of the uniform noise functions of BBOB.
Attributes unifalphafac and unifbeta need to be defined by inheriting
classes.
"""
# unifalphafac = None
# unifbeta = None
def noise(self, ftrue):
"""Returns the noisy function values."""
return fUniform(ftrue, self.unifalphafac * (0.49 + 1. / self.dim), self.unifbeta)
def boundaryhandling(self, x):
return defaultboundaryhandling(x, 100.)
class BBOBCauchyFunction(BBOBFunction):
"""Class of the Cauchy noise functions of BBOB.
Attributes cauchyalpha and cauchyp need to be defined by inheriting
classes.
"""
# cauchyalpha = None
# cauchyp = None
def noise(self, ftrue):
"""Returns the noisy function values."""
return fCauchy(ftrue, self.cauchyalpha, self.cauchyp)
def boundaryhandling(self, x):
return defaultboundaryhandling(x, 100.)
class _FSphere(BBOBFunction):
"""Abstract Sphere function.
Method boundaryhandling needs to be defined.
"""
rrseed = 1
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
# BOUNDARY HANDLING
fadd = fadd + self.boundaryhandling(x)
# TRANSFORMATION IN SEARCH SPACE
x = x - self.arrxopt # cannot be replaced with x -= arrxopt!
# COMPUTATION core
ftrue = np.sum(x**2, -1)
fval = self.noise(ftrue)
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
class F1(_FSphere, BBOBNfreeFunction):
"""Noise-free Sphere function"""
funId = 1
def boundaryhandling(self, x):
return 0.
class F101(_FSphere, BBOBGaussFunction):
"""Sphere with moderate Gauss noise"""
funId = 101
gaussbeta = 0.01
class F102(_FSphere, BBOBUniformFunction):
"""Sphere with moderate uniform noise"""
funId = 102
unifalphafac = 0.01
unifbeta = 0.01
class F103(_FSphere, BBOBCauchyFunction):
"""Sphere with moderate Cauchy noise"""
funId = 103
cauchyalpha = 0.01
cauchyp = 0.05
class F107(_FSphere, BBOBGaussFunction):
"""Sphere with Gauss noise"""
funId = 107
gaussbeta = 1.
class F108(_FSphere, BBOBUniformFunction):
"""Sphere with uniform noise"""
funId = 108
unifalphafac = 1.
unifbeta = 1.
class F109(_FSphere, BBOBCauchyFunction):
"""Sphere with Cauchy noise"""
funId = 109
cauchyalpha = 1.
cauchyp = 0.2
class F2(BBOBNfreeFunction):
"""Separable ellipsoid with monotone transformation
Parameter: condition number (default 1e6)
"""
funId = 2
paramValues = (1e0, 1e6)
condition = 1e6
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
if hasattr(self, 'param') and self.param: # not self.param is None
tmp = self.param
else:
tmp = self.condition
self.scales = tmp ** linspace(0, 1, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
# TRANSFORMATION IN SEARCH SPACE
x = x - self.arrxopt # cannot be replaced with x -= arrxopt!
# COMPUTATION core
ftrue = dot(monotoneTFosc(x)**2, self.scales)
fval = self.noise(ftrue) # without noise
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
class F3(BBOBNfreeFunction):
"""Rastrigin with monotone transformation separable "condition" 10"""
funId = 3
condition = 10.
beta = 0.2
def initwithsize(self, curshape, dim):
# DIM-dependent initialisation
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
self.arrscales = resize(self.scales, curshape)
self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape)
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
# BOUNDARY HANDLING
# TRANSFORMATION IN SEARCH SPACE
x = x - self.arrxopt
x = monotoneTFosc(x)
idx = (x > 0)
x[idx] = x[idx] ** (1 + self.arrexpo[idx] * np.sqrt(x[idx]))
x = self.arrscales * x
# COMPUTATION core
ftrue = 10 * (self.dim - np.sum(np.cos(2 * np.pi * x), -1)) + np.sum(x ** 2, -1)
fval = self.noise(ftrue) # without noise
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
class F4(BBOBNfreeFunction):
"""skew Rastrigin-Bueche, condition 10, skew-"condition" 100"""
funId = 4
condition = 10.
alpha = 100.
maxindex = np.inf # 1:2:min(DIM,maxindex) are the skew variables
rrseed = 3
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.xopt[:min(dim, self.maxindex):2] = abs(self.xopt[:min(dim, self.maxindex):2])
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
self.arrscales = resize(self.scales, curshape)
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
# BOUNDARY HANDLING
xoutside = np.maximum(0., np.abs(x) - 5) * sign(x)
fpen = 1e2 * np.sum(xoutside**2, -1) # penalty
fadd = fadd + fpen # self.fadd becomes an array
# TRANSFORMATION IN SEARCH SPACE
x = x - self.arrxopt # shift optimum to zero
x = monotoneTFosc(x)
try:
tmpx = x[:, :min(self.dim, self.maxindex):2] # tmpx is a reference to a part of x
except IndexError:
tmpx = x[:min(self.dim, self.maxindex):2] # tmpx is a reference to a part of x
tmpx[tmpx > 0] = self.alpha ** .5 * tmpx[tmpx > 0] # this modifies x
x = self.arrscales * x # scale while assuming that Xopt == 0
# COMPUTATION core
ftrue = 10 * (self.dim - np.sum(np.cos(2 * np.pi * x), -1)) + np.sum(x ** 2, -1)
fval = self.noise(ftrue)
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
class F5(BBOBNfreeFunction):
"""Linear slope"""
funId = 5
alpha = 100.
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim) # TODO: what happens here?
else:
self.xopt = 5 * sign(compute_xopt(self.rseed, dim))
self.scales = -sign(self.xopt) * (self.alpha ** .5) ** linspace(0, 1, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
fadd = fadd + 5 * np.sum(np.abs(self.scales))
# BOUNDARY HANDLING
# move "too" good coordinates back into domain
x = np.array(x) # convert x and make a copy of x.
# The following may modify x directly.
idx_out_of_bounds = (x * self.arrxopt) > 25 # 25 == 5 * 5
x[idx_out_of_bounds] = sign(x[idx_out_of_bounds]) * 5
# TRANSFORMATION IN SEARCH SPACE
# COMPUTATION core
ftrue = dot(x, self.scales)
fval = self.noise(ftrue)
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
class F6(BBOBNfreeFunction):
"""Attractive sector function"""
funId = 6
condition = 10.
alpha = 100.
osz_fac = 0.49
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.rotation = compute_rotation(self.rseed + 1e6, dim)
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
# decouple scaling from function definition
self.linearTF = dot(self.linearTF, self.rotation)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
def _evalfull(self, x):
fadd = self.fopt
curshape, dim = self.shape_(x)
# it is assumed x are row vectors
if self.lastshape != curshape:
self.initwithsize(curshape, dim)
# TRANSFORMATION IN SEARCH SPACE
x = x - self.arrxopt # cannot be replaced with x -= arrxopt!
x = dot(x, self.linearTF) # TODO: check
# COMPUTATION core
idx = (x * self.arrxopt) > 0
x[idx] = self.alpha * x[idx]
ftrue = monotoneTFosc(np.sum(x**2, -1), self.osz_fac) ** .9
fval = self.noise(ftrue)
# FINALIZE
ftrue += fadd
fval += fadd
return fval, ftrue
class _FStepEllipsoid(BBOBFunction):
"""Abstract Step-ellipsoid, condition 100
Method boundaryhandling needs to be defined.
"""
rrseed = 7
condition = 100.