-
Notifications
You must be signed in to change notification settings - Fork 1
/
neatevolve.lua
1482 lines (1273 loc) · 42 KB
/
neatevolve.lua
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
--[[ MarI/O by SethBling, Heavily extended by Dwood15
-- Intended for use with the BizHawk emulator and Super Mario World
-- Special shoutout to henke37, who gave the inspiration for how to add extra inputs
--
-- TODO: remove network visualization, find way to represent it better.
-- TODO: refactorization, optimization, make the script more consistent across the board, as well as more readable
]]--
--local includeFile = require "smw-bizhawk"
require("smw-bizhawk")
--shamelessly stolen from smw-bizhawk on github
local mainmemory = mainmemory
-- Compatibility
local u8 = mainmemory.read_u8
local s8 = mainmemory.read_s8
local u16 = mainmemory.read_u16_le
local s16 = mainmemory.read_s16_le
local u24 = mainmemory.read_u24_le
local s24 = mainmemory.read_s24_le
local WRAM = WRAM
local SMW = SMW
function getCurrentRoom()
return bit.lshift(u8(WRAM.room_index), 16) + bit.lshift(u8(WRAM.room_index + 1), 8) + u8(WRAM.room_index + 2)
end
--I only care about screens to do timeout math. I don't actually care enough to index ALL of the room ID's for this script
-- default zero
local function getLevelStats()
return u8(WRAM.level_index), u8(WRAM.game_mode), u8(WRAM.end_level_timer), getCurrentRoom()
end
local Current_Level_Index, game_mode, End_Level_Timer, CurrentRoomID = getLevelStats()
--read_screens is in smw-bizhawk
local give_fitBonus = false
local levelType, currLevelScreenCount, hScreenCurrent, hScreenCurrCount, vScreenCurrent, vScreenCurrCount = read_screens()
function getPlayerStats()
return s16(WRAM.x), s16(WRAM.y), u24(WRAM.mario_score), u8(WRAM.game_over_time_out_flag), u8(WRAM.exit_level_byte), u8(WRAM.mario_lives)
end
--local current_level = level.new({1, 2, 3}) -- how to declare new level objects
local Filename = {"DP1.State"} -- This way we can train the program on levels more efficiently.
local ButtonNames = {
"A",
"B",
"X",
"Y",
"Up",
"Down",
"Left",
"Right"
}
function initializeConstants()
fNameIndex = 1
STALEXWEIGHT = .39 --
STALEYWEIGHT = .33
STALEDEATHWEIGHT = .1
STALESCOREWEIGHT = .18
STALEGENOMERATIO = .40 -- staleness < (#species.genomes * STALEGENOMERATIO)
MAXEVALS = 2 -- The number of times which we
CURRENTRUN = 0
GENERATIONSPERTEST = 100
BEGINDECAYPERCENT = 50 -- 50% - The percentage of generations we allow without one completing the level before we begin penalizing for not making progress.
GENERATIONALDECAYRATE = .25 -- decayrate * population = decayrate. The per-generational number which we reduce the number of generations left till a full restart, so essentially
-- if(pool.currGeneration/generationspertest) >= begindecaypercent then GENERATIONSPERTEST = GENERATIONSPERTEST - Gen
--NOT IMPLEMENTED YET
MINPOPULATION = 30
MINDESIREDGENOMES = 2 -- not implemented
DELTADISJOINT = .65
DELTAWEIGHTS = 0.4
DELTATHRESHOLD = 1.0
STALESPECIES = 20
MUTATECONNECTIONSCHANCE = 0.4
PERTURBCHANCE = 0.90
CROSSOVERCHANCE = 0.75
LINKMUTATIONCHANCE = 3.0
NODEMUTATIONCHANCE = 0.65
BIASMUTATIONCHANCE = 0.45
STEPSIZE = 0.23
DISABLEMUTATIONCHANCE = .40
ENABLEMUTATIONCHANCE = .60
TIMEOUTCONST = 900
STANDSTILLPENALTY = .60
RANDOMCULLCHANCE = .01 --TODO: this and extinction
MAXNODES = 255000
end
function getPositions() --get mario location and score, along with screen values
local last_level_exit_byte = level_exit_byte
marioX, marioY, marioScore, ai_failed_flag, level_exit_byte, mario_lives = getPlayerStats()
if level_exit_byte ~= last_level_exit_byte and level_exit_byte == 128 then died = true end
local layer1x = s16(0x1A)
local layer1y = s16(0x1C)
screenX = marioX-layer1x
screenY = marioY-layer1y
local tmpScrnX = hScreenCurrent
local tmpScrnY = vScreenCurrent
levelType, currLevelScreenCount, hScreenCurrent, hScreenCurrCount, vScreenCurrent, vScreenCurrCount = read_screens()
--Only bother updating if it's not the same
if hScreenCurrent ~= tmpScrnX then
if lasthScreenCurrent ~= 0 then
give_fitBonus = true
end
lasthScreenCurrent = tmpScrnX
end
if vScreenCurrent ~= tmpScrnY then
if lastvScreenCurrent ~= 0 then
give_fitBonus = true
end
lastvScreenCurrent = tmpScrnY
end
Current_Level_Index, game_mode, End_Level_Timer, CurrentRoomID = getLevelStats()
end
function getTile(dx, dy)
x = math.floor((marioX+dx+8)/16)
y = math.floor((marioY+dy)/16)
return memory.readbyte(0x1C800 + math.floor(x/0x10)*0x1B0 + y*0x10 + x%0x10)
end
function getSprites()
local sprites = {}
for slot= 0, SMW.sprite_max - 1 do -- May as well search the whole bit instead of doing the first 12 or so sprites.
-- This way, mario will actually know where he is!
local status = memory.readbyte(WRAM.sprite_status+slot)
if status ~= 0 then -- we only care about objects we can interact with.....
spritex = memory.readbyte(0xE4+slot) + memory.readbyte(WRAM.sprite_x_high+slot)*256 --5344
spritey = memory.readbyte(0xD8+slot) + memory.readbyte(WRAM.sprite_y_high+slot)*256
spriteNo = u8(WRAM.sprite_number + slot)
sprites[#sprites+1] = {["ID"]= spriteNo, ["x"]=spritex, ["y"]=spritey}
end
end
return sprites
end
function getExtendedSprites()
local extended = {}
for slot=0, 11 do -- the list of extended sprites here...
local number = memory.readbyte(0x170B+slot)
if number > 1 and number ~= 15 then
spritex = memory.readbyte(0x171F+slot) + memory.readbyte(0x1733+slot)*256
spritey = memory.readbyte(0x1715+slot) + memory.readbyte(0x1729+slot)*256
extended[#extended+1] = {["ID"]= number, ["x"]=spritex, ["y"]=spritey}
end
end
return extended
end
function idToBinaryArray(spriteID, inputArray)
powers = {256, 128, 64, 32, 16, 8, 4, 2}
if spriteID == nil then spriteID = 0xFF end
for i = 1, #powers do
if spriteID > powers[i] then
spriteID = spriteID - powers[i]
inputArray[i] = -1
else
inputArray[i] = 1
end
end
return inputArray
end
--Yes, this code is repetitive. If there is a faster, more efficient way of doing this, please message dwood15 using reddit or tasvideos.com forums.
local function directionalGet(dx, dy)
local extInd = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
if distx < 0 then
extInd[1] = 1
else if distx == 0 then
extInd[2] = 1
else if distx > 0 then
extInd[3] = 1
end
end
end
if disty < 0 then
extInd[4] = 1
else if disty == 0 then
extInd[5] = 1
else if disty > 0 then
extInd[6] = 1
end
end
end
distx = math.abs(distx)
disty = math.abs(disty)
if distx < 7 then
extInd[7] = 1
if distx < 6 then
extInd[8] = 1
if distx < 5 then
extInd[9] = 1
if distx < 4 then
extInd[10] = 1
if distx < 3 then
extInd[11] = 1
if distx < 2 then
extInd[12] = 1
if distx < 1 then
extInd[13] = 1
end
end
end
end
end
end
end
if disty < 7 then
extInd[14] = 1
if disty < 6 then
extInd[15] = 1
if disty < 5 then
extInd[16] = 1
if disty < 4 then
extInd[17] = 1
if disty < 3 then
extInd[18] = 1
if disty < 2 then
extInd[19] = 1
if disty < 1 then
extInd[20] = 1
end
end
end
end
end
end
end
return extInd
end
function getInputs()
getPositions()
sprites = getSprites()
extended = getExtendedSprites()
local inputs = {}
-- 6 * 16 = 96 so we search 96 up, 96 down, 96 left, and 96 to the right.
-- tile is 16 * 6 bytes
for dy=-BOXRADIUS*16, BOXRADIUS*16,16 do
-- -96 to 96
for dx= -BOXRADIUS*16, BOXRADIUS*16,16 do
--we start from the bottom left, and seek from there to the right.
inputs[#inputs + 1] = 0 --we add the input
local x = math.floor((marioX+dx+8)/16)
local y = math.floor((marioY+dy)/16)
local ind = { -1, -1, -1, -1, -1, -1, -1, -1 }
local extInd = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
tile = getTile(dx, dy) --get the point at that position on the screen?
if tilesSeen["L" .. Current_Level_Index .. "X" .. x .. "Y" .. y] == nil and marioY+dy < 0x1B0 then
tilesSeen["L" .. Current_Level_Index .. "X" .. x .. "Y" .. y] = 1
totalSeen = totalSeen + 1;
if tile == 1 then
totalSeen = totalSeen + 5;
end
timeout = TIMEOUTCONST
end
if tile == 1 and marioY+dy < 0x1B0 then
inputs[#inputs] = 1 --firing neuron
end
--So mario just knows when something is nearby, not what type it is. Based on proximity and level memorization entirely.
for i = 1, #sprites do
distx = sprites[i]["x"] - (marioX+dx)
disty = sprites[i]["y"] - (marioY+dy)
if math.abs(distx) <= 8 and math.abs(disty) <= 8 then
inputs[#inputs] = -1 --the sprite is nearby
extInd = directionalGet(distx, disty)
--fire a neuron based on the TYPE of sprite around...
ind = idToBinaryArray(sprites[i]["ID"], ind)
end
end
for i = 1,#extended do
distx = extended[i]["x"] - (marioX+dx)
disty = extended[i]["y"] - (marioY+dy)
if math.abs(distx) < 8 and math.abs(disty) < 8 then
inputs[#inputs] = -1 -- the sprite is nearby/input is firing, i don't think mario has any way to tell the type of sprite???
ind = {1, 1, 1, 1, 1, 1, -1, -1}
extInd = directionalGet(distx, disty)
end
end
for i = 1, #ind do
inputs[#inputs + 1] = ind[i]
end
for i = 1, #extInd do
inputs[#inputs + 1] = extInd[i]
end
end
end
player_blocked_status = u8(WRAM.player_blocked_status)
blocked_status = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
for i = 0, 7, 1 do
if bit.check(player_blocked_status, i) then
inputs[#inputs + 1] = 1
else
inputs[#inputs + 1] = -1
end
end
return inputs
end
function sigmoid(x)
return 2/(1+math.exp(-4.9*x))-1
end
function newInnovation()
pool.innovation = pool.innovation + 1
return pool.innovation
end
function newPool()
local pool = {}
pool.species = {}
pool.generation = 0
pool.innovation = Outputs
pool.currentSpecies = 1
pool.currentGenome = 1
pool.currentFrame = 0
pool.maxFitness = 0
return pool
end
function newSpecies()
local species = {}
species.topFitness = 0
species.staleness = 0.001
species.genomes = {}
species.averageFitness = 0
species.distancefromMean = 0
return species
end
function newGenome()
local genome = {}
genome.genes = {}
genome.fitness = 0
genome.adjustedFitness = 0
genome.network = {}
genome.maxneuron = 0
genome.globalRank = 0
genome.mutationRates = {}
genome.mutationRates.connections = MUTATECONNECTIONSCHANCE
genome.mutationRates.link = LINKMUTATIONCHANCE
genome.mutationRates.bias = BIASMUTATIONCHANCE
genome.mutationRates.node = NODEMUTATIONCHANCE
genome.mutationRates.enable = ENABLEMUTATIONCHANCE
genome.mutationRates.disable = DISABLEMUTATIONCHANCE
genome.mutationRates.step = STEPSIZE
genome.FinalStats = {}
genome.FinalStats.X = 0
genome.FinalStats.Y = 0
genome.FinalStats.Score = 0
genome.FinalStats.Died = false
genome.FinalStats.game_mode = 0
return genome
end
function copyGenome(genome)
local genome2 = newGenome()
for g=1,#genome.genes do
table.insert(genome2.genes, copyGene(genome.genes[g]))
end
genome2.maxneuron = genome.maxneuron
genome2.mutationRates.connections = genome.mutationRates.connections
genome2.mutationRates.link = genome.mutationRates.link
genome2.mutationRates.bias = genome.mutationRates.bias
genome2.mutationRates.node = genome.mutationRates.node
genome2.mutationRates.enable = genome.mutationRates.enable
genome2.mutationRates.disable = genome.mutationRates.disable
genome2.FinalStats = {}
genome2.FinalStats.X = 0
genome2.FinalStats.Y = 0
genome2.FinalStats.Score = 0
genome2.FinalStats.Died = false
genome2.FinalStats.game_mode = 0
return genome2
end
function basicGenome()
local genome = newGenome()
local innovation = 1
genome.maxneuron = Inputs
mutate(genome)
return genome
end
function newGene()
local gene = {}
gene.into = 0
gene.out = 0
gene.weight = 0.0
gene.enabled = true
gene.innovation = 0
return gene
end
function copyGene(gene)
local gene2 = newGene()
gene2.into = gene.into
gene2.out = gene.out
gene2.weight = gene.weight
gene2.enabled = gene.enabled
gene2.innovation = gene.innovation
return gene2
end
function newNeuron()
local neuron = {}
neuron.incoming = {}
neuron.value = 0.0
return neuron
end
function generateNetwork(genome)
local network = {}
network.neurons = {}
for i = 1, Inputs do
network.neurons[i] = newNeuron()
end
for o=1,Outputs do
network.neurons[MAXNODES+o] = newNeuron()
end
table.sort(genome.genes, function (a,b)
return (a.out < b.out)
end)
for i=1,#genome.genes do
local gene = genome.genes[i]
if gene.enabled then
if network.neurons[gene.out] == nil then
network.neurons[gene.out] = newNeuron()
end
local neuron = network.neurons[gene.out]
table.insert(neuron.incoming, gene)
if network.neurons[gene.into] == nil then
network.neurons[gene.into] = newNeuron()
end
end
end
genome.network = network
end
function evaluateNetwork(network, inputs)
--table.insert(inputs, 1)
if #inputs ~= Inputs then
console.writeline("Incorrect # of inputs, we have: " .. #inputs .." Expected: " .. Inputs)
return {}
end
for i=1,Inputs do
network.neurons[i].value = inputs[i]
end
for i = 1, MAXEVALS do
for _,neuron in pairs(network.neurons) do
if #neuron.incoming > 0 then
local sum = 0
for j = 1,#neuron.incoming do
local incoming = neuron.incoming[j]
local other = network.neurons[incoming.into]
sum = sum + incoming.weight * other.value
end
neuron.value = sigmoid(sum)
end
end
end
local outputs = {}
for o=1,Outputs do
local button = "P1 " .. ButtonNames[o]
if network.neurons[MAXNODES+o].value > 0 then
outputs[button] = true
else
outputs[button] = false
end
end
return outputs
end
function crossover(g1, g2)
-- Make sure g1 is the higher fitness genome
if g2.fitness > g1.fitness then
tempg = g1
g1 = g2
g2 = tempg
end --swap the genes
local child = newGenome()
local innovations2 = {}
for i=1,#g2.genes do
local gene = g2.genes[i]
innovations2[gene.innovation] = gene
end
for i=1,#g1.genes do
local gene1 = g1.genes[i]
local gene2 = innovations2[gene1.innovation]
if gene2 ~= nil and math.random(2) == 1 and gene2.enabled then
table.insert(child.genes, copyGene(gene2))
else
table.insert(child.genes, copyGene(gene1))
end
end
child.maxneuron = math.max(g1.maxneuron,g2.maxneuron)
for mutation,rate in pairs(g1.mutationRates) do
child.mutationRates[mutation] = rate
end
return child
end
function randomNeuron(genes, nonInput)
local neurons = {}
if not nonInput then
for i=1, Inputs do
neurons[i] = true
end
end
for o=1, Outputs do
neurons[MAXNODES+o] = true
end
for i=1,#genes do
if (not nonInput) or genes[i].into > Inputs then
neurons[genes[i].into] = true
end
if (not nonInput) or genes[i].out > Inputs then
neurons[genes[i].out] = true
end
end
local count = 0
for _,_ in pairs(neurons) do
count = count + 1
end
local n = math.random(1, count)
for k,v in pairs(neurons) do
n = n-1
if n == 0 then
return k
end
end
return 0
end
function containsLink(genes, link)
for i=1,#genes do
local gene = genes[i]
if gene.into == link.into and gene.out == link.out then
return true
end
end
end
function pointMutate(genome)
local step = genome.mutationRates.step
for i=1,#genome.genes do
local gene = genome.genes[i]
if math.random() < PERTURBCHANCE then
gene.weight = gene.weight + (math.random() * STEPSIZE * 2) - STEPSIZE
else
gene.weight = (math.random()*4)-2
end
end
end
function linkMutate(genome, forceBias)
local neuron1 = randomNeuron(genome.genes, false)
local neuron2 = randomNeuron(genome.genes, true)
local newLink = newGene()
if neuron1 <= Inputs and neuron2 <= Inputs then
--Both input nodes
return
end
if neuron2 <= Inputs then
-- Swap output and input
local temp = neuron1
neuron1 = neuron2
neuron2 = temp
end
newLink.into = neuron1
newLink.out = neuron2
if forceBias then
newLink.into = Inputs
end
if containsLink(genome.genes, newLink) then
return
end
newLink.innovation = newInnovation()
newLink.weight = math.random()*4-2
table.insert(genome.genes, newLink)
end
function nodeMutate(genome)
if #genome.genes == 0 then
return
end
genome.maxneuron = genome.maxneuron + 1
local gene = genome.genes[math.random(1,#genome.genes)]
if not gene.enabled then
return
end
gene.enabled = false
local gene1 = copyGene(gene)
gene1.out = genome.maxneuron
gene1.weight = 1.0
gene1.innovation = newInnovation()
gene1.enabled = true
table.insert(genome.genes, gene1)
local gene2 = copyGene(gene)
gene2.into = genome.maxneuron
gene2.innovation = newInnovation()
gene2.enabled = true
table.insert(genome.genes, gene2)
end
function enableDisableMutate(genome, enable)
local candidates = {}
for _,gene in pairs(genome.genes) do
if gene.enabled == not enable then
table.insert(candidates, gene)
end
end
if #candidates == 0 then
return
end
local gene = candidates[math.random(1,#candidates)]
gene.enabled = not gene.enabled
end
function mutate(genome)
for mutation,rate in pairs(genome.mutationRates) do
if math.random(1,2) == 1 then
genome.mutationRates[mutation] = 0.95*rate
else
genome.mutationRates[mutation] = 1.05263*rate
end
end
if math.random() < genome.mutationRates.connections then
pointMutate(genome)
end
local p = genome.mutationRates.link
while p > 0 do
if math.random() < p then
linkMutate(genome, false)
end
p = p - .5
end
p = genome.mutationRates.bias
while p > 0 do
if math.random() < p then
linkMutate(genome, true)
end
p = p - .5
end
p = genome.mutationRates.node
while p > 0 do
if math.random() < p then
nodeMutate(genome)
end
p = p - .5
end
end
function disjoint(genes1, genes2)
local i1 = {}
for i = 1,#genes1 do
local gene = genes1[i]
i1[gene.innovation] = true
end
local i2 = {}
for i = 1,#genes2 do
local gene = genes2[i]
i2[gene.innovation] = true
end
local disjointGenes = 0
for i = 1,#genes1 do
local gene = genes1[i]
if not i2[gene.innovation] then
disjointGenes = disjointGenes+1
end
end
for i = 1,#genes2 do
local gene = genes2[i]
if not i1[gene.innovation] then
disjointGenes = disjointGenes+1
end
end
local n = math.max(#genes1, #genes2)
return disjointGenes / n
end
--The range for gene.weight is [-2, 2]
function weights(genes1, genes2)
local i2 = {}
for i = 1,#genes2 do
local gene = genes2[i]
i2[gene.innovation] = gene
end
local sum = 0
local coincident = 0
for i = 1,#genes1 do
local gene = genes1[i]
if i2[gene.innovation] ~= nil then
local gene2 = i2[gene.innovation]
sum = sum + math.abs(gene.weight - gene2.weight) -- The largest value for sum will be 4, the smallest is zero.
coincident = coincident + 1
end
end
return sum / coincident
end
function sameSpecies(genome1, genome2)
local dd = DELTADISJOINT*disjoint(genome1.genes, genome2.genes) -- The largest value will be 1, the smallest will be 0.
local dw = DELTAWEIGHTS*weights(genome1.genes, genome2.genes) -- the smallest value is 0, the largest value is 4 * #genes in genome
return dd + dw < DELTATHRESHOLD
end
function rankGlobally()
local global = {}
for s = 1,#pool.species do
local species = pool.species[s]
for g = 1,#species.genomes do
table.insert(global, species.genomes[g])
end
end
table.sort(global, function (a,b)
return (a.fitness < b.fitness)
end)
for g=1,#global do
global[g].globalRank = g
end
end
function calculateAverageFitness(species)
local total = 0
for g=1,#species.genomes do
local genome = species.genomes[g]
total = total + genome.globalRank
end
--console.writeline("Species avgFitness: " .. total .. "Species genomes: " .. #species.genomes)
species.averageFitness = total / #species.genomes
end
function totalAverageFitness()
local total = 0
for s = 1,#pool.species do
local species = pool.species[s]
total = total + species.averageFitness
end
return total
end
function removeStaleSpecies() --this is where the novelty f() is important
local survived = {}
console.writeline("Removing stale, there are: " .. #pool.species .. " species")
for s = 1, #pool.species do
local species = pool.species[s]
console.writeline("genome count for specie #" .. s .. ": " .. #species.genomes )
local stale = 0.0
for g = 1, #species.genomes do
for gtop = #species.genomes, 1 do
if gtop ~= g then
if species.genomes[g].FinalStats.X == species[gtop].FinalStats.X then stale = stale + STALEXWEIGHT end --highest weight
if species.genomes[g].FinalStats.Y == species[gtop].FinalStats.Y then stale = stale + STALEYWEIGHT end --2nd
if species.genomes[g].FinalStats.Score == species[gtop].FinalStats.Score then stale = stale + STALESCOREWEIGHT end --3rd
if species.genomes[g].FinalStats.Died and species[gtop].FinalStats.Died then stale = stale + STALEDEATHWEIGHT end -- 4th
end
end
end
console.writeline("Staleness: " .. stale .. " for species: " .. s)
--I need to revisit this statement. I like where it's going, but it needs to be double checked.
if stale > (#species.genomes * STALEGENOMERATIO ) then stale = math.ceil(stale) end
--console.writeline("reset stale species for species: " .. s .. " of gen: " .. pool.generation .. " stalenes: " .. staleness)
if species.genomes[1].fitness > pool.maxFitness then
species.topFitness = species.genomes[1].fitness
else species.staleness = species.staleness + stale end
console.writeline("species.staleness: " .. species.staleness)
if species.staleness < STALESPECIES then
table.insert(survived, species)
end
end
pool.species = survived
console.writeline(" " .. #pool.species .. " spec survived the stale calculations.")
end
function cullSpecies(cutToOne)
for s = 1, #pool.species do
local species = pool.species[s]
-- table.sort(species.genomes, function (a,b)
-- return (a.fitness > b.fitness)
-- end)
local remaining = math.ceil(math.random(1, #species.genomes))
if remaining <= 0 then remaining = 2 end
if remaining > #species.genomes then remaining = #species.genomes end
if cutToOne then remaining = 1 end --Some randomness to keep things spicy.
while #species.genomes > remaining do table.remove(species.genomes) end
end
end
function breedChild(species)
local child = {}
if math.random() < CROSSOVERCHANCE then
g1 = species.genomes[math.random(1, #species.genomes)]
g2 = species.genomes[math.random(1, #species.genomes)]
child = crossover(g1, g2)
else
g = species.genomes[math.random(1, #species.genomes)]
child = copyGenome(g)
end
mutate(child)
return child
end
function removeWeakSpecies()
local survived = {}
local totalAvgFitness = totalAverageFitness()
for s = 1,#pool.species do
local species = pool.species[s]
local result = math.floor((species.averageFitness / totalAvgFitness) * MINPOPULATION)
if result >= 1 then
table.insert(survived, species)
end
end
pool.species = survived
end
function addToSpecies(child)
local foundSpecies = false
for s=1, #pool.species do
local species = pool.species[s]
if not foundSpecies and sameSpecies(child, species.genomes[1]) then
table.insert(species.genomes, child)
foundSpecies = true
end
end
if not foundSpecies then
local childSpecies = newSpecies()
table.insert(childSpecies.genomes, child)
table.insert(pool.species, childSpecies)
end
end
function newGeneration()
console.writeline("New generation")
--Sort the genomes by fitness.
for s = 1, #pool.species do table.sort(pool.species[s].genomes, function(a, b) return (a.fitness > b.fitness) end) end
rankGlobally()
local totalAvgFitness = totalAverageFitness()
removeStaleSpecies()
cullSpecies(false) -- Cull the bottom half of each species
for s = 1, #pool.species do
local species = pool.species[s]
calculateAverageFitness(species)
end
console.write("\nRemoving weak species, there are: " .. #pool.species .. " but ")
removeWeakSpecies()
console.write(#pool.species .. " survived\n")
totalAvgFitness = totalAverageFitness()
local children = {}
for s = 1,#pool.species do
local species = pool.species[s]
local breed = math.floor(species.averageFitness / totalAvgFitness * MINPOPULATION) - 1
for i=1, breed do
table.insert(children, breedChild(species))
end
end
cullSpecies(true) -- Cull all but the top member of each species
if #pool.species == 0 then
pool = newPool()
console.writeline("We killed all species, created new pool")
end
while #children + #pool.species < MINPOPULATION do
local species = pool.species[math.random(1, (#pool.species))]
table.insert(children, breedChild(species))
end
for c=1,#children do
local child = children[c]
addToSpecies(child)
end
pool.generation = pool.generation + 1
writeNeuralNetworkFile("AIData\\Gen" .. pool.generation .. "backup." .. forms.gettext(saveLoadFile))
end
function initializePool()
pool = newPool()
for i=1, MINPOPULATION do
basic = basicGenome()
addToSpecies(basic)
end
initializeRun()
end
function clearJoypad()
controller = {}
for b = 1,#ButtonNames do
controller["P1 " .. ButtonNames[b]] = false
end
joypad.set(controller)
end
function evaluateCurrent(updateInputs)
local species = pool.species[pool.currentSpecies]
local genome = species.genomes[pool.currentGenome]
if updateInputs then inputs = getInputs() end
controller = evaluateNetwork(genome.network, inputs)
if controller["P1 Left"] and controller["P1 Right"] then
controller["P1 Left"] = false
controller["P1 Right"] = false