forked from mtsatsev/NaturalComputingProject
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevolutionaryAlgorithm.js
More file actions
94 lines (82 loc) · 2.69 KB
/
Copy pathevolutionaryAlgorithm.js
File metadata and controls
94 lines (82 loc) · 2.69 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
class EvolutionaryAlgorithm {
constructor(Boids, Foods, mu, nRules = 15, pc = 1.0) {
this.NBoids = Boids.length;
this.mu = mu;
this.pc = pc;
this.Boids = Boids;
this.Foods = Foods;
this.nRules = nRules;
}
fitness(boid) {
// TODO: DOES NOT WORK. NO FUNCITONALITY TO SEE HOW MUCH FOOD WE GOT.
const collectedFood = boid.consumed_food;
return collectedFood
}
mutate(boid, id) {
const muProb = [];
for (let i = 0; i < this.nRules; i++) {
const prob = Math.random();
muProb.push(prob);
}
var deltaWeights = this.generateGaussianDistribution(
this.nRules, 0, 1
);
for (let i = 0; i < deltaWeights.lenght; i++) {
if (muProb[i] > this.mu) {
deltaWeights[i] = 0.0;
}
}
var weights = boid.rw;
const updatedWeights = weights.map((weight, idx) => weight + deltaWeights[idx])
var x = floor(random(0, 800));
var y = floor(random(0, 800));
return new Boid(id, x, y, updatedWeights);
/*
Object.keys(boid).forEach((attrName, idx) => {
if (attrName.startsWith("wr")) {
boid[attrName] = updatedWeights[idx];
}
});*/
}
select_parent(K = 10) {
const parents = [];
var bestFitness = -1;
var bestIdx = -1;
for (let i = 0; i < K; i++) {
const parent_candidate = this.Boids[Math.floor(Math.random(0, this.NBoids))];
parents.push(parent_candidate);
var parentFitness = this.fitness(parent_candidate);
if (bestFitness < parentFitness) {
bestFitness = parentFitness;
bestIdx = i;
}
}
const choice = parents[bestIdx];
return choice;
}
writeResults(G) {
const weights = this.Boids.reduce((dict, boid) => {
dict["BOID: " + boid.id.toString()] = [boid.rw, this.fitness(boid)];
return dict;
}, {});
saveJSON(weights, "result/"+G.toString()+'results.json');
}
Evolution(K) {
const newGeneration = [];
var i = 0;
for (let i = 0; i < this.NBoids; i++) {
var parent = this.select_parent(K)
var offspring = this.mutate(parent, i)
newGeneration.push(offspring)
}
return newGeneration;
}
generateGaussianDistribution(N, mean, standardDeviation) {
const numbers = [];
for (let i = 0; i < N; i++) {
const number = randomGaussian(mean, standardDeviation);
numbers.push(number);
}
return numbers
}
}