-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Population.js
101 lines (83 loc) · 2.71 KB
/
Population.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
const Schedule = require('./Schedule');
function mapNum (n, in_min, in_max, out_min, out_max) {
return (n - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}
module.exports = function Population(classCodes, mutationRate, num) {
this.population = [];
this.matingPool = [];
this.generations = 0;
this.finished = false;
this.mutationRate = mutationRate;
this.perfectScore = 1;
for(var i=0; i<num; i++) {
this.population[i] = new Schedule(classCodes, true);
}
// Calculate fitness of each schedule
this.calcFitness = function() {
for(var i=0; i<this.population.length;i++) {
this.population[i].calcFitness();
}
}
this.calcFitness();
this.naturalSelection = function() {
this.matingPool = [];
var maxFitness = 0;
for(var i=0; i<this.population.length;i++) {
if(this.population[i].fitness > maxFitness) {
maxFitness = this.population[i].fitness;
}
}
for(var i=0; i<this.population.length;i++) {
var fitness = mapNum(this.population[i].fitness,0,maxFitness,0,1);
var n = Math.floor(fitness*100);
for(var j=0;j<n;j++) {
this.matingPool.push(i);
}
}
}
this.generate = function() {
var newPop = [];
for(var i=0; i<this.population.length;i++) {
var a = getRndInteger(0,this.matingPool.length);
var b = getRndInteger(0, this.matingPool.length);
var partnerA = this.population[this.matingPool[a]];
var partnerB = this.population[this.matingPool[b]];
var child = partnerA.crossover(partnerB);
child.mutate(this.mutationRate);
newPop.push(child);
}
this.population = newPop;
this.generations++;
}
this.getBest = function() {
return this.best;
}
this.evaluate = function() {
var record = 0.0;
var index = 0;
for(var i=0; i < this.population.length; i++) {
if(this.population[i].fitness > record) {
index = i;
record = this.population[i].fitness;
}
}
this.best = this.population[index];
if(record === this.perfectScore) {
this.finished = true;
}
}
this.isFinished = function() {
return this.finished;
}
this.getGenerations = function() {
return this.generations;
}
this.print = function() {
for(var i=0; i<this.population.length;i++) {
this.population[i].print();
}
}
}