forked from ZJouba/virtual_creatures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
actuator_GA.py
791 lines (640 loc) · 25.8 KB
/
actuator_GA.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
from Tools.Plot2D3DandProfile import plotDavid
import itertools
import multiprocessing as mp
import os
import sys
import operator
import copy
import time
from datetime import datetime
from decimal import Decimal
from math import atan2, cos, degrees, radians, sin, tan, pi
import pandas as pd
from tikzplotlib import save as tksave
from matplotlib import rc
rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size': 15})
rc('text', usetex=True)
import matplotlib.cm as cm
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
from numpy.polynomial import Polynomial as P
from matplotlib import transforms
from matplotlib.offsetbox import (AnnotationBbox, DrawingArea, OffsetImage,
TextArea)
from matplotlib.ticker import MultipleLocator
from matplotlib.collections import PatchCollection
import matplotlib.patches as patches
import matplotlib.image as mpimg
from scipy import ndimage
from tabulate import tabulate
from grid_strategy import strategies
from Tools.Classes import Limb
from shapely.geometry import LineString
from scipy.spatial.distance import cdist
from PIL import Image
def evaluate(orient_vector, first=False):
global top_X, parameters
invalid = False
l = Limb()
l.build(orient_vector)
data = np.copy(l.XY)
origin = np.array((0, 0))
point = np.array((data[0][-1], data[1][-1]))
D = np.linalg.norm(point-origin)
X = data[0][-1]
Y = data[1][-1]
if any(value == True for value in parameters.get('Curve fitting').values()):
m = data[0][-1]/(2*pi)
amp = 20
if parameters.get('Curve fitting').get('Sin'):
curve = amp*np.sin(data[0]/m)
elif parameters.get('Curve fitting').get('Cos'):
curve = amp*np.cos(data[0]/m)-1
elif parameters.get('Curve fitting').get('Custom'):
curve = []
func = parameters.get('Curve fitting').get('Custom func')
for ea in data[0]/m:
x = ea
curve.append(eval(func))
curve_fit = cdist([data[1]], [curve], 'sqeuclidean')
else:
curve_fit = 0
Curvature = degrees(l.curvature[-1])
limb_res = [
round(X, 2),
round(Y, 2),
round(D, 2),
round(Curvature, 2),
orient_vector,
curve_fit,
]
lowest = min(np.array(top_X)[:,sort_by])
highest = max(np.array(top_X)[:,sort_by])
if (lowest < limb_res[sort_by] < highest) or first:
lines = []
to_tuple = [(x, y) for x, y in zip(data[0], data[1])]
lines.append(LineString(to_tuple))
try:
lines.append(lines[0].parallel_offset(1.9, side='left'))
except:
pass
try:
lines.append(lines[0].parallel_offset(1.9, side='right'))
except:
pass
for line in lines:
if not line.is_simple or line.is_closed:
invalid = True
if invalid:
if descending:
D = 0
X = 0
Y = 0
Curvature = 0
else:
D = 99999
X = 99999
Y = 99999
Curvature = 99999
limb_res = [
round(X, 2),
round(Y, 2),
round(D, 2),
round(Curvature, 2),
# l,
orient_vector
]
return limb_res
def selection(generation_data, num_segments, elite, randomised, mutation, crossover, probabilities):
global random_array
for i in range(len(generation_data[0])):
if isinstance(generation_data[0][i],list):
vec_ind = i
if isinstance(elite, float):
elite = int(len(generation_data) * elite)
if isinstance(randomised, float):
randomised = int(len(generation_data) * randomised)
elif isinstance(randomised, tuple):
try:
if len(random_array) == 1:
randomised = int(len(generation_data) * random_array[-1])
else:
randomised, random_array = random_array[0], random_array[1:]
randomised = int(len(generation_data) * randomised)
except NameError:
random_array = np.linspace(
randomised[0], randomised[1], randomised[2])
randomised, random_array = random_array[0], random_array[1:]
randomised = int(len(generation_data) * randomised)
if isinstance(mutation, float):
mutation = int(len(generation_data) * mutation)
if isinstance(crossover, float):
crossover = int(len(generation_data) * crossover)
new_generation_data = []
for i in range(elite):
new_generation_data.append(generation_data[i][vec_ind])
if isinstance(num_segments, int):
for i in range(randomised):
new_vec = [np.random.choice(choices)
for _ in range(num_segments)]
new_generation_data.append(new_vec)
else:
for i in range(randomised):
top_margin = len(elite[0]) + 5
bottom_margin = len(elite[0]) - 5
new_vec = [np.random.choice(
choices) for _ in range(np.random.randint(bottom_margin, top_margin))]
new_generation_data.append(new_vec)
for i in range(mutation):
limb = generation_data[np.random.randint(len(generation_data))][vec_ind]
index = np.random.randint(
low=0, high=len(limb), size=int(len(limb)*0.2))
for place in index:
limb[place] = np.random.choice(choices)
new_generation_data.append(limb)
def choose():
indices = list(range(len(generation_data)))
probabilities.flatten()
indA = np.random.choice(
indices,
p=probabilities
)
indB = np.random.choice(
indices,
p=probabilities
)
parentA = generation_data[indA][vec_ind]
parentB = generation_data[indB][vec_ind]
mid = int(len(parentA) * 0.5)
return parentA[:mid] + parentB[mid:]
if crossover == 'rest':
while len(new_generation_data) < len(generation_data):
child = choose()
new_generation_data.append(child)
else:
for i in range(crossover):
child = choose()
new_generation_data.append(child)
return new_generation_data
def GA(parameters):
""" ------------------------------------------------------------------------
INITIALIZATION
-------------------------------------------------------------------------"""
global descending, sort_by, choices, top_X
def delete_lines(n=1):
for _ in range(n):
sys.stdout.write('\x1b[1A')
sys.stdout.write('\x1b[2K')
i = 0
start = time.time()
if settings.get('Save data'):
current_directory = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'CSVs'
)
unique_id = datetime.now().strftime('%d%m%H%M')
file_name = 'ActuatorGA_000' + str(i) + unique_id + '.txt'
file_path = os.path.join(
current_directory,
file_name
)
while os.path.isfile(file_path):
i += 1
file_name = 'ActuatorGA_000' + str(i) + unique_id + '.txt'
file_path = os.path.join(
current_directory,
file_name
)
generation_save_directory = open(file_path, 'a')
columns = [
"MAX X",
"MAX Y",
"MAX DISTANCE",
"TOTAL CURVATURE",
"ORIENTATION VECTOR",
"CURVE FIT",
]
results = [[
columns[0],
columns[1],
columns[2],
columns[3],
columns[4],
columns[5],
]]
""" ------------------------------------------------------------------------
CHECKS
-------------------------------------------------------------------------"""
if settings.get('Save data'):
generation_save_directory.write(("{}\n".format(results[0])))
pop_size = parameters.get('Population size')
if any(value == True for value in parameters.get('Fitness Metric').get('Metrics').values()) and \
any(value == True for value in parameters.get('Curve fitting').values()):
exception_string = ('Cannot optimize for fitness metric and curve fitting at the same time. Check parameters dictionary')
raise Exception(exception_string)
if sum(value == True for value in parameters.get('Fitness Metric').get('Metrics').values()) > 1:
exception_string = (
'Only one fitness metric allowed. Check parameters dictionary')
raise Exception(exception_string)
if sum(value == True for value in parameters.get('Fitness Metric').get('Metrics').values()) == 0 and \
sum(value == True for value in parameters.get('Curve fitting').values()) == 0:
exception_string = ('Please choose a fitness metric. Check parameters dictionary')
raise Exception(exception_string)
if sum(value == True for value in parameters.get('Curve fitting').values()) > 1:
exception_string = (
'Only one curve fit allowed. Check parameters dictionary')
raise Exception(exception_string)
if any(value == True for value in parameters.get('Curve fitting').values()):
descending = False
sort_by = 5
else:
fitness = parameters.get('Fitness Metric').get('Metrics')
descending = parameters.get('Fitness Metric').get('Maximise')
metric = [i for i, x in fitness.items() if x]
sort_by = list(fitness.keys()).index(metric[0])
num_segments = parameters.get('Number of segments').get('Type')
if num_segments == 'Integer':
num_segments = parameters.get('Number of segments').get('Number')
else:
num_segments = 0
patience = parameters.get('Patience')
maximum = parameters.get('Maximum iterations')
tolerance = parameters.get('Tolerance')
elite = parameters.get('Selection').get('Elite')
rand = parameters.get('Selection').get('Random')
mutation = parameters.get('Selection').get('Mutation')
crossover = parameters.get('Selection').get('Crossover')
choices = parameters.get('Choices')
num_top = parameters.get('Top')
check_set = set(str(value).lower() for value in parameters.get(
'Selection').values())
if not 'rest' in check_set:
exception_string = (
'One selection method must be set to \'rest\'. Check parameters dictionary')
raise Exception(exception_string)
cumm_percentage = 0
for sel_value in parameters.get('Selection').values():
if isinstance(sel_value, int):
cumm_percentage += sel_value / pop_size
elif isinstance(sel_value, tuple):
cumm_percentage += sel_value[0]
elif isinstance(sel_value, float):
cumm_percentage += sel_value
if cumm_percentage > 1:
exception_string = (
'Cummulative selection values cannot exceed 100%. Check parameters dictionary')
raise Exception(exception_string)
""" ------------------------------------------------------------------------
RANDOM INITIAL POPULATION
-------------------------------------------------------------------------"""
top_X = [[0] * len(results[0])]*num_top
while len(results) <= pop_size:
if num_segments == 0:
orientations = [np.random.choice(choices) for _ in range(np.random.randint(1, 50))]
else:
orientations = [np.random.choice(choices)
for _ in range(num_segments)]
results.append(evaluate(orientations, True))
new_list = results[1:]
new_list.sort(key=lambda x: x[sort_by], reverse=descending)
results = new_list
indi_time = 0
top = parameters.get('Top')
top_X = copy.deepcopy(results[:top])
best = top_X[0][sort_by]
stop_criteria_counter = 0
iterations = 0
stop = False
iteration = 0
if descending:
op = operator.ge
else:
op = operator.le
while not stop:
indi_s_time = time.time()
fitnesses = [item[sort_by] for item in results]
min_shifted = abs(min(fitnesses))
fitnesses = list(map(lambda x: x + min_shifted, fitnesses))
if sum(fitnesses) == 0:
probabilities = pop_size*[1/pop_size]
else:
total = sum(fitnesses)
probabilities = list(map(lambda x: x/total, fitnesses))
probabilities = np.array(probabilities).flatten()
new_generation = selection(results, num_segments, elite, rand, mutation, crossover, probabilities)
results = [evaluate(ea) for ea in new_generation]
results.sort(key=lambda x: x[sort_by], reverse=descending)
gen_top = results[0][sort_by]
lowest = float(min(np.array(top_X)[:,sort_by]))
highest = float(max(np.array(top_X)[:,sort_by]))
top_range = np.arange(lowest, highest)
if descending:
checker = highest
else:
checker = lowest
new_place = top-1
if (gen_top in top_range) or op(gen_top, checker):
for place in range(top-2):
if op(gen_top, top_X[place][sort_by]):
new_place = place
for i in range(new_place, top-2):
top_X[i+1] = top_X[i]
top_X[new_place] = results[0]
top_X.sort(key=lambda x: x[sort_by], reverse=descending)
if parameters.get('Stopping criteria').get('Maximum iterations') and parameters.get('Stopping criteria').get('Tolerance'):
iterations += 1
if iterations > maximum:
stop = True
if op(best, gen_top):
stop_criteria_counter += 1
else:
stop_criteria_counter = 0
if stop_criteria_counter > patience:
stop = True
elif parameters.get('Stopping criteria').get('Tolerance'):
if op(best, gen_top):
stop_criteria_counter += 1
else:
stop_criteria_counter = 0
if stop_criteria_counter > patience:
stop = True
elif parameters.get('Stopping criteria').get('Maximum iterations'):
iterations += 1
if iterations > maximum:
stop = True
iteration += 1
best = top_X[0][sort_by]
print('\nIteration:\t{}'.format(iteration))
print('\nTop value:\t{}'.format(float(best)))
delete_lines(n=4)
indi_e_time = time.time()
indi_time += (indi_e_time - indi_s_time)/pop_size
if settings.get('Save data'):
for line in results[1:]:
generation_save_directory.write(("{}\n".format(line)))
avg_time = indi_time/iteration
end = time.time()
print("\n" + 150*"-")
if iterations > maximum:
print("\nMAXIMUM ITERATIONS REACHED\n")
else:
print("\nSTOPPING CRITERIA REACHED\n")
print("Number of iterations:\t{}\n".format(iteration))
print("Duration:\t{:.5f} s\n".format(end - start))
print("Average duration per individual:\t{:.5f} s".format(avg_time))
print("\n" + 150*"-")
if settings.get('Save data'):
generation_save_directory.close()
check = [evaluate(ea) for ea in np.array(top_X)[:,4]]
check.sort(key=lambda x: x[sort_by], reverse=descending)
if settings.get('Plot final'):
plot_limb(check)
def plot_limb(limbs):
def on_click(event):
ax = event.inaxes
if ax is None:
return
if event.button != 1:
return
if zoomed_axes[0] is None:
zoomed_axes[0] = (ax, ax.get_position())
ax.set_position([0.1, 0.1, 0.8, 0.8])
ax.legend(loc='best')
ax.get_xaxis().set_visible(True)
ax.get_yaxis().set_visible(True)
ax.xaxis.set_major_locator(MultipleLocator(5))
ax.grid(linestyle=':')
ax.set_ylim(0)
ax.margins(x=0, y=-0.25)
for axis in event.canvas.figure.axes:
if axis is not ax:
axis.set_visible(False)
else:
zoomed_axes[0][0].set_position(zoomed_axes[0][1])
zoomed_axes[0] = None
ax.get_legend().remove()
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
for axis in event.canvas.figure.axes:
axis.set_visible(True)
event.canvas.draw()
zoomed_axes = [None]
for i in range(len(limbs[0])):
if isinstance(limbs[0][i],list):
vec_ind = i
limbs = np.array(limbs)
if len(limbs.shape) > 1:
num_plots = len(limbs)
limbs = limbs[:,vec_ind]
else:
num_plots = len(limbs.shape)
limbs = [limbs]
# fig = vp.Fig(size=(600,500), show=False)
# limb = Limb()
# limb.build(limbs[0])
# points = np.copy(limb.XY)
# line = fig[0, 0].plot((points[0, :], points[1, :]), color='red')
# fig.show(run=True)
specs = strategies.SquareStrategy('center').get_grid(num_plots)
fig = plt.figure(1, constrained_layout=False)
# fig.canvas.set_window_title('Top ' + str(num_plots))
for vec, sub in zip(limbs, specs):
ax = fig.add_subplot(sub)
limb = Limb()
limb.build(vec)
segs = len(limb.orient)
points = np.copy(limb.XY)
rots = limb.curvature
# ax.set_title("Soft actuator\n" + "Number of segments: {}".format(segs))
# ax.get_xaxis().set_visible(False)
# ax.get_yaxis().set_visible(False)
ax.plot([0, 0], [-2, 2], color='black')
# ax.xaxis.set_major_locator(MultipleLocator(1))
if settings.get('Rainbow'):
colors = cm.rainbow(np.linspace(0, 1, segs))
"""------NORMAL-------"""
for i in range(0, segs-1):
ax.plot([i, i+2], [0, 0], color=colors[i])
"""------ACTUATED-------"""
for i in range(0, segs-1):
ax.plot(points[0, i:i+2], points[1, i:i+2], color=colors[i])
else:
"""------NORMAL-------"""
# normal = np.zeros((segs+1))
# ax.plot(normal, color='grey',
# label="Initial pressure (P=P" + r'$_i$' + ")")
"""------ACTUATED-------"""
ax.plot(points[0, :], points[1, :], color='red',
label="Reduced-order model")
if any(value == True for value in parameters.get('Curve fitting').values()):
m = points[0][-1]/(2*pi)
if parameters.get('Curve fitting').get('Sin'):
curve = 20*np.sin(points[0]/m)
elif parameters.get('Curve fitting').get('Cos'):
curve = 25*np.cos(points[0]/m)-25
elif parameters.get('Curve fitting').get('Custom'):
curve = []
func = parameters.get('Curve fitting').get('Custom func')
for ea in points[0]/m:
x = ea
curve.append(eval(func))
ax.plot(points[0], curve, color='black', alpha=0.85, linestyle='--', label='Desired profile')
# ax.margins(0.5, 0.5)
# ax.set_xlim(0)
# ax.margins(x=0, y=-0.25)
if settings.get('Plot boundaries'):
to_tuple = [(x, y) for x, y in zip(limb.XY[0], limb.XY[1])]
line_check = LineString(to_tuple)
line_top = line_check.parallel_offset(1.9, side='left')
line_bottom = line_check.parallel_offset(1.9, side='right')
ax.plot(line_top.xy[0], line_top.xy[1])
ax.plot(line_bottom.xy[0], line_bottom.xy[1])
if settings.get('Overlay images'):
def imshow_affine(ax, z, *args, **kwargs):
im = ax.imshow(z, *args, **kwargs);
_, x2, y1, _ = im.get_extent()
im._image_skew_coordinate = (x2, y1)
return im
# width = 2.57
# height = 3.9
width = 22.5
height = 35
image_directory = os.path.dirname(
os.path.realpath(__file__)) + '\\box.png'
# img = plt.imread(image_directory, format='png')
# img = Image.open(image_directory)
img = mpimg.imread(image_directory)
cps = [[], []]
for i in range(segs):
cps[0].append((points[0][i] + points[0][i+1])/2)
cps[1].append((points[1][i] + points[1][i+1])/2)
cps = np.asarray(cps)
for i in range(cps.shape[1]):
img_show = imshow_affine(
ax,
img,
interpolation='none',
extent=[0, width, 0, height],
)
c_x, c_y = width/2, (16*cos(radians(11)))
if limb.orient[i] == "TOP":
rot_angle = 180 + degrees(rots[i+1])
elif limb.orient[i] == "BOTTOM":
rot_angle = degrees(rots[i+1])
else:
rot_angle = degrees(rots[i+1])
transform_data = (transforms.Affine2D()
.rotate_deg_around(c_x, c_y, rot_angle)
.translate((cps[0][i]-c_x), (cps[1][i]-c_y))
+ ax.transData)
img_show.set_transform(transform_data)
diff = 20
x_min = min(points[0, :])-diff
x_max = max(points[0, :])+diff
y_min = min(points[1, :])-diff
y_max = max(points[1, :])+diff
# fig.canvas.mpl_connect('button_press_event', on_click)
# ax.set_aspect('equal', adjustable='datalim')
# ax.autoscale()
# plt.tight_layout()
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.xlabel('X [mm]')
plt.ylabel('Y [mm]')
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.grid(linestyle=':')
# ax.margins(0.5, 0.1)
plotDavid(ax)
figManager = plt.get_current_fig_manager()
figManager.window.state('zoomed')
lgd = ax.legend(loc='lower center', bbox_to_anchor=(0.5, 1))
# plt.show()
plt.savefig('C:\\Users\\zjmon\\Documents\\Meesters\\Thesis\\figs\\Cos.pgf')
# bbox_extra_artists=(lgd,), bbox_inches='tight')
if __name__ == '__main__':
"""Genetic Algorithm for Soft Actuator
Parameters:
Fitness Metric -- Metric by which each individual in a population is evaluated (choose one by changing to True)
Curve fitting -- Curve to fit actuator shape to. Custom functions must use 'x' as variable.
Population size -- Population size of the GA
Stopping criteria -- Determines when the GA stops (choose one by changing to True)
Tolerance - Fitness metric difference between subsequent generations' best individual
Maximum iterations - Run for X iterations
Maximum iterations -- If Stopping criteria = Maximum iterations; Set number of iterations here
Tolerace -- If Stopping criteria = Tolerance; Set tolerance here
Patience -- If Stopping criteria = Tolerance; Grace period (in iterations) before GA is terminated
Number of segments -- Number of segments in actuator ('None' or 'Integer'). If 'None' - becomes learnable parameter
Selection -- GA selection percentages or integers. NB: One method must be 'rest'
Elite - can be int or float
Random - can be int or float or range for scheduled decrease of randomness
Scheduled Decrease format = (start percentage, end percentage, number of steps in schedule) i.e. (0.5, 0.05, 100)
Mutation - can be int or float
Crossover - can be int or float
Top -- Number of top individuals to save
"""
global parameters, settings
def test(vec):
plot_limb(vec)
parameters = {
'Fitness Metric': {
'Maximise': False,
'Metrics': {
'X-coordinate': False,
'Y-coordinate': False,
'Distance from origin': False,
}
},
'Curve fitting': {
'Sin': False,
'Cos': True,
'Custom': False,
'Custom func': 'x**0.5', # x**2, x**0.5, 2**x
},
'Population size': 250,
'Stopping criteria': {
'Maximum iterations': True,
'Tolerance': True,
},
'Maximum iterations': 1000,
'Tolerance': 1e-10,
'Patience': 50,
'Number of segments': {
'Type': 'Integer',
'Number': 15,
},
'Selection': {
'Elite': 1,
'Random': 0.01,
'Mutation': 0.05,
'Crossover': 'rest',
},
'Top': 1,
'Choices': ['BOTTOM', 'TOP'],
'Segment width': 1,
}
settings = {
'Multiprocessing': False,
'Plot final': True,
'Rainbow': False,
'Overlay images': True,
'Save data': False,
'Plot boundaries': False,
}
# MIN X
# test(10*['TOP'] + ['BOTTOM', 'BOTTOM', 'TOP', 'BOTTOM', 'BOTTOM'])
# MAX X
# ['BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'TOP',
# 'BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'BOTTOM', 'TOP']
# MAX Y
# test(5*['TOP']+['BOTTOM', 'TOP', 'BOTTOM',
# 'TOP', 'BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'BOTTOM', 'TOP'])
# SIN
# test(['TOP', 'TOP', 'BOTTOM', 'BOTTOM', 'BOTTOM', 'BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'TOP', 'BOTTOM', 'TOP', 'TOP', 'TOP', 'TOP'])
# COS
test(['BOTTOM', 'BOTTOM', 'BOTTOM', 'TOP', 'TOP', 'TOP', 'BOTTOM',
'TOP', 'TOP', 'TOP', 'TOP', 'BOTTOM', 'BOTTOM', 'BOTTOM', 'TOP'])
# test(['BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'TOP',
# 'BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'BOTTOM', 'TOP', 'BOTTOM', 'TOP'])
# test(15*['BOTTOM'])
# GA(parameters)