- Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathvariable.js
More file actions
Latest commit
236 lines (191 loc) · 7.3 KB
/
Copy pathvariable.js
File metadata and controls
236 lines (191 loc) · 7.3 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
// https://github.com/subprotocol/genetic-js/blob/master/examples/string-solver.html
constGenetic=require('genetic-js');
constgenetic=Genetic.create();
genetic.optimize=Genetic.Optimize.Maximize;
genetic.select1=Genetic.Select1.Tournament2;
genetic.select2=Genetic.Select2.Tournament2;
constutilityManager={
operators: '+-*/',
values: '0123456789x',
isOperator: function(val){
returnthis.operators.includes(val);
},
plus: function(a,b,variables={}){return(variables[a]||a)+(variables[b]||b);},
minus: function(a,b,variables={}){return(variables[a]||a)-(variables[b]||b);},
multiply: function(a,b,variables={}){return(variables[a]||a)*(variables[b]||b);},
divide: function(a,b,variables={}){return(variables[a]||a)/(variables[b]||b);},
compute: function(a,op,b,variables={}){
returnop ? op(a,b,variables) : null;
},
symbolToOperator: function(symbol){
switch(symbol){
case'+': returnthis.plus;
case'-': returnthis.minus;
case'*': returnthis.multiply;
case'/': returnthis.divide;
}
},
subtreePrefix: function(expr,index){
constparts=expr.split('');
letval=parts[index];
constopStack=[];// Start with the node at the index.
constvalStack=[];
letvalCount=0;
leti=index+1;
if(this.isOperator(val)){
opStack.push(val);
}
else{
valStack.push(val);
}
while(opStack.length&&i<parts.length){
val=parts[i];
if(!this.isOperator(val)&&valCount){
val=parseInt(val);// Swap variables with the value 1 for subtree extraction, since the actual value doesn't matter.
val=val||1;
valStack.push(this.compute(valStack.pop(),this.symbolToOperator(opStack.pop()),val));
}
elseif(this.isOperator(val)){
opStack.push(val);
valCount=0;
}
else{
val=parseInt(val);// Swap variables with the value 1 for subtree extraction, since the actual value doesn't matter.
val=val||1;
valStack.push(val);
valCount++;
}
i++;
}
if(Math.abs(index-i)%2===0){
i--;
}
return{expression: expr.substring(index,i),start: index,end: i-1};
},
evaluatePrefix: function(expr,variables={}){
constparts=expr.split('');
conststack=[];
for(letj=expr.length-1;j>=0;j--){
constval=variables[expr[j]]||expr[j];
// Push operated to stack.
if(!this.isOperator(val)){
stack.push(parseInt(val));
}
else{
// Operator found. Pop two elements from the stack.
consta=stack.pop();
constb=stack.pop();
stack.push(this.compute(a,this.symbolToOperator(val),b));
}
}
returnstack[0];
},
replaceAt: function(str,index,replacement){
returnstr.substr(0,index)+replacement+str.substr(index+replacement.length);
},
replaceAtIndex: function(input,index,search,replace){
returninput.slice(0,index)+input.slice(index).replace(search,replace)
}
}
genetic.seed=function(){
constgetNode=(isValue)=>{
letisFunction=isValue ? 0 : Math.floor(Math.random()*2);
returnisFunction ? this.userData.manager.operators[Math.floor(Math.random()*this.userData.manager.operators.length)] : this.userData.manager.values[Math.floor(Math.random()*this.userData.manager.values.length)];
};
consttree=(maxDepth,depth=0)=>{
letresult=[];
constnode=getNode(depth>maxDepth);
result.push(node);
if(this.userData.manager.isOperator(node)){
// This node is a function, so generate two child nodes.
constleft=tree(maxDepth,depth+1);
constright=tree(maxDepth,depth+1);
result=result.concat(left).concat(right);
}
returnresult;
};
returntree(this.userData.maxTreeDepth).join('');
}
genetic.mutate=function(entity){
letresult=entity;
letindex=Math.floor(Math.random()*entity.length);
if(this.userData.manager.isOperator(entity[index])){
// Replace with an operator.
letr=Math.floor(Math.random()*this.userData.manager.operators.length);
result=this.userData.manager.replaceAt(entity,index,this.userData.manager.operators[r]);
}
else{
// Replace with a value.
letr=Math.floor(Math.random()*this.userData.manager.values.length);
result=this.userData.manager.replaceAt(entity,index,this.userData.manager.values[r]);
}
returnresult;
}
genetic.crossover=function(parent1,parent2){
constindex1=Math.floor(Math.random()*parent1.length);
constindex2=Math.floor(Math.random()*parent2.length);
constsubtree1=this.userData.manager.subtreePrefix(parent1,index1).expression;
constsubtree2=this.userData.manager.subtreePrefix(parent2,index2).expression;
// Copy subtree2 to parent1 at index1.
letchild1=this.userData.manager.replaceAtIndex(parent1,index1,subtree1,subtree2);
// Copy subtree1 to parent2 at index2.
letchild2=this.userData.manager.replaceAtIndex(parent2,index2,subtree2,subtree1);
if(child1.length>this.userData.maxLength){
child1=parent1;
}
if(child2.length>this.userData.maxLength){
child2=parent2;
}
return[child1,child2];
}
genetic.fitness=function(entity){
letfitness=0;
letsolution=this.userData.solution;
if(this.userData.testCases){
// For each test case, subtract a penalty from a total of 100 for any deviation in the evaluation from the target value.
returnthis.userData.testCases.map(testCase=>{
consttarget=this.userData.manager.evaluatePrefix(this.userData.solution,testCase);
constactual=this.userData.manager.evaluatePrefix(entity,testCase);
// Give 100 points for each test case, minus any deviation in the evaluated value.
return(100-Math.abs(target-actual));
}).reduce((total,x)=>{returntotal+x;});
}
else{
fitness=this.userData.manager.evaluatePrefix(entity);
returnsolution-Math.abs(solution-fitness);
}
}
genetic.generation=function(pop,generation,stats){
// If using test cases, give 100 points for each test case. Otherwise, just use the value of the evaluation.
letsolution=(this.userData.testCases&&this.userData.testCases.length*100)||this.userData.solution;
returnpop[0].fitness!==solution;
}
genetic.notification=function(pop,generation,stats,isDone){
constvalue=pop[0].entity;
console.log(`Generation ${generation}, Best Fitness ${stats.maximum}, Best genome: ${value}`);
if(isDone){
if(this.userData.testCases){
this.userData.testCases.forEach(testCase=>{
constresult=this.userData.manager.evaluatePrefix(value,testCase);
console.log(testCase);
console.log(`Result: ${result}`);
});
}
else{
console.log(`Result: ${this.userData.manager.evaluatePrefix(value)}`);
}
}
}
genetic.evolve({
iterations: 100000,
size: 100,
crossover: 0.3,
mutation: 0.3,
skip: 50/* frequency for notifications */
},{
solution: '**xxx',// The function for the GA to learn.
testCases: [{x: 1},{x: 3},{x: 5},{x: 9},{x: 10}],// Test cases to learn from.
maxTreeDepth: 25,
maxLength: 100,
manager: utilityManager
})