Repository navigation
Expand file tree
/
Copy pathsprites.py
More file actions
1856 lines (1432 loc) · 62.6 KB
/
Copy pathsprites.py
File metadata and controls
1856 lines (1432 loc) · 62.6 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
import time
import sys
import random
import networks
import math
import numpy
import copy
import pymunk
from PyQt5 import QtCore, QtGui
from PyQt5 import QtWidgets
from userInterface import Ui_MainWindow
from threading import Thread
from pymunk import Vec2d
from torch import tensor
#import neural
import neural
import physics
cell_types = ["barrier", "carniv", "eye", "olfactory", "co2C", "push", "body", "rotate"]
dead_image = "dead.png"
dirType = "/"
if sys.platform.startswith("win"):
dirType = "\\"
#co2_dispersion_ratio = 20
# The dispersion ratio for dead cells.
# This is used to calculate how much CO2 is added back into the environment when a dead cell is dispersed
# Dispersion equation: <dispersion_ratio> * (<cell_size> / 2) * (<cell_mass> / 2)
last_bubble_creation = time.time()
bubble_interval = 1.
co2_conversion_ratio = 3 # The amount of energy generated from 1 CO2 particle
cell_dispersion_rate = 6 # The percentage of a dead cell's mass to disperse per second
reproduction_limit = 6 # The amount of time (in seconds) an organism has to wait before reproducing again
offspring_amount = 1 # How many offspring to create when an organism reproduces
heal_rate = 4 # The percentage of health to heal each second if the cell has enough energy
mass_cutoff = 1 # If a dead cell's percentage of mass becomes less than this, it will be removed (dispersed completely)
break_damage = 5 # The amount of damage a cell does to its parent when it dies (break off from body) - multiplied by its size
starvation_rate = 6 # The percentage of damage to do to a cell each second if its energy equals 0
neural_update_delay = .5 # How long to wait before activating an organism's brain - helps reduce lag
learning_update_delay = .5 # How long to wait before training an organism
training_epochs = 1 # How many epochs to train a network for per training interval
max_push_speed = 250
max_rotation_speed = 6 # Radians per second
age_limit = 200
eyesight_multiplier = 10 # This multiplied by an eye cell's size is how far away that eye can see
olfactory_multiplier = 15 # This multiplied by an olfactory cell's size is how far away that organism can smell dead cells
base_cell_info = {
"health": {
# This is multiplied by the size and mass of each given cell
# <max_health> = <base_health> * <cell_size> * <cell_mass>
"barrier": 30,
"carniv": 30,
"co2C": 15,
"eye": 8,
"olfactory": 24,
"push": 24,
"body": 24,
"heart": 15,
"rotate": 24
},
"energy_usage": {
# The first variable in the lists below represent an idle cell
# The second variable reprents a cell's energy intake while in use
# This is multiplied by the size and mass of each given cell
# <max_energy_usage> = <base_energy_usage> * (<cell_size> / 2) * (<cell_mass> / 2)
"barrier": [1.2, 1.2],
"carniv": [2.5, 4],
"co2C": [3.6, 3.6],
"eye": [2, 2],
"olfactory": [3.5, 5],
"push": [3, 6],
"body": [1.2, 1.2],
"heart": [2.5, 2.5],
"rotate": [2.5, 5]
},
"energy_storage": {
# This is multiplied by the size and mass of each given cell
# <energy_storage> = <base_energy_storage> * <cell_size> * <cell_mass>
"barrier": 15,
"carniv": 30,
"co2C": 33,
"eye": 20,
"olfactory": 30,
"push": 30,
"body": 30,
"heart": 33,
"rotate": 30
},
"damage": {
# The damage each cell does when in contact with a cell from another organism
"barrier": 0,
"carniv": 2,
"co2C": 0,
"eye": 0,
"olfactory": 0,
"push": 0,
"body": 0,
"heart": 0,
"rotate": 0
}
}
def random_direction():
deg = random.randrange(0, 360)
rad = math.radians(deg)
x_direction = math.cos(rad)
y_direction = math.sin(rad)
return [x_direction, y_direction]
def calculateDistance(x1,y1,x2,y2):
return math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
def positive(x):
if x > 0:
return x
return -x
def num2perc(num, maxNum):
return (float(num) / float(maxNum)) * 100.0
def perc2num(perc, maxNum):
return (float(perc) / 100.0) * float(maxNum)
def getAngle(x1, y1, x2, y2):
myradians = math.atan2(y2-y1, x2-x1)
return myradians
def getDirection(angle):
direction = [math.cos(angle), math.sin(angle)]
return direction
def randomizeList(l):
return sorted(l, key=lambda x: random.random())
def viable_organism_position(pos, dna, environment):
orgList = environment.info["organism_list"]
dead_cells = [sprite for sprite in environment.sprites if not sprite.alive]
overlappingSprites = []
dna_rect = dna.get_rect()
dna_rect = [
dna_rect[0] + pos[0],
dna_rect[1] + pos[1],
dna_rect[2] + pos[0],
dna_rect[3] + pos[1]
]
if dna_rect[0] < 0 or dna_rect[2] > environment.width or dna_rect[1] < 0 or dna_rect[3] > environment.height:
return False, []
for org in orgList:
if not org.alive():
continue
rect = org.get_rect()
# Rect = [min_x, min_y, max_x, max_y]
if (dna_rect[0] > rect[0] and dna_rect[0] < rect[2]) or (dna_rect[2] > rect[0] and dna_rect[2] < rect[2]) or (rect[0] > dna_rect[0] and rect[2] < dna_rect[2]): # Within X boundaries
if (dna_rect[1] > rect[1] and dna_rect[1] < rect[3]) or (dna_rect[3] > rect[1] and dna_rect[3] < rect[3]) or (rect[1] > dna_rect[1] and rect[3] < dna_rect[3]): # Within Y boundaries
return False, []
for sprite in dead_cells:
spritePos = sprite.getPos()
spriteRadius = sprite.radius
if spritePos[0] > dna_rect[0] and spritePos[0] < dna_rect[2]: # Within X boundaries
if spritePos[1] > dna_rect[1] and spritePos[1] < dna_rect[3]:
overlappingSprites.append(sprite)
return True, overlappingSprites
def get_new_organism_position(old_organism, dna, environment):
orgSize = old_organism.dna.get_size()
newSize = dna.get_size()
dist = [ (orgSize[0]/1.3) + (newSize[0]/1.3), (orgSize[1]/1.3) + (newSize[1]/1.3) ]
degList = list(range(360))
#rDegList = sorted(degList, key=lambda x: random.random())
rDegList = randomizeList(degList)
for i in rDegList:
rad = math.radians(i)
direction = [math.cos(rad), math.sin(rad)]
addX = direction[0] * dist[0]
addY = direction[1] * dist[1]
xPos = old_organism.pos[0] + addX
yPos = old_organism.pos[1] + addY
viable, overlappingSprites = viable_organism_position([xPos, yPos], dna, environment)
if viable:
for sprite in overlappingSprites:
environment.removeSprite(sprite)
sprite.info["removed"] = True
return [xPos, yPos]
return False
def eye_segment_handler(arbiter, space, data):
if isinstance(arbiter.shapes[0], pymunk.Segment) or isinstance(arbiter.shapes[1], pymunk.Segment):
return False
if arbiter.shapes[1].sensor:
return False
sensor = arbiter.shapes[0].sprite
sprite = arbiter.shapes[1].sprite
if not sensor.alive:
return False
if sensor.organism != sprite.organism:
if not sprite in sensor.info["view"]:
sensor.info["view"].append(sprite)
return False
def finish_cell_info(cell_info):
cell_type = cell_info["type"]
cell_mass = cell_info["mass"]
cell_size = cell_info["size"]
cell_health = (base_cell_info["health"][cell_type] * cell_size) + (base_cell_info["health"][cell_type] * cell_mass)
cell_info["max_health"] = cell_health
cell_energy_usage = [ (i * cell_size) + (i * cell_mass) for i in base_cell_info["energy_usage"][cell_type] ]
cell_info["energy_usage"] = cell_energy_usage
cell_damage = (base_cell_info["damage"][cell_type] * cell_size) + (base_cell_info["damage"][cell_type] * cell_mass)
cell_info["damage"] = cell_damage
cell_energy_storage = (base_cell_info["energy_storage"][cell_type] * cell_size) + (base_cell_info["energy_storage"][cell_type] * cell_mass)
cell_info["energy_storage"] = cell_energy_storage
def build_sprite(environment, organism, pos, cell_id, cell_info, alive=True):
if alive:
image = "Images{}{}.png".format(dirType, cell_info["type"])
else:
image = "Images{}{}".format(dirType, dead_image)
body, shape = physics.makeCircle(
cell_info["size"]/2,
friction = cell_info["friction"],
elasticity = cell_info["elasticity"],
mass = cell_info["mass"]
)
newCell = physics.Sprite(
pos,
cell_info["size"],
cell_info["size"],
environment,
body,
shape,
image=image
)
newCell.cell_id = cell_id
if organism is not None:
newCell.collision = lambda sprite: organism._cell_collision(newCell, sprite)
newCell.organism = organism
newCell.cell_info = cell_info
newCell.info = {
"health": cell_info["max_health"],
"energy": cell_info["energy_storage"]/2,
"in_use": False,
"detection_items": [],
"view": [],
"removed": False,
"colliding": [],
"sight_range": 0.0,
"smell_range": 0.0
}
newCell.alive = alive
newCell.isBubble = False
newCell.creationTime = time.time()
newCell.environment = environment
if organism is not None:
newCell.mouseDoubleClickEvent = lambda event: organism.cell_double_clicked(newCell)
if cell_info["type"] == "eye" and newCell.alive:
newCell.info["sight_range"] = cell_info["size"] * eyesight_multiplier
newBody, newShape = physics.makeCircle( newCell.info["sight_range"], friction=0.0, elasticity=0.0, mass=1 )
newShape.sensor = True
newShape.collision_type = 1
newShape.sprite = newCell
newBody.position = pos
joint = pymunk.PinJoint(newBody, newCell.body, [0,0], [0,0])
newCell.info["detection_items"] = [newBody, newShape, joint]
elif cell_info["type"] == "olfactory" and newCell.alive:
newCell.info["smell_range"] = cell_info["size"] * olfactory_multiplier
newBody, newShape = physics.makeCircle( newCell.info["smell_range"], friction=0.0, elasticity=0.0, mass=1 )
newShape.sensor = True
newShape.collision_type = 1
newShape.sprite = newCell
newBody.position = pos
joint = pymunk.PinJoint(newBody, newCell.body, [0,0], [0,0])
newCell.info["detection_items"] = [newBody, newShape, joint]
return newCell
class DNA():
def __init__(self):
self.cells = {}
# Structure: {
# <Cell_ID>: {
# "size": <integer>,
# "type": <string>,
# "elasticity": <float>,
# "friction": <float>
# "mass": <integer>,
# "first": <boolean>,
# "relative_pos": [<integer>, <integer>],
# "mirror_self": <cell_id>,
# "max_health": <integer>,
# "energy_usage": [<idle>, <in use>],
# "energy_storage": <integer>,
# "damage": <integer>
# }
#}
# `relative_pos` helps keep cells from forming to close to one another (starts at [0,0] for the first cell)
self.growth_pattern = {}
# Structure: {
# <Cell_ID>: {
# <Cell_ID_1>: [<X_Direction>, <Y_Direction>],
# <Cell_ID_2>: [<X_Direction>, <Y_Direction>]
# },
# <Cell_ID>: {
# <Cell_ID_1>: [<X_Direction>, <Y_Direction>],
# <Cell_ID_2>: [<X_Direction>, <Y_Direction>]
# }
#}
self._base_brain_structure = {
"input_size": 6,
"inputs": ["energy", "health", "rotation", "speed", "x_direction", "y_direction"],
"hidden_layers": [], # [<integer>, <integer>, <integer>]
"hidden_weights": [], # [ [<float>, <float>], [<float>, <float>, <float>], [<float>, <float>] ]
"output_size": 4,
"outputs": ["rotation", "speed", "x_direction", "y_direction"],
"optimizer": "adam"
}
self.brain_structure = copy.deepcopy(self._base_brain_structure)
self.trainingInput = []
self.trainingOutput = []
self.trainingReward = []
self.trainingHidden = []
self.previousInputs = []
self.previousOutputs = []
self.previousDopamine = []
self.stim_history = [0]*10
self.short_term_memory = []
self.hidden_memory = []
self.base_info = {
"distanceThreshold": .8,
"mirror_x": False,
"mirror_y": False,
"maximum_creation_tries": 30,
"curiosity": 0.5 # Ranges from 0.0 to 1.0
}
# Structure: {
# "distanceThreshold": <float>,
# "mirror_x": <boolean>,
# "mirror_y": <boolean>,
# "maximum_creation_tries": <integer>,
# "curiosity": <float>
#}
self.cellRange = [3,30]
self.sizeRange = [6,42]
self.massRange = [5,20]
self.mirror_x = [0.6, 0.4]
self.mirror_y = [0.6, 0.4]
self.generation = 0
def copy(self):
return copy.deepcopy(self)
def erase_memory(self):
self.trainingInput = []
self.trainingOutput = []
self.trainingReward = []
self.previousInputs = []
self.previousOutputs = []
self.short_term_memory = []
def first_cell(self):
# Returns the first cell that's created while building this creature's body
for cid in self.cells:
if self.cells[cid]["first"]:
return cid
def sub_cells(self, cell_id):
if cell_id in self.growth_pattern:
return [ cid for cid in self.growth_pattern[cell_id] ]
return []
def all_sub_cells(self, cell_id):
all_cells = []
checkList = []
if cell_id in self.growth_pattern:
checkList.extend( self.sub_cells(cell_id) )
while checkList:
cid = checkList[0]
all_cells.append(cid)
checkList.extend( self.sub_cells(cid) )
checkList.remove(cid)
return all_cells
def _lower_cells(self):
# Returns all cells that do not contain children
lower_cell_list = []
for cell_id in self.growth_pattern:
if not self.sub_cells(cell_id):
lower_cell_list.append(cell_id)
return lower_cell_list
def grows_from(self, cell_id):
# Returns the cell ID that this given cell grows from
for cid in self.growth_pattern:
if cell_id in self.growth_pattern[cid]:
return cid
def path_to_first(self, cell_id):
pList = []
while True:
parentCell = self.grows_from(cell_id)
if parentCell:
cell_id = parentCell
pList.append(cell_id)
else:
break
return pList
def get_rect(self):
# The is a rect of the relative positions of the cells in this DNA class - not their in-world position
fCell = self.first_cell()
minX = self.cells[fCell]["relative_pos"][0]
maxX = self.cells[fCell]["relative_pos"][0]
minY = self.cells[fCell]["relative_pos"][1]
maxY = self.cells[fCell]["relative_pos"][1]
for cell_id in self.cells:
pos = self.cells[cell_id]["relative_pos"]
radius = self.cells[cell_id]["size"]/2
if pos[0]-radius < minX:
minX = pos[0]
if pos[0]+radius > maxX:
maxX = pos[0]
if pos[1]-radius < minY:
minY = pos[1]
if pos[1]+radius > maxY:
maxY = pos[1]
return [minX, minY, maxX, maxY]
def get_size(self):
rect = self.get_rect()
minX = rect[0]
minY = rect[1]
maxX = rect[2]
maxY = rect[3]
if minX < 0:
minX = -minX
if minY < 0:
minY = -minY
width = maxX + minX
height = maxY + minY
return [width, height]
def cell_distance(self, id1, id2):
if not id1 in self.cells or not id2 in self.cells:
return
rel_pos1 = self.cells[id1]["relative_pos"]
rel_pos2 = self.cells[id2]["relative_pos"]
x1 = rel_pos1[0]
y1 = rel_pos1[1]
x2 = rel_pos2[0]
y2 = rel_pos2[1]
distance = calculateDistance(x1, y1, x2, y2)
return distance
def _new_cell_id(self):
cid = 1
while cid in self.cells:
cid += 1
return cid
def _finish_cell_info(self, cell_info):
cell_type = cell_info["type"]
cell_mass = cell_info["mass"]
cell_size = cell_info["size"]
cell_health = base_cell_info["health"][cell_type] * cell_size * cell_mass
cell_info["max_health"] = cell_health
cell_energy_usage = [i * cell_size * cell_mass for i in base_cell_info["energy_usage"][cell_type]]
cell_info["energy_usage"] = cell_energy_usage
cell_damage = base_cell_info["damage"][cell_type] * cell_size * cell_mass
cell_info["damage"] = cell_damage
cell_energy_storage = base_cell_info["energy_storage"][cell_type] * cell_size * cell_mass
cell_info["energy_storage"] = cell_energy_storage
def _make_random_cell(self, sizeRange, massRange, first_cell=False):
cell_id = self._new_cell_id()
cell_info = {}
cell_size = random.randrange(int(sizeRange[0]), int(sizeRange[1]))
cell_info["size"] = cell_size
cell_mass = random.randrange(int(massRange[0]), int(massRange[1]))
cell_info["mass"] = cell_mass
cell_elasticity = random.random()
cell_info["elasticity"] = cell_elasticity
cell_friction = random.random()
cell_info["friction"] = cell_friction
if first_cell:
cell_info["mirror_self"] = cell_id
else:
cell_info["mirror_self"] = None
if first_cell:
cell_type = "heart"
else:
cell_type = random.choice(cell_types)
cell_info["type"] = cell_type
finish_cell_info(cell_info)
cell_info["first"] = first_cell
return cell_id, cell_info
def remove_cell(self, cell_id, removing_mirror=False, remove_sub_cells=True):
# Returns a modified version of this DNA with the missing cells
if not cell_id in self.cells:
return
new_dna = self.copy()
if remove_sub_cells:
for cID in new_dna.sub_cells(cell_id):
new_dna = new_dna.remove_cell(cID, removing_mirror=removing_mirror)
cell_info = new_dna.cells[cell_id]
if cell_info["mirror_self"] and not removing_mirror:
new_dna = new_dna.remove_cell(cell_info["mirror_self"], removing_mirror=True)
new_dna.growth_pattern.pop(cell_id)
new_dna.cells.pop(cell_id)
for cID in new_dna.growth_pattern:
if cell_id in new_dna.growth_pattern[cID]:
new_dna.growth_pattern[cID].pop(cell_id)
return new_dna
def set_mass(self, cell_id, new_mass, changing_mirror=False):
if not cell_id in self.cells:
return
self.cells[cell_id]["mass"] = new_mass
if self.cells[cell_id]["mirror_self"] and not changing_mirror:
self.set_mass(self.cells[cell_id]["mirror_self"], new_mass, changing_mirror=True)
finish_cell_info(self.cells[cell_id])
def set_size(self, cell_id, new_size, changing_mirror=False):
if not cell_id in self.cells:
return
self.cells[cell_id]["size"] = new_size
if self.cells[cell_id]["mirror_self"] and not changing_mirror:
self.set_size(self.cells[cell_id]["mirror_self"], new_size, changing_mirror=True)
finish_cell_info(self.cells[cell_id])
def change_type(self, cell_id, new_type, changing_mirror=False):
if not cell_id in self.cells:
return
self.cells[cell_id]["type"] = new_type
if self.cells[cell_id]["mirror_self"] and not changing_mirror:
self.change_type(self.cells[cell_id]["mirror_self"], new_type, changing_mirror=True)
finish_cell_info(self.cells[cell_id])
def add_cell(self, parentID, cell_type, size, mass, elasticity, friction, angle):
if not parentID in self.cells:
return
grow_direction = [ math.cos(angle), math.sin(angle) ]
cell_id = self._new_cell_id()
cell_info = {}
cell_info = {
"size": size,
"mass": mass,
"elasticity": elasticity,
"friction": friction,
"type": cell_type,
"mirror_self": None,
"first": False
}
finish_cell_info(cell_info)
relative_pos = self._new_relative_pos(parentID, grow_direction, cell_info["size"])
cell_info["relative_pos"] = relative_pos
self.growth_pattern[parentID][cell_id] = grow_direction
self.cells[cell_id] = cell_info
self.growth_pattern[cell_id] = {}
if self.base_info["mirror_x"] or self.base_info["mirror_y"]:
parentID = self.grows_from(cell_id)
grow_direction = self.growth_pattern[parentID][cell_id]
self._apply_mirror(cell_id, parentID, grow_direction)
return cell_id
def set_elasticity(self, cell_id, new_value):
if not cell_id in self.cells:
return
self.cells[cell_id]["elasticity"] = new_value
if cell_id == self.first_cell():
return
mirror_id = self.cells[cell_id]["mirror_self"]
if mirror_id is not None and mirror_id in self.cells:
self.cells[mirror_id]["elasticity"] = new_value
def set_friction(self, cell_id, new_value):
if not cell_id in self.cells:
return
self.cells[cell_id]["friction"] = new_value
if cell_id == self.first_cell():
return
mirror_id = self.cells[cell_id]["mirror_self"]
if mirror_id is not None and mirror_id in self.cells:
self.cells[mirror_id]["friction"] = new_value
def _closest_cell_to_point(self, x, y):
# This function only compares the relative positions of cells
distances = {}
count = 0
for cell_id in self.cells:
rel_pos = self.cells[cell_id]["relative_pos"]
radius = self.cells[cell_id]["size"] / 2
dist = calculateDistance(x, y, rel_pos[0], rel_pos[1]) - radius
distances[dist] = cell_id
if distances:
closest_cell = distances[min(distances)]
dist = min(distances)
return closest_cell, dist
def _new_relative_pos(self, parentID, direction, childSize):
relParentPos = self.cells[parentID]["relative_pos"]
parentSize = self.cells[parentID]["size"]
newRelPos = relParentPos[:]
addX = direction[0] * ( (parentSize/2.1) + (childSize/2.1) )
addY = direction[1] * ( (parentSize/2.1) + (childSize/2.1) )
newRelPos = [newRelPos[0] + addX, newRelPos[1] + addY]
return newRelPos
def _cell_mirrorable(self, x, y, cell_info):
cellSize = cell_info["size"]
cellRadius = cellSize / 2
newX = x
newY = y
if self.base_info["mirror_x"]:
newX = -newX
if self.base_info["mirror_y"]:
newY = -newY
distance = calculateDistance(x, y, newX, newY) - (cellSize/2)
cid, distance2 = self._closest_cell_to_point(newX, newY)
if distance > (cellRadius*self.base_info["distanceThreshold"]) and distance2 > ( cellRadius*self.base_info["distanceThreshold"] ):
return True
return False
def _viable_cell_position(self, x, y, cell_info):
cid, dist = self._closest_cell_to_point(x, y)
size = cell_info["size"]
radius = size / 2
if self.base_info["mirror_x"] or self.base_info["mirror_y"]:
if not self._cell_mirrorable(x, y, cell_info):
return False
if dist > (radius*self.base_info["distanceThreshold"]):
return True
return False
def _apply_mirror(self, cell_id, grows_from, grow_direction, newID=None):
if newID is None:
newID = self._new_cell_id()
cell_info = self.cells[cell_id].copy()
self.cells[cell_id]["mirror_self"] = newID
cell_info["mirror_self"] = cell_id
relative_pos = self.cells[cell_id]["relative_pos"][:]
new_grow_direction = grow_direction[:]
if self.base_info["mirror_x"]:
relative_pos[0] = -relative_pos[0]
new_grow_direction[0] = -new_grow_direction[0]
if self.base_info["mirror_y"]:
relative_pos[1] = -relative_pos[1]
new_grow_direction[1] = -new_grow_direction[1]
new_grows_from = self.cells[grows_from]["mirror_self"]
#new_grow_direction = [-i for i in grow_direction]
self.growth_pattern[new_grows_from][newID] = new_grow_direction
cell_info["relative_pos"] = relative_pos
self.cells[newID] = cell_info
if not newID in self.growth_pattern:
self.growth_pattern[newID] = {}
def add_randomized_cell(self, sizeRange, massRange, first_cell=False):
cell_id, cell_info = self._make_random_cell(sizeRange, massRange, first_cell=first_cell)
if first_cell:
relative_pos = [0,0]
if self.cells and not first_cell:
pos_verified = False
iterations = 0
while not pos_verified:
if iterations > self.base_info["maximum_creation_tries"]:
return False
iterations += 1
grow_from = random.choice( list(self.cells) )
grow_direction = random_direction()
relative_pos = self._new_relative_pos(grow_from, grow_direction, cell_info["size"])
if self._viable_cell_position(relative_pos[0], relative_pos[1], cell_info):
pos_verified = True
self.growth_pattern[grow_from][cell_id] = grow_direction
cell_info["relative_pos"] = relative_pos
self.cells[cell_id] = cell_info
self.growth_pattern[cell_id] = {}
return cell_id
def _setup_brain_structure(self, hiddenRange):
self.brain_structure = copy.deepcopy(self._base_brain_structure)
for cell_id in self.cells:
cell_info = self.cells[cell_id]
if cell_info["type"] == "eye":
self.brain_structure["input_size"] += neural.output_lengths["eye"]
elif cell_info["type"] == "carniv":
self.brain_structure["input_size"] += neural.output_lengths["carniv"]
hiddenSize = random.randrange(hiddenRange[0], hiddenRange[1])
hiddenLayers = []
if self.brain_structure["input_size"] > self.brain_structure["output_size"]:
decRange = numpy.linspace(
self.brain_structure["input_size"],
self.brain_structure["output_size"],
hiddenSize
)
decRange = list(decRange)
else:
decRange = numpy.linspace(
self.brain_structure["output_size"],
self.brain_structure["input_size"],
hiddenSize
)
decRange = list(decRange)
decRange = decRange.reverse()
minRange = min(decRange)-1
maxRange = max(decRange)*2
for i in decRange:
hiddenLayerSize = int(random.triangular(minRange, i, maxRange))
while hiddenLayerSize == 0:
hiddenLayerSize = int(random.triangular(minRange, i, maxRange))
hiddenLayers.append(hiddenLayerSize)
self.brain_structure["hidden_layers"] = hiddenLayers
tempNet = neural.setup_network(self)
for layer in tempNet.hiddenLayers:
self.brain_structure["hidden_weights"].append( layer.weight.tolist() )
def randomize(self, cellRange=[3,30], sizeRange=[6,42], massRange=[5,20], mirror_x=[0.6, 0.4], mirror_y=[0.6, 0.4], hiddenRange=[2, 6]):
self.cellRange = cellRange
self.sizeRange = sizeRange
self.massRange = massRange
self.mirror_x = mirror_x
self.mirror_y = mirror_y
self.cells = {}
self.growth_pattern = {}
mirror_x = numpy.random.choice(numpy.arange(0, 2), p=mirror_x)
mirror_y = numpy.random.choice(numpy.arange(0, 2), p=mirror_y)
mirror_x = bool(mirror_x)
mirror_y = bool(mirror_y)
self.base_info["mirror_x"] = mirror_x
self.base_info["mirror_y"] = mirror_y
self.base_info["curiosity"] = random.random()
first_cell = True
for i in range(random.randrange(cellRange[0], cellRange[1])):
added = False
while not added:
added = self.add_randomized_cell(
sizeRange,
massRange,
first_cell=first_cell
)
first_cell = False
if self.base_info["mirror_x"] or self.base_info["mirror_y"]:
first_id = self.first_cell()
for cell_id in copy.deepcopy(self.cells):
if cell_id != first_id:
grow_from = self.grows_from(cell_id)
grow_direction = self.growth_pattern[grow_from][cell_id]
self._apply_mirror(cell_id, grow_from, grow_direction)
self._setup_brain_structure(hiddenRange)
return self
def mutate_cell_count(self, severity):
new_dna = self.copy()
current_count = len(self.cells)
countRange = int(severity * 18.)
countRange = round(countRange)
if not countRange:
return new_dna
addedCells = random.randrange(-countRange, countRange)
while current_count + addedCells < 2:
addedCells = random.randrange(-countRange, countRange)
if addedCells < 0:
for i in range(positive(addedCells)):
lCells = randomizeList(new_dna._lower_cells())
rCell = lCells[0]
if rCell in self.cells and not self.cells[rCell]["first"]:
new_dna.remove_cell(rCell)
elif addedCells > 0:
for i in range(addedCells):
added = False
while not added:
added = new_dna.add_randomized_cell(
new_dna.sizeRange,
new_dna.massRange
)
if new_dna.base_info["mirror_x"] or new_dna.base_info["mirror_y"]:
grow_from = new_dna.grows_from(added)
grow_direction = new_dna.growth_pattern[grow_from][added]
new_dna._apply_mirror(added, grow_from, grow_direction)
return new_dna
def mutate_cell_types(self, severity):
new_dna = self.copy()
for cell_id in new_dna.cells:
if random.random() <= severity and not new_dna.cells[cell_id]["first"]:
new_type = random.choice(cell_types)
new_dna.cells[cell_id]["type"] = new_type
if new_dna.base_info["mirror_x"] or new_dna.base_info["mirror_y"]:
mirror_id = new_dna.cells[cell_id]["mirror_self"]
if mirror_id:
if mirror_id in new_dna.cells:
new_dna.cells[mirror_id]["type"] = new_type
return new_dna
def mutate_cell_masses(self, severity):
new_dna = self.copy()
for cell_id in new_dna.cells:
if random.random() <= severity:
mRange = int(severity * 10.)
mRange = round(mRange)
if not mRange:
return new_dna
addRange = random.randrange(int(-mRange), int(mRange))
while new_dna.cells[cell_id]["mass"] + addRange <= 0:
addRange = random.randrange(int(-mRange), int(mRange))
new_dna.cells[cell_id]["mass"] += addRange
return new_dna
def mutate_brain_layers(self, severity, weight_persistence):
oldHidden = self.brain_structure["hidden_layers"][:]
newHidden = []
lengthChange = round(severity * 10.)
try:
random.randrange(-lengthChange, lengthChange)
except ValueError:
return
#lengthChange = random.randrange(-lengthChange, lengthChange)
lengthChange = int(random.triangular(-lengthChange, 0, lengthChange))
if lengthChange > 0:
for i in range(lengthChange):
if len(oldHidden)-1 >= i:
newLayer = oldHidden[i]
else:
newLayer = random.randrange( min(oldHidden), max(oldHidden)+1 )
newHidden.append(newLayer)
else: