-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimism.py
More file actions
2447 lines (1994 loc) · 58.5 KB
/
Copy pathoptimism.py
File metadata and controls
2447 lines (1994 loc) · 58.5 KB
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
"""
optimism.py
OPTIMisation Including Surrogate Modelling
Library of optimisation functions.
(c) copyright Aleksander J Dubas 2021
Licensed under GPLv3, see LICENSE.
"""
import numpy as np
import numpy.linalg as npla
# surrogate modelling classes
class Surrogate():
"""
Base class for a surrogate model.
"""
def __init__(self):
self.xs = []
self.ys = []
def loaddata(self, filename, noy=False):
"""
Loads data into the surrogate model.
Uses the same data structure as the savedata function.
Use of an absolute path is recommended.
Parameters
----------
filename: string
Name of file to load data from.
noy: bool (default False)
Set to true if no y-data in file.
Returns
-------
None
"""
with open(filename, 'r') as fin:
lines = fin.readlines()
if noy:
xlen = len(lines[0].split())
else:
xlen = len(lines[0].split()) - 1
for line in lines:
parts = line.split()
self.xs.append([])
for i in range(len(parts)):
if i < xlen:
self.xs[-1].append(float(parts[i]))
else:
self.ys.append(float(parts[i]))
# convert xs to array
self.xs = np.array(self.xs)
return None
def savedata(self, filename):
"""
Saves data from a surrogate model.
In the structure:
xs[0][0] xs[0][1] xs[0][2] ... xs[0][-2] xs[0][-1] ys[0]\n
xs[1][0] xs[1][1] xs[1][2] ... xs[1][-2] xs[1][-1] ys[1]\n
Use of an absolute path is recommended.
Parameters
----------
filename: string
Name of file to save data to.
Returns
-------
None
"""
with open(filename, 'w') as fout:
for i in range(len(self.xs)):
for x in self.xs[i]:
fout.write(str(x)+" ")
try:
fout.write(str(self.ys[i])+"\n")
except IndexError:
fout.write("\n")
return None
def infill(self, f):
"""
Evaluates any unevaluated points in self.xs array using f.
Parameters
----------
f: function
Function used to evaluate infill points.
Returns
-------
None
"""
xlen = len(self.xs)
ylen = len(self.ys)
if xlen == ylen:
return None
self.ys = np.hstack((self.ys, np.zeros(xlen-ylen)))
for i in range(ylen, xlen):
self.ys[i] = f(self.xs[i])
return None
def infill_point(self, x):
"""
Adds infill point x to self.xs array.
Parameters
----------
x: 1-d array
Infill point to be added.
Returns
-------
None
"""
self.xs = np.vstack((self.xs, x))
return None
def minx(self):
"""
Returns the x value of the minimum (real) point.
"""
return self.xs[np.argmin(self.ys)]
def miny(self):
"""
Returns the y value of the minimum (real) point.
"""
return min(self.ys)
def mini(self):
"""
Returns the i value of the minimum (real) point.
"""
return np.argmin(self.ys)
def maxx(self):
"""
Returns the x value of the maximum (real) point.
"""
return self.xs[np.argmax(self.ys)]
def maxy(self):
"""
Returns the y value of the maximum (real) point.
"""
return max(self.ys)
def maxi(self):
"""
Returns the i value of the maximum (real) point.
"""
return np.argmax(self.ys)
class GaussianRBF(Surrogate):
"""
Constructs a surrogate model using the Radial Basis Function in SciPy.
Uses a Gaussian distribution.
"""
def build(self):
"""
Builds the surrogate model.
"""
self.name = "GaussianRBF"
from scipy.interpolate import Rbf
# creating packing list for passing to RBF
packinglist = []
for i in range(len(self.xs[0])):
packinglist.append(self.xs[:, i])
packinglist.append(self.ys)
self.rbf = Rbf(*tuple(packinglist), function="gaussian")
def f(self, xs):
"""
Evaluates the surrogate model at xs.
"""
return self.rbf(*tuple(xs))
class MultiQuadricRBF(Surrogate):
"""
Constructs a surrogate model using the Radial Basis Function in SciPy.
Uses a MultiQuadric distribution.
"""
def build(self):
"""
Builds the surrogate model.
"""
self.name = "MultiQuadricRBF"
from scipy.interpolate import Rbf
# creating packing list for passing to RBF
packinglist = []
for i in range(len(self.xs[0])):
packinglist.append(self.xs[:, i])
packinglist.append(self.ys)
self.rbf = Rbf(*tuple(packinglist), function="multiquadric")
def f(self, xs):
"""
Evaluates the surrogate model at xs.
"""
return self.rbf(*tuple(xs))
class InverseRBF(Surrogate):
"""
Constructs a surrogate model using the Radial Basis Function in SciPy.
Uses an Inverse distribution.
"""
def build(self):
"""
Builds the surrogate model.
"""
self.name = "InverseRBF"
from scipy.interpolate import Rbf
# creating packing list for passing to RBF
packinglist = []
for i in range(len(self.xs[0])):
packinglist.append(self.xs[:, i])
packinglist.append(self.ys)
self.rbf = Rbf(*tuple(packinglist), function="inverse")
def f(self, xs):
"""
Evaluates the surrogate model at xs.
"""
return self.rbf(*tuple(xs))
class LinearRBF(Surrogate):
"""
Constructs a surrogate model using the Radial Basis Function in SciPy.
Uses a Linear distribution.
"""
def build(self):
"""
Builds the surrogate model.
"""
self.name = "LinearRBF"
from scipy.interpolate import Rbf
# creating packing list for passing to RBF
packinglist = []
for i in range(len(self.xs[0])):
packinglist.append(self.xs[:, i])
packinglist.append(self.ys)
self.rbf = Rbf(*tuple(packinglist), function="linear")
def f(self, xs):
"""
Evaluates the surrogate model at xs.
"""
return self.rbf(*tuple(xs))
class CubicRBF(Surrogate):
"""
Constructs a surrogate model using the Radial Basis Function in SciPy.
Uses a Cubic distribution.
"""
def build(self):
"""
Builds the surrogate model.
"""
self.name = "CubicRBF"
from scipy.interpolate import Rbf
# creating packing list for passing to RBF
packinglist = []
for i in range(len(self.xs[0])):
packinglist.append(self.xs[:, i])
packinglist.append(self.ys)
self.rbf = Rbf(*tuple(packinglist), function="cubic")
def f(self, xs):
"""
Evaluates the surrogate model at xs.
"""
return self.rbf(*tuple(xs))
class QuinticRBF(Surrogate):
"""
Constructs a surrogate model using the Radial Basis Function in SciPy.
Uses a Quintic distribution.
"""
def build(self):
"""
Builds the surrogate model.
"""
self.name = "QuinticRBF"
from scipy.interpolate import Rbf
# creating packing list for passing to RBF
packinglist = []
for i in range(len(self.xs[0])):
packinglist.append(self.xs[:, i])
packinglist.append(self.ys)
self.rbf = Rbf(*tuple(packinglist), function="quintic")
def f(self, xs):
"""
Evaluates the surrogate model at xs.
"""
return self.rbf(*tuple(xs))
class ThinPlateRBF(Surrogate):
"""
Constructs a surrogate model using the Radial Basis Function in SciPy.
Uses a Thin Plate distribution.
"""
def build(self):
"""
Builds the surrogate model.
"""
self.name = "ThinPlateRBF"
from scipy.interpolate import Rbf
# creating packing list for passing to RBF
packinglist = []
for i in range(len(self.xs[0])):
packinglist.append(self.xs[:, i])
packinglist.append(self.ys)
self.rbf = Rbf(*tuple(packinglist), function="thin_plate")
def f(self, xs):
"""
Evaluates the surrogate model at xs.
"""
return self.rbf(*tuple(xs))
class BestRBF(Surrogate):
"""
Constructs a surrogate model based on the RBF with minimal NRMSD
"""
def calcNRMSD(self, Surrogate):
"""
Returns the NRMSD of the surrogate model.
"""
from gc import collect
predys = np.zeros(len(self.ys))
for i in range(len(self.ys)):
inst = Surrogate()
inst.xs = np.vstack((self.xs[:i], self.xs[i+1:]))
inst.ys = np.hstack((self.ys[:i], self.ys[i+1:]))
inst.build()
predys[i] = inst.f(self.xs[i])
# explicit dereferencing and cleanup
del inst
collect()
NRMSD = (sum((np.array(predys)-np.array(self.ys))**2)
/ float(len(self.ys)))**0.5 /\
(self.maxy() - self.miny())
# explicit dereferencing
del predys
return NRMSD
def build(self):
"""
Builds the surrogate model.
"""
from gc import collect
# ensure array form for memory efficiency
self.xs = np.array(self.xs)
self.ys = np.array(self.ys)
# define candidate RBFs
candidates = [GaussianRBF, MultiQuadricRBF, InverseRBF,
LinearRBF, CubicRBF, QuinticRBF, ThinPlateRBF]
# make storage for NRMSD values
self.NRMSDs = []
for candidate in candidates:
# calculate NRMSD for each candidate RBF
self.NRMSDs.append(self.calcNRMSD(candidate))
# trigger garbage collection for memory cleanup
collect()
# find best RBF
besti = np.argmin(self.NRMSDs)
# make best RBF
brbf = candidates[besti]()
brbf.xs = self.xs
brbf.ys = self.ys
brbf.build()
# use best RBF as current RBF
self.name = brbf.name
self.rbf = brbf.rbf
def f(self, xs):
"""
Evaluates the surrogate model at xs.
"""
return self.rbf(*tuple(xs))
class Kriging(Surrogate):
"""
A Kriging surrogate model, based on:
Forrester et al - Engineering Design via Surrogate Modelling (Wiley, 2008).
including a few optimisation changes to reduce build and evaluation time.
"""
def __init__(self):
self.xs = []
self.ys = []
self.gapops = 20
self.gagens = 100
self.lntlb = -7 # e^-7 ~= 10^-3
self.lntub = 5 # e^5 ~= 10^2 as per book
def build(self):
"""
Builds the surrogate model.
"""
self.name = "Kriging"
# extract size parameters
k = len(self.xs[0])
n = len(self.ys)
self.overn = 1/float(n)
# run ga search of likelihood
self.Theta, self.MinNegLnLikelihood, _ = \
ga(lambda x: self.likelihood(x)[0], k,
np.linspace(self.lntlb, self.lntub, 101),
self.gapops, self.gagens)
# put Cholesky factorisation of Psi into namespace
self.NegLnLike, self.Psi, self.U = self.likelihood(self.Theta)
return None
def rebuild(self):
"""
Rebuilds the surrogate model,
seeding the optimisation with current Kriging hyper-parameters.
"""
self.name = "Kriging"
# extract size parameters
k = len(self.xs[0])
n = len(self.ys)
self.overn = 1/float(n)
# construct seed
seedTheta = list(self.Theta)
# run ga search of likelihood
self.Theta, self.MinNegLnLikelihood, _ = \
ga(lambda x: self.likelihood(x)[0], k,
np.linspace(self.lntlb, self.lntub, 101),
self.gapops, self.gagens,
seed=seedTheta)
# put Cholesky factorisation of Psi into namespace
self.NegLnLike, self.Psi, self.U = self.likelihood(self.Theta)
return None
def likelihood(self, thetas):
"""
Calculates the likelihood.
"""
# initialise theta, n, one, eps
theta = np.e**np.array(thetas)
n = len(self.ys)
one = np.ones([n])
eps = 1000*np.spacing(1)
# pre-allocate memory
Psi = np.zeros([n, n])
# build upper half of the correlation matrix
for i in range(n):
for j in range(i+1, n):
Psi[i, j] = np.exp(-sum(theta*(self.xs[i]-self.xs[j])**2))
# add upper and lower halves and diagonal of ones
# plus a small number to reduce ill conditioning
Psi += Psi.T + np.eye(n) * (1+eps)
# cholesky factorisation
# added try/except block to capture error and implement penalty
try:
U = npla.cholesky(Psi).T
except npla.LinAlgError:
return 1000, Psi, np.zeros([n, n])
# Forrester et al. have a penalty here if ill-conditioned
# but this is not implemented in numpy.linalg.cholesky
# Sum lns of diagonal to find ln(det(Psi))
LnDetPsi = 2*sum(np.log(np.abs(np.diag(U))))
# use back-substitution of Cholesky instead of inverse
mu = np.dot(one, npla.solve(U, npla.solve(U.T, self.ys))) /\
np.dot(one, npla.solve(U, npla.solve(U.T, one)))
ysMuTemp = self.ys - mu # only calculate this once
SigmaSqr = (np.dot(ysMuTemp,
npla.solve(U,
npla.solve(U.T, ysMuTemp)))*self.overn)
NegLnLike = -1*(-(0.5*n)*np.log(SigmaSqr)-0.5*LnDetPsi)
return NegLnLike, Psi, U
def f(self, xs):
"""
Evaluates the surrogate model at xs.
"""
# initialise theta
theta = np.e**np.array(self.Theta)
# calculate number of sample points
n = len(self.ys)
# create vector of ones
one = np.ones([n])
# calculate mu
mu = np.dot(one, npla.solve(self.U, npla.solve(self.U.T, self.ys))) /\
np.dot(one, npla.solve(self.U, npla.solve(self.U.T, one)))
psi = np.exp(-np.sum(theta*np.abs(self.xs-xs)**2, axis=1))
return mu+np.dot(psi,
npla.solve(self.U, npla.solve(self.U.T, self.ys-mu)))
def lb(self, xs):
"""
Evaluates the statistical lower bound at xs.
"""
# initialise theta
theta = np.e**np.array(self.Theta)
# intialise A
if not hasattr(self, "A"):
self.A = 2
# calculate number of sample points
n = len(self.ys)
# create vector of ones
one = np.ones([n])
# calculate mu
mu = np.dot(one, npla.solve(self.U, npla.solve(self.U.T, self.ys))) /\
np.dot(one, npla.solve(self.U, npla.solve(self.U.T, one)))
# calculate sigma^2
ysMuTemp = self.ys - mu # only calculate this once
UUTym = npla.solve(self.U, npla.solve(self.U.T, ysMuTemp))
SigmaSqr = np.dot(ysMuTemp, UUTym)*self.overn
psi = np.exp(-np.sum(theta*np.abs(self.xs-xs)**2, axis=1))
# calculate prediction
f = mu + np.dot(psi, UUTym)
# error
SSqr = SigmaSqr*(1-np.dot(psi,
npla.solve(self.U,
npla.solve(self.U.T, psi))))
# lower bound
return f - self.A * np.sqrt(SSqr)
def ei(self, xs):
"""
Evaluates the expected improvement at xs.
"""
# define the error function as it's missing from python
def erf(x):
# save the sign of x
sign = 1 if x >= 0 else -1
x = np.abs(x)
# constants
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
p = 0.3275911
# A&S formula 7.1.26
t = (1.0 + p*x)**-1
y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*np.exp(-x*x)
return sign*y # erf(-x) = -erf(x)
# initialise theta
theta = np.e**np.array(self.Theta)
# intialise A
if not hasattr(self, "A"):
self.A = 2
# calculate number of sample points
n = len(self.ys)
# create vector of ones
one = np.ones([n])
# calculate mu
mu = np.dot(one, npla.solve(self.U, npla.solve(self.U.T, self.ys))) /\
np.dot(one, npla.solve(self.U, npla.solve(self.U.T, one)))
# calculate sigma^2
ysMuTemp = self.ys - mu # only calculate this once
UUTym = npla.solve(self.U, npla.solve(self.U.T, ysMuTemp))
SigmaSqr = np.dot(ysMuTemp, UUTym)*self.overn
psi = np.exp(-np.sum(theta*np.abs(self.xs-xs)**2, axis=1))
# calculate prediction
f = mu + np.dot(psi, UUTym)
y_hat = f
# error
SSqr = SigmaSqr*(1-np.dot(psi,
npla.solve(self.U,
npla.solve(self.U.T, psi))))
# find best so far:
y_min = np.min(self.ys)
# expected improvement
if SSqr == 0:
return 0
else:
sqrtAbsSSqr = np.sqrt(np.abs(SSqr)) # only calculate this once
yDiff = y_min - y_hat # only calculate this once
ei_term1 = yDiff *\
(0.5+0.5*erf((0.70710678)*(yDiff/sqrtAbsSSqr)))
ei_term2 = sqrtAbsSSqr *\
(0.39894228)*np.exp(-0.5*(yDiff**2/SSqr))
return ei_term1 + ei_term2
# analysis functions
def calcNRMSD(Surrogate, xs, ys):
"""
Calculates the normalised root mean square deviation of a surrogate class.
Parameters
----------
Surrogate: Surrogate
Surrogate class for which to calculate the NRMSD.
xs: list of list of numbers
x-data to calculate NRMSD.
ys: list of numbers
y-data to calcualte NRMSD.
Returns
NRMSD: number
Normalised root mean square deviation.
"""
from gc import collect
predys = np.zeros(len(ys))
deltay = max(ys) - min(ys)
for i in range(len(ys)):
inst = Surrogate()
inst.xs = np.vstack((xs[:i], xs[i+1:]))
inst.ys = np.hstack((ys[:i], ys[i+1:]))
inst.build()
predys[i] = inst.f(xs[i])
# explicit dereferencing and cleanup
del inst
collect()
NRMSD = (sum((np.array(predys)-np.array(ys))**2)
/ float(len(ys)))**0.5 /\
(deltay)
# explicit dereferencing
del predys
return NRMSD
# genetic and evolutionary algorithms
def ga(f, length, bases, pops=20, gens=100,
tournamentSize=0.4, mutationRate=0.6, seed=False):
"""
A genetic algorithm for finding the minimum of f.
A genetic algorithm for finding the minimum of f. Uses a tournament
selection method and both crossover and mutation to introduce variation.
Elite selection is also used to preserve the best individual found so far.
Includes the option to 'seed' the initial population with the placement
of a predefined individual.
Parameters
----------
f: function
Function to be minimised, that takes a single iterable argument.
length: integer
Length of the iterable to pass to the function.
bases: iterable
Possible values for each place in the genetic code.
For example ["A", "C", "G", "T"] for DNA.
pops: number (default 20)
Individuals in each new population.
gens: number (default 100)
Number of generations of populations.
tournamentSize: number (default 0.4)
Size of tournament as a proportion of the population.
mutationRate: number (default 0.6)
Rate of mutation expressed in the range (0, 1).
seed: list of numbers (default False)
A seed individual to include in the first population.
Returns
-------
indiout: list of numbers
The 'chromosome' of the fittest individual found.
fitness: number
The fitness of the output individual. i.e. f(indiout).
history: list of numbers
The optimisation history, taking the maximum fitness in each generation
and thus returning a list of length gens.
"""
import random
# set up history
hist = []
# set up tournament size as integer
nTournament = int(tournamentSize*pops)
# generate initial population
parents = []
if seed is not False:
parents.append(seed)
for i in range(pops-1):
indi = [random.choice(bases) for j in range(length)]
parents.append(indi)
else:
for i in range(pops):
indi = [random.choice(bases) for j in range(length)]
parents.append(indi)
# calculate fitnesses
fits = [f(parent) for parent in parents]
hist.append(min(fits))
# begin main loop over generations
for gen in range(gens-1):
children = []
# elite selection
children.append(parents[fits.index(min(fits))])
# select remaining population
while len(children) < pops:
# tournament selection
tournis = random.sample(range(len(fits)), nTournament)
# pick the two best parents in the tournament
p1i = tournis[0]
p2i = tournis[0]
for tourni in tournis[1:]:
if fits[tourni] < fits[p1i]:
p1i = tourni
elif fits[tourni] < fits[p2i]:
p2i = tourni
# crossover
cp = random.randint(0, length-1)
child1 = parents[p1i][:cp]+parents[p2i][cp:]
child2 = parents[p2i][:cp]+parents[p1i][cp:]
# mutation child1
if random.random() < mutationRate:
mp = random.randint(0, length-1)
child1[mp] = random.choice(bases)
# mutation child2
if random.random() < mutationRate:
mp = random.randint(0, length-1)
child2[mp] = random.choice(bases)
# add to population
children.append(child1)
if len(children) < pops:
children.append(child2)
# progress one generation and recalculate fitness
parents = children
fits = [f(parent) for parent in parents]
# store history
hist.append(min(fits))
# find best of final generation
for i in range(pops):
if fits[i] == hist[-1]:
indiout = parents[i]
return indiout, hist[-1], hist
# sample plan space filling metrics
def sampleplan_mean_distance(sampleplan):
"""
Returns the mean distance between points in a sample plan.
Parameters
----------
sampleplan: n*k array
Sample plan to calculate the mean distance of.
Returns
-------
mean_distance: number
Mean distance between points in the sample plan.
"""
mean_distance = 0
n = len(sampleplan)
total_measured = 0
for i in range(n-1):
for j in range(i + 1, n):
mean_distance += npla.norm(sampleplan[i] - sampleplan[j])
total_measured += 1
mean_distance /= total_measured
return mean_distance
def morris_mitchell_phi(sampleplan, q=2, euclidean=True):
"""
Calculates the sampling plan quality criterion of Morris and Mitchell.
Parameters
----------
sampleplan: 2d array
An n by k array of the sample plan. Where n is the number of points
and k is the number of dimensions.
q: number (default 2)
Exponent used in the calculation of the metric.
euclidean: bool (default True)
Whether to use the Euclidean distance metric or rectangular.
Returns
-------
phiq: number
Sampling plan space-fillingness metric.
"""
# number of points in sampling plan
n = len(sampleplan)
# compute the distances between all pairs of points
d = np.zeros(n*(n-1)/2.0)
for i in range(n-1):
for j in range(i+1, n):
# d[(i-1)*n-(i-1)*i/2+j-i] is the original matlab here
if euclidean:
d[(i)*n-(i)*(i+1)/2+j-i-1] = npla.norm(sampleplan[i] -
sampleplan[j])
if not euclidean:
d[(i)*n-(i)*(i+1)/2+j-i-1] = npla.norm(sampleplan[i] -
sampleplan[j], 1)
# remove multiple occurrences
dd = np.unique(d)
# preallocate memory for J
J = np.zeros(len(dd))
# generate multiplicity array
for i in range(len(dd)):
# J[i] = sum(ismember(d, dd[i])) is the original matlab here
J[i] = sum([x == dd[i] for x in d])
# the sampling plan quality criterion
phiq = sum(J*(dd**(-q)))**(1.0/q)
return phiq
# sampling plans
def randlh(k, n, edges=False):
"""
Returns an random latin hypercube with k dimensions
and n points in a structure xs[n][k].
All dimensions are normalised between 0 and 1.
Parameters
----------
k: number
Number of dimensions.
n: number
Number of points in the latin hypercube.
edges: bool (default False)
Whether or not to use edge points at 0 and 1.
Returns
-------
samplexs: 2d array
An n by k array of sample points in the given space.
Example
-------
>>> randlh(2, 2)
[[0.25, 0.25], [0.75, 0.75]]
"""
from random import randint
samplexs = np.zeros([n, k])
# create k by n dimensional sampling list - to be popped at random.
popper = []
for i in range(k):
popper.append(list(range(n)))
# create latin hypercube
for i in range(n):
for j in range(k):
samplexs[i, j] = popper[j].pop(randint(0, len(popper[j]) - 1))
# and normalise to 1
if edges:
samplexs[i, j] /= float(n - 1)
elif not edges:
samplexs[i, j] = (samplexs[i, j] + 0.5) / float(n)
return samplexs
def bestlh(k, n, n_hypercubes=50, edges=False,
space_fillingness=morris_mitchell_phi):
"""
Generates a number of random latin hypercubes
and picks the best one based on maximum space fillingness.
Parameters
----------
k: integer
Number of dimensions.
n: integer
Number of points in the latin hypercube.
n_hypercubes: integer (default 50)
Number of hypercubes to generate to pick the best one.
edges: bool (default False)
Whether or not to use edge points at 0 and 1.
space_fillingness: function (default morris_mitchell_phi)
Function that defines the space fillingness of a sample plan.
This is the objective that is minimised.
Returns
-------
samplexs: 2d array
An n by k array of sample points in the given space.
"""
currentxs = randlh(k, n, edges)
newxs = randlh(k, n, edges)
if space_fillingness(newxs) < space_fillingness(currentxs):
currentxs = newxs[:]
for i in range(n_hypercubes - 2):
newxs = randlh(k, n, edges)
if space_fillingness(newxs) < space_fillingness(currentxs):
currentxs = newxs[:]
return currentxs
def randsampleplan(k, n):
"""
Returns a random sample plan.
All dimensions are normalised between 0 and 1.
Parameters
----------
k: integer
Number of dimensions.
n: integer
Number of points.
Returns
-------
samplexs: 2d array
An n by k array of sample points in the given space.
"""
from random import random
samplexs = np.zeros([n, k])
for i in range(n):
for j in range(k):
samplexs[i, j] = random()
return samplexs
def bestrandplan(k, n, n_plans=50,
space_fillingness=sampleplan_mean_distance):
"""
Generates a number of random sample plans
and picks the best one based on maximum space fillingness.
Parameters
----------
k: integer
Number of dimensions.
n: integer
Number of points.
n_plans: integer (default 50)
Number of random plans to generate to pick the best one.
space_fillingness: function (default sampleplan_mean_distance)
Function that defines the space fillingness of a sample plan.
This is the objective that is maximised.
Returns
-------
samplexs: 2d array
An n by k array of sample points in the given space.
"""
currentxs = randsampleplan(k, n)
newxs = randsampleplan(k, n)
if space_fillingness(newxs) > space_fillingness(currentxs):
currentxs = newxs[:]
for i in range(n_plans - 2):
newxs = randsampleplan(k, n)
if space_fillingness(newxs) > space_fillingness(currentxs):
currentxs = newxs[:]
return currentxs
def full2dsampleplan(n):
"""
Returns a full sample plan for 2 dimensions with n points per dimension.
Note this is a total of n^2 points.