forked from sacert/Genetic-Hello-World
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
184 lines (151 loc) · 6.15 KB
/
app.js
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
const AVAILABLE_CHARACTERS = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345789!@#$%^&*()_+`~[]{}\|;':\".,/<>?";
const AVAIL_CHAR_LENGTH = AVAILABLE_CHARACTERS.length;
const AVAIL_CHAR_HALF_LENGTH = Math.floor(AVAIL_CHAR_LENGTH/2);
const CHILD_PRINT_MODULO = 1;
// individual genes
class Gene {
constructor(code) {
this.code = code ? code : [];
this.cost = 9999;
}
generateCode(length) {
this.code = Array.from(Array(length)).map(() => { return Math.floor(Math.random() * AVAILABLE_CHARACTERS.length); });
}
// calculate difference between current gene and other gene. higher costs are exponentially higher)
calcDiff(otherGene) {
this.cost = this.code.reduce((a, v, i) => {
const diff = Math.abs(v - otherGene.code[i]);
const cost = diff > AVAIL_CHAR_HALF_LENGTH ? -1 * diff + AVAIL_CHAR_LENGTH : diff;
return a + (cost * cost);
}, 0);
}
// mate current gene with another gene
// pivot may be changed for better results
mate(gene, mutateChance) {
const pivot = Math.round(this.code.length/2) - 1;
// new children will take half of each gene
const child1 = new Gene([ ...this.code.slice(0, pivot), ...gene.code.slice(pivot) ]);
const child2 = new Gene([ ...gene.code.slice(0, pivot), ...this.code.slice(pivot) ]);
child1.mutate(mutateChance);
child2.mutate(mutateChance);
return [ child1, child2 ];
}
// randomly mutate gene by a character depending on the percentage
mutate(percentage) {
if (Math.random() > percentage) {
const operation = Math.random();
const index = Math.floor(Math.random() * this.code.length);
const upDown = Math.random() > 0.5 ? 1 : -1;
switch(true) {
case (operation < 0.33):
var newCode = this.code[index] + upDown;
var fixedCode = newCode > AVAILABLE_CHARACTERS.length - 1 ? 0 : (newCode < 0 ? AVAILABLE_CHARACTERS.length - 1: newCode);
this.code[index] = fixedCode;
break;
case (operation < 0.66):
var copyPos = index + upDown;
var newPos = copyPos < 0 ? this.code.length - 1 : (copyPos > this.code.length - 1 ? 0 : copyPos);
this.code[index] = this.code[newPos];
break;
default:
var newCode = this.code[index] + upDown*2;
var fixedCode = newCode > AVAILABLE_CHARACTERS.length - 1 ? 0 : (newCode < 0 ? AVAILABLE_CHARACTERS.length - 1: newCode);
this.code[index] = fixedCode;
break;
}
}
}
print(targetChromosome) {
return this.code.reduce((a,c,i) => {
return a + '<span class="gene ' + (c === targetChromosome.code[i] ? 'same' : 'diff') + '">' + htmlEscape(AVAILABLE_CHARACTERS[c]) + '</span>';
}, '')
}
}
class Population {
// stores the entire gene population and finds the targetChromosome
constructor() {
this.running = false;
this.targetAchieved = false;
this.genePool = [];
this.generationNumber = 0;
this.targetChromosome = null;
this.bestGeneTemplate = document.getElementById('bestGenesContainer').innerHTML;
}
setPopSize(size) {
this.genePool = Array.from(Array(size));
}
setTarget(target) {
this.target = target;
this.targetChromosome = new Gene(target.split('').map(val => AVAILABLE_CHARACTERS.indexOf(val)));
this.genePool = this.genePool.map(() => {
const gene = new Gene();
gene.generateCode(target.length);
return gene;
});
this.genePool.map(gene => { gene.calcDiff(this.targetChromosome) });
this.sort();
this.targetAchieved = false;
}
sort() {
this.genePool.sort((a, b) => a.cost - b.cost);
}
start() {
document.getElementById('bestGenesContainer').innerHTML = this.bestGeneTemplate;
this.generationNumber = 0;
this.print();
this.generationNumber++;
}
toggleRunning() {
this.running = !this.running;
if (this.running) this.step();
}
step() {
this.generation();
if (this.genePool[0].cost === 0) {
this.running = false;
this.print();
}
if (this.running) window.setTimeout(() => { this.step() }, 0);
}
generation() {
const mutateChance = 0.3;
const childrenToMate = Math.floor(this.genePool.length / 2 + 0.5); //half rounded up
const newChildren = Array.from(Array(childrenToMate)).reduce((a, v, i) => {
const children = this.genePool[0].mate(this.genePool[i+1], mutateChance);
children.map(child => { child.calcDiff(this.targetChromosome) });
return a.concat(children);
}, []);
this.genePool = newChildren.slice(0, this.genePool.length);
this.sort();
if (this.generationNumber % CHILD_PRINT_MODULO === 0) this.print();
this.generationNumber++;
}
print() {
var table = document.getElementById('table')
table.innerHTML = '';
table.innerHTML += ("<h2>Generation: " + this.generationNumber + "</h2>");
table.innerHTML += ("<ul>");
for (var i = 0; i < this.genePool.length; i++) {
table.innerHTML += ("<li>" + this.genePool[i].print(this.targetChromosome) + " (" + this.genePool[i].cost + ")");
}
table.innerHTML += ("</ul>");
var bestGenes = document.getElementById('bestGenes');
var newChild = document.createElement('tr');
newChild.innerHTML = '<td>' + this.generationNumber + '</td><td>' + this.genePool[0].print(this.targetChromosome) + '</td><td>' + this.genePool[0].cost + '</td>';
bestGenes.appendChild(newChild);
};
}
document.addEventListener("DOMContentLoaded", () => {
pop = new Population();
pop.setPopSize(20);
const startString = document.getElementById('target').value;
pop.setTarget(startString);
document.getElementById("start").addEventListener("click", () => { pop.setTarget(pop.target); pop.start(); });
document.getElementById("toggleRunning").addEventListener("click", () => { pop.toggleRunning(); });
document.getElementById("step").addEventListener("click", () => { pop.step(); });
document.getElementById("setTarget").addEventListener("click", () => { pop.setTarget(document.getElementById('target').value); pop.start(); });
pop.start();
});
function htmlEscape(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/\ /g, ' ');
}