/
manipulator.py
executable file
·1858 lines (1525 loc) · 57.6 KB
/
manipulator.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
from __future__ import division
# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab autoindent smarttab
from builtins import str
from builtins import map
from builtins import range
from past.utils import old_div
from builtins import object
import abc
import collections
import copy
import hashlib
import json
import logging
import math
import os
import pickle
import random
from fn import _
import argparse
from datetime import datetime
import numpy
import inspect
import sys
from future.utils import with_metaclass
from functools import reduce
log = logging.getLogger(__name__)
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('--list-params', '-lp',
help='list available parameter classes')
class ConfigurationManipulatorBase(with_metaclass(abc.ABCMeta, object)):
"""
abstract interface for objects used by search techniques to mutate
configurations
"""
# List of file formats, which can be extended by subclasses. Used in
# write_to_file() and load_from_file(). Objects in list must define
# load(fd) and dump(cfg, fd).
FILE_FORMATS = {'default': json, 'json': json,
'pickle': pickle, 'pk': pickle}
def validate(self, config):
"""is the given config valid???"""
return all(map(_.validate(config), self.parameters(config)))
def normalize(self, config):
"""mutate config into canonical form"""
for param in self.parameters(config):
param.normalize(config)
def set_search_driver(self, search_driver):
"""called exactly once during setup"""
pass
def copy(self, config):
"""produce copy of config"""
return copy.deepcopy(config)
def parameters_dict(self, config):
"""convert self.parameters() to a dictionary by name"""
return dict([(p.name, p) for p in self.parameters(config)])
def param_names(self, *args):
"""return union of parameter names in args"""
return sorted(reduce(set.union,
[set(map(_.name, self.parameters(cfg)))
for cfg in args]))
def linear_config(self, a, cfg_a, b, cfg_b, c, cfg_c):
"""return a configuration that is a linear combination of 3 other configs"""
dst = self.copy(cfg_a)
dst_params = self.proxy(dst)
for k in self.param_names(dst, cfg_a, cfg_b, cfg_c):
dst_params[k].op4_set_linear(cfg_a, cfg_b, cfg_c, a, b, c)
return dst
def _get_serializer(self, filename, format=None):
"""
Extract the correct file format serializer from self.FILE_FORMATS.
Guess the format by extension if one is not given.
"""
if format is None:
format = os.path.splitext(filename)[1].lower().replace('.', '')
if format not in self.FILE_FORMATS:
serializer = self.FILE_FORMATS['default']
if len(self.FILE_FORMATS) > 1:
log.warning('Unknown file format "%s", using "%s" instead', format,
serializer.__name__)
else:
serializer = self.FILE_FORMATS[format]
return serializer
def save_to_file(self, cfg, filename, format=None):
"""
Write cfg to filename. Guess the format by extension if one is not given.
"""
with open(filename, 'wb') as fd:
self._get_serializer(filename, format).dump(cfg, fd)
def load_from_file(self, filename, format=None):
"""
Read cfg from filename. Guess the format by extension if one is not given.
"""
with open(filename, 'rb') as fd:
return self._get_serializer(filename, format).load(fd)
def proxy(self, cfg):
return ManipulatorProxy(self, cfg)
@abc.abstractmethod
def random(self):
"""produce a random initial configuration"""
return
@abc.abstractmethod
def parameters(self, config):
"""return a list of of Parameter objects"""
return list()
@abc.abstractmethod
def hash_config(self, config):
"""produce unique hash value for the given config"""
return
class ConfigurationManipulator(ConfigurationManipulatorBase):
"""
a configuration manipulator using a fixed set of parameters and storing
configs in a dict-like object
"""
def __init__(self, params=None, config_type=dict, seed_config=None, **kwargs):
if params is None:
params = []
self.params = list(params)
self.config_type = config_type
self.search_driver = None
self._seed_config = seed_config
super(ConfigurationManipulator, self).__init__(**kwargs)
for p in self.params:
p.parent = self
def add_parameter(self, p):
p.set_parent(self)
self.params.append(p)
#TODO sub parameters should be recursed on
# not currently an issue since no doubly-nested sub-parameters
sub_params = p.sub_parameters()
for sp in sub_params:
sp.set_parent(p)
self.params.extend(sub_params)
def set_search_driver(self, search_driver):
self.search_driver = search_driver
def seed_config(self):
"""produce a fixed seed configuration"""
if self._seed_config:
cfg = copy.deepcopy(self._seed_config)
else:
cfg = self.config_type()
for p in self.params:
if not isinstance(p.name, str) or '/' not in p.name:
cfg[p.name] = p.seed_value()
return cfg
def random(self):
"""produce a random configuration"""
cfg = self.seed_config()
for p in self.parameters(cfg):
p.op1_randomize(cfg)
return cfg
def parameters(self, config):
"""return a list of Parameter objects"""
if type(config) is not self.config_type:
log.error("wrong type, expected %s got %s",
str(self.config_type),
str(type(config)))
raise TypeError()
return self.params
def parameters_to_json(self):
"""
output information about the parameters in this manipulator in json format:
[ConfigurationManipulator,{pinfo:count,pinfo:count ...}]
where pinfo has a similar form to describe the parameter's sub-parameters:
[param_name,{pinfo:count,pinfo:count ...}]
"""
def param_info_to_json(param, sub_parameters):
"""
recursively output information about a parameter and its subparameters in a json format:
[parameter_name, {subparam_info:count,subparam_info:count,...}]
or if no subparams
[parameter_name,{}]
where subparam_info are sorted alphabetically. Note we can't directly use json since
sets/dictionaries aren't always ordered by key
"""
sub_parameter_counts = {}
# build the string
if isinstance(param, str):
param_name = param
else:
param_name = param.__class__.__name__
out = ['[', param_name, ',{']
if len(sub_parameters) > 0:
# count sub params
for sp in sub_parameters:
spout = param_info_to_json(sp, sp.sub_parameters())
sub_parameter_counts[spout] = sub_parameter_counts.get(spout, 0) + 1
# add the count map in sorted order
for sp in sorted(sub_parameter_counts):
out.append(sp)
out.append(':')
out.append(str(sub_parameter_counts[sp]))
out.append(',')
out.pop() # remove trailing comma
out.append('}]')
return ''.join(out)
# filter out subparameters to avoid double counting
params = [p for p in self.params if p.parent is self]
return param_info_to_json(self, params)
def hash_config(self, config):
"""produce unique hash value for the given config"""
m = hashlib.sha256()
params = list(self.parameters(config))
params.sort(key=_.name)
for i, p in enumerate(params):
m.update(str(p.name).encode())
m.update(p.hash_value(config))
m.update(str(i).encode())
m.update(b"|")
return m.hexdigest()
def search_space_size(self):
"""estimate the size of the search space, not precise"""
return reduce(_ * _, [x.search_space_size() for x in self.params])
def difference(self, cfg1, cfg2):
cfg = self.copy(cfg1)
for param in self.parameters(cfg1):
if param.is_primitive(cfg1):
# TODO: check range
param.set_value(cfg, param.get_value(cfg1) - param.get_value(cfg2))
else:
pass
return cfg
def applySVs(self, cfg, sv_map, args, kwargs):
"""
Apply operators to each parameter according to given map. Updates cfg.
Parameters with no operators specified are not updated.
cfg: configuration data
sv_map: python dict that maps string parameter name to class method name
arg_map: python dict that maps string parameter name to class method
arguments
"""
# TODO: check consistency between sv_map and cfg
param_dict = self.parameters_dict(cfg)
for pname in self.param_names(cfg):
param = param_dict[pname]
getattr(param, sv_map[pname])(cfg, *args[pname], **kwargs[pname])
class Parameter(with_metaclass(abc.ABCMeta, object)):
"""
abstract base class for parameters in a ConfigurationManipulator
"""
def __init__(self, name):
self.name = name
self.parent = None
super(Parameter, self).__init__()
def _to_storage_type(self, val):
"""hook to support transformation applied while stored"""
return val
def _from_storage_type(self, sval):
"""hook to support transformation applied while stored"""
return sval
def _read_node(self, config):
"""hook to support different storage structures"""
node = config
if not isinstance(self.name, str):
return node, self.name
name_parts = self.name.split('/')
for part in name_parts[:-1]:
if isinstance(node, list):
part = int(part)
node = node[part]
part = name_parts[-1]
if isinstance(node, list):
part = int(part)
return node, part
def _get(self, config):
"""hook to support different storage structures"""
node, part = self._read_node(config)
return self._from_storage_type(node[part])
def _set(self, config, v):
"""hook to support different storage structures"""
node, part = self._read_node(config)
node[part] = self._to_storage_type(v)
def set_parent(self, manipulator):
self.parent = manipulator
def validate(self, config):
"""is the given config valid???"""
return True
def is_primitive(self, ignored=None):
return isinstance(self, PrimitiveParameter)
def is_permutation(self, ignored=None):
return isinstance(self, PermutationParameter)
def manipulators(self, config):
"""
a list of manipulator functions to change this value in the config
manipulators must be functions that take a config and change it in place
default implementation just has op1_randomize as only operation
"""
return [self.op1_randomize]
def normalize(self, config):
"""
mutate this parameter into a canonical form
"""
pass
def sub_parameters(self):
"""
additional parameters added with this parameter
"""
return []
@abc.abstractmethod
def op1_randomize(self, cfg):
"""
Set this parameter's value in a configuration to a random value
:param config: the configuration to be changed
"""
pass
@abc.abstractmethod
def seed_value(self):
"""some legal value of this parameter (for creating initial configs)"""
return
@abc.abstractmethod
def copy_value(self, src, dst):
"""copy the value of this parameter from src to dst config"""
pass
@abc.abstractmethod
def same_value(self, cfg1, cfg2):
"""test if cfg1 and cfg2 have the same value of this parameter"""
return
@abc.abstractmethod
def hash_value(self, config):
"""produce unique hash for this value in the config"""
return
@abc.abstractmethod
def op4_set_linear(self, cfg, cfg_a, cfg_b, cfg_c, a, b, c):
"""
Sets the parameter value in a configuration to a linear combination of 3
other configurations: :math:`a*cfg_a + b*cfg_b + c*cfg_c`
:param cfg: the configuration to be changed
:param cfg_a: a parent configuration
:param cfg_b: a parent configuration
:param cfg_c: a parent configuration
:param a: weight for cfg_a
:param b: weight for cfg_b
:param c: weight for cfg_c
"""
pass
def search_space_size(self):
return 1
def op1_nop(self, cfg):
"""
The 'null' operator. Does nothing.
:param cfg: the configuration to be changed
"""
pass
# Stochastic variators
def op3_swarm(self, cfg, cfg1, cfg2, c, c1, c2, *args, **kwargs):
"""
Stochastically 'move' the parameter value in a configuration towards those
in two parent configurations. This is done by calling :py:meth:`opn_stochastic_mix`
:param cfg: the configuration to be changed
:param cfg1: a parent configuration
:param cfg2: a parent configuration
:param c: weight of original configuration
:param c1: weight for cfg1
:param c2: weight for cfg2
"""
# default to probabilistic treatment
self.opn_stochastic_mix(cfg, [cfg, cfg1, cfg2], [c, c1, c2])
def opn_stochastic_mix(self, cfg, cfgs, ratio, *args, **kwargs):
"""
Stochastically recombine a list of parent values into a single result.
This randomly copies a value from a list of parents configurations according
to a list of weights.
:param cfg: the configuration to be changed
:param cfgs: a list of parent configurations
:param ratio: a list of floats representing the weight of each configuration
in cfgs
"""
assert len(cfgs) == len(ratio)
r = random.random()
c = old_div(numpy.array(ratio, dtype=float), sum(ratio))
for i in range(len(c)):
if r < sum(c[:i + 1]):
self.copy_value(cfg, cfgs[i])
break
class PrimitiveParameter(with_metaclass(abc.ABCMeta, Parameter)):
"""
An abstract interface implemented by parameters that represent a single
dimension in a cartesian space in a legal range
"""
def __init__(self, name, value_type=float, **kwargs):
self.value_type = value_type
super(PrimitiveParameter, self).__init__(name, **kwargs)
def hash_value(self, config):
"""produce unique hash for this value in the config"""
self.normalize(config)
return hashlib.sha256(repr(self.get_value(config)).encode('utf-8')).hexdigest().encode('utf-8')
def copy_value(self, src, dst):
"""copy the value of this parameter from src to dst config"""
self.set_value(dst, self.get_value(src))
def same_value(self, cfg1, cfg2):
"""test if cfg1 and cfg2 have the same value of this parameter"""
return self.get_value(cfg1) == self.get_value(cfg2)
def is_integer_type(self):
"""true if self.value_type can only represent integers"""
return self.value_type(0) == self.value_type(0.1)
def get_unit_value(self, config):
"""get_value scaled such that range is between 0.0 and 1.0"""
low, high = self.legal_range(config)
if self.is_integer_type():
# account for rounding
low -= 0.4999
high += 0.4999
val = self.get_value(config)
if low < high:
return old_div(float(val - low), float(high - low))
else:
if low > high:
log.warning('invalid range for parameter %s, %s to %s',
self.name, low, high)
# only a single legal value!
return 0.0
def set_unit_value(self, config, unit_value):
"""set_value scaled such that range is between 0.0 and 1.0"""
assert 0.0 <= unit_value <= 1.0
low, high = self.legal_range(config)
if self.is_integer_type():
# account for rounding
low -= 0.4999
high += 0.4999
if low < high:
val = unit_value * float(high - low) + low
if self.is_integer_type():
val = round(val)
val = max(low, min(val, high))
self.set_value(config, self.value_type(val))
def op1_normal_mutation(self, cfg, sigma=0.1, *args, **kwargs):
"""
apply normally distributed noise to this parameter's value in a
configuration
:param cfg: The configuration to be changed
:param sigma: the std. deviation of the normally distributed noise on a unit
scale
"""
v = self.get_unit_value(cfg)
v += random.normalvariate(0.0, sigma)
# handle boundary cases by reflecting off the edge
if v < 0.0:
v *= -1.0
if v > 1.0:
v = 1.0 - (v % 1)
self.set_unit_value(cfg, v)
def op4_set_linear(self, cfg, cfg_a, cfg_b, cfg_c, a, b, c):
"""
set the parameter value in a configuration to a linear combination of 3
other configurations: :math:`a*cfg_a + b*cfg_b + c*cfg_c`
:param cfg: The configuration to be changed
:param cfg_a: a parent configuration
:param cfg_b: a parent configuration
:param cfg_c: a parent configuration
:param a: weight for cfg_a
:param b: weight for cfg_b
:param c: weight for cfg_c
"""
va = self.get_unit_value(cfg_a)
vb = self.get_unit_value(cfg_b)
vc = self.get_unit_value(cfg_c)
v = a * va + b * vb + c * vc
v = max(0.0, min(v, 1.0))
self.set_unit_value(cfg, v)
def manipulators(self, config):
"""
a list of manipulator functions to change this value in the config
manipulators must be functions that take a config and change it in place
for primitive params default implementation is uniform random and normal
"""
return [self.op1_randomize, self.op1_normal_mutation]
@abc.abstractmethod
def set_value(self, config, value):
"""assign this value in the given configuration"""
pass
@abc.abstractmethod
def get_value(self, config):
"""retrieve this value from the given configuration"""
return 0
@abc.abstractmethod
def legal_range(self, config):
"""return the legal range for this parameter, inclusive"""
return 0, 1
class NumericParameter(PrimitiveParameter):
"""
A parameter representing a number with a minimum and maximum value
"""
def __init__(self, name, min_value, max_value, **kwargs):
"""min/max are inclusive"""
assert min_value <= max_value
super(NumericParameter, self).__init__(name, **kwargs)
# after super call so self.value_type is initialized
self.min_value = self.value_type(min_value)
self.max_value = self.value_type(max_value)
def seed_value(self):
"""some legal value of this parameter (for creating initial configs)"""
return self.min_value
def set_value(self, config, value):
assert value >= self.min_value
assert value <= self.max_value
self._set(config, value)
def get_value(self, config):
return self._get(config)
def legal_range(self, config):
return self.min_value, self.max_value
def op1_randomize(self, config):
"""
Set this parameter's value in a configuration to a random value in its legal
range
:param config: the configuration to be changed
"""
if self.is_integer_type():
self.set_value(config, random.randint(*self.legal_range(config)))
else:
self.set_value(config, random.uniform(*self.legal_range(config)))
def op1_scale(self, cfg, k):
"""
Scale this parameter's value in a configuration by a constant factor
:param cfg: the configuration to be changed
:param k: the constant factor to scale the parameter value by
"""
v = self.get_value(cfg) * k
v = max(self.min_value, min(self.max_value, v))
self.set_value(cfg, v)
def op3_difference(self, cfg, cfg1, cfg2):
"""
Set this parameter's value in a configuration to the difference between this
parameter's values in 2 other configs (cfg2 - cfg1)
:param cfg: the configuration to be changed
:param cfg1: The configuration whose parameter value is being subtracted
:param cfg2: The configuration whose parameter value is subtracted from
"""
v = self.get_value(cfg2) - self.get_value(cfg1)
v = max(self.min_value, min(self.max_value, v))
self.set_value(cfg, v)
def opn_sum(self, cfg, *cfgs):
"""
Set this parameter's value in a configuration to the sum of it's values in a
list of configurations
:param cfg: the configuration to be changed
:param cfgs: a list of configurations to sum
"""
v = sum([self.get_value(c) for c in cfgs])
v = max(self.min_value, min(self.max_value, v))
self.set_value(cfg, v)
def search_space_size(self):
if self.value_type is float:
return 2 ** 32
else:
return self.max_value - self.min_value + 1 # inclusive range
class IntegerParameter(NumericParameter):
"""
A parameter representing an integer value in a legal range
"""
def __init__(self, name, min_value, max_value, **kwargs):
"""min/max are inclusive"""
kwargs['value_type'] = int
super(IntegerParameter, self).__init__(name, min_value, max_value, **kwargs)
def op3_swarm(self, cfg, cfg1, cfg2, c=1, c1=0.5,
c2=0.5, velocity=0, sigma=0.2, *args, **kwargs):
"""
Simulates a single update step in particle swarm optimization by updating
the current position and returning a new velocity.
The new velocity is given by
.. math:: c*velocity + r1*c1*(cfg1-cfg) + r2*c2*(cfg2-cfg)
where r1 and r2 are random values between 0 and 1.
The new current position is the new velocity with gaussian noise added.
:param cfg: the configuration to be changed. Represents the current position
:param cfg1: a configuration to shift towards. Should be the local best
position
:param cfg2: a configuration to shift towards. Should be the global best
position
:param c: the weight of the current velocity
:param c1: weight of cfg1
:param c2: weight of cfg2
:param velocity: the old velocity
:param sigma: standard deviation of the gaussian noise, on a unit-scale
:return: the new velocity, a float
"""
vmin, vmax = self.legal_range(cfg)
k = vmax - vmin
# calculate the new velocity
v = velocity * c + (self.get_value(cfg1) - self.get_value(
cfg)) * c1 * random.random() + (self.get_value(
cfg2) - self.get_value(cfg)) * c2 * random.random()
# Map velocity to continuous space with sigmoid
s = old_div(k, (1 + numpy.exp(-v))) + vmin
# Add Gaussian noise
p = random.gauss(s, sigma * k)
# Discretize and bound
p = int(min(vmax, max(round(p), vmin)))
self.set_value(cfg, p)
return v
class FloatParameter(NumericParameter):
def __init__(self, name, min_value, max_value, **kwargs):
"""min/max are inclusive"""
kwargs['value_type'] = float
super(FloatParameter, self).__init__(name, min_value, max_value, **kwargs)
def op3_swarm(self, cfg, cfg1, cfg2, c=1, c1=0.5,
c2=0.5, velocity=0, *args, **kwargs):
"""
Simulates a single update step in particle swarm optimization by updating
the current position and returning a new velocity.
The new velocity is given by
.. math:: c*velocity + r1*c1*(cfg1-cfg) + r2*c2*(cfg2-cfg)
where r1 and r2 are random values between 0 and 1
The new current position is the old current position offset by the new
velocity:
:param cfg: the configuration to be changed. Represents the current position
:param cfg1: a configuration to shift towards. Should be the local best
position
:param cfg2: a configuration to shift towards. Should be the global best
position
:param c: the weight of the current velocity
:param c1: weight of cfg1
:param c2: weight of cfg2
:param velocity: the old velocity
:return: the new velocity, a float
"""
vmin, vmax = self.legal_range(cfg)
v = velocity * c + (self.get_value(cfg1) - self.get_value(
cfg)) * c1 * random.random() + (self.get_value(
cfg2) - self.get_value(cfg)) * c2 * random.random()
p = self.get_value(cfg) + v
p = min(vmax, max(p, vmin))
self.set_value(cfg, p)
return v
class ScaledNumericParameter(NumericParameter):
"""
A Parameter that is stored in configurations normally, but has a scaled
value when accessed using 'get_value'.
Because search techniques interact with Parameters through get_value, these
parameters are searched on a different scale (e.g. log scale).
"""
@abc.abstractmethod
def _scale(self, v):
"""
called on a value when getting it from it's configuration. Transforms the
actual value to the scale it is searched on
"""
return v
@abc.abstractmethod
def _unscale(self, v):
"""
called on a value when storing it. Transforms a value from it's search scale
to it's actual value
"""
return v
def set_value(self, config, value):
NumericParameter.set_value(self, config, self._unscale(value))
def get_value(self, config):
return self._scale(NumericParameter.get_value(self, config))
def legal_range(self, config):
return list(map(self._scale, NumericParameter.legal_range(self, config)))
class LogIntegerParameter(ScaledNumericParameter, FloatParameter):
"""
an integer value that is searched on a log scale, but stored without scaling
"""
def _scale(self, v):
return math.log(v + 1.0 - self.min_value, 2.0)
def _unscale(self, v):
v = 2.0 ** v - 1.0 + self.min_value
v = int(round(v))
return v
def legal_range(self, config):
low, high = NumericParameter.legal_range(self, config)
# increase the bounds account for rounding
return self._scale(low - 0.4999), self._scale(high + 0.4999)
class LogFloatParameter(ScaledNumericParameter, FloatParameter):
"""
a float parameter that is searched on a log scale, but stored without scaling
"""
def _scale(self, v):
return math.log(v + 1.0 - self.min_value, 2.0)
def _unscale(self, v):
v = 2.0 ** v - 1.0 + self.min_value
return v
class PowerOfTwoParameter(ScaledNumericParameter, IntegerParameter):
"""
An integer power of two, with a min and max value. Searched by the exponent
"""
def __init__(self, name, min_value, max_value, **kwargs):
kwargs['value_type'] = int
assert min_value >= 1
assert math.log(min_value, 2) % 1 == 0 # must be power of 2
assert math.log(max_value, 2) % 1 == 0 # must be power of 2
super(PowerOfTwoParameter, self).__init__(name, min_value, max_value,
**kwargs)
def _scale(self, v):
return int(math.log(v, 2))
def _unscale(self, v):
return 2 ** int(v)
def legal_range(self, config):
return int(math.log(self.min_value, 2)), int(math.log(self.max_value, 2))
def search_space_size(self):
return int(math.log(super(PowerOfTwoParameter, self).search_space_size(), 2))
##################
class ComplexParameter(Parameter):
"""
A non-cartesian parameter that can't be manipulated directly, but has a set
of user defined manipulation functions
"""
def copy_value(self, src, dst):
"""copy the value of this parameter from src to dst config"""
self._set(dst, copy.deepcopy(self._get(src)))
def same_value(self, cfg1, cfg2):
"""test if cfg1 and cfg2 have the same value of this parameter"""
return self._get(cfg1) == self._get(cfg2)
def hash_value(self, config):
"""produce unique hash for this value in the config"""
self.normalize(config)
return hashlib.sha256(repr(self._get(config))).hexdigest()
def get_value(self, config):
return self._get(config)
def set_value(self, config, value):
self._set(config, value)
def op4_set_linear(self, cfg, cfg_a, cfg_b, cfg_c, a, b, c):
"""
set this value to :math:`a*cfg_a + b*cfg_b + c*cfg_c`
this operation is not possible in general with complex parameters but
we make an attempt to "fake" it for common use cases
basically a call to randomize unless after normalization,
a = 1.0, b == -c, and cfg_b == cfg_c, in which case nothing is done
:param cfg: the configuration to be changed
:param cfg_a: a parent configuration
:param cfg_b: a parent configuration
:param cfg_c: a parent configuration
:param a: weight for cfg_a
:param b: weight for cfg_b
:param c: weight for cfg_c
"""
# attempt to normalize order, we prefer a==1.0
if a != 1.0 and b == 1.0: # swap a and b
a, cfg_a, b, cfg_b = b, cfg_b, a, cfg_a
if a != 1.0 and c == 1.0: # swap a and c
a, cfg_a, c, cfg_c = c, cfg_c, a, cfg_a
# attempt to normalize order, we prefer b==-c
if b < c: # swap b and c
b, cfg_b, c, cfg_c = c, cfg_c, b, cfg_b
if b != -c and a == -c: # swap a and c
a, cfg_a, c, cfg_c = c, cfg_c, a, cfg_a
if a == 1.0 and b == -c:
self.copy_value(cfg_a, cfg)
self.add_difference(cfg, b, cfg_b, cfg_c) # TODO inline this logic?
else:
# TODO: should handle more cases
self.op1_randomize(cfg)
def add_difference(self, cfg_dst, scale, cfg_b, cfg_c):
"""
add the difference cfg_b-cfg_c to cfg_dst
this is the key operation used in differential evolution
and some simplex techniques
this operation is not possible in general with complex parameters but
we make an attempt to "fake" it
"""
if not self.same_value(cfg_b, cfg_c):
self.op1_randomize(cfg_dst)
@abc.abstractmethod
def op1_randomize(self, config):
"""
randomize this value without taking into account the current position
:param config: the configuration to be changed
"""
pass
@abc.abstractmethod
def seed_value(self):
"""some legal value of this parameter (for creating initial configs)"""
return
class BooleanParameter(ComplexParameter):
def manipulators(self, config):
return [self.op1_flip]
def get_value(self, config):
return self._get(config)
def set_value(self, config, value):
self._set(config, value)
def op1_randomize(self, config):
"""
Set this parameter's value in a configuration randomly
:param config: the configuration to be changed
"""
self._set(config, self.seed_value())
def seed_value(self):
return random.choice((True, False))
def op1_flip(self, config):
"""
Flip this parameter's value in a configuration
:param config: the configuration to be changed
"""
self._set(config, not self._get(config))
def search_space_size(self):
return 2
def op3_swarm(self, cfg, cfg1, cfg2, c=1, c1=0.5,
c2=0.5, velocity=0, *args, **kwargs):
"""
Simulates a single update step in particle swarm optimization by updating
the current position and returning a new velocity.
The new velocity is given by
.. math:: c*velocity + r1*c1*(cfg1-cfg) + r2*c2*(cfg2-cfg)
where r1 and r2 are random values between 0 and 1
The new current position is randomly chosen based on the new velocity
:param cfg: the configuration to be changed. Represents the current position
:param cfg1: a configuration to shift towards. Should be the local best position
:param cfg2: a configuration to shift towards. Should be the global best position
:param c: the weight of the current velocity
:param c1: weight of cfg1
:param c2: weight of cfg2
:param velocity: the old velocity
:param args:
:param kwargs:
:return: the new velocity, a float
"""
v = velocity * c + (self.get_value(cfg1) - self.get_value(
cfg)) * c1 * random.random() + (self.get_value(
cfg2) - self.get_value(cfg)) * c2 * random.random()
# Map velocity to continuous space with sigmoid
s = old_div(1, (1 + numpy.exp(-v)))
# Decide position randomly
p = (s - random.random()) > 0
self.set_value(cfg, p)
return v
class SwitchParameter(ComplexParameter):
"""