Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 58 additions & 60 deletions js/genetic-0.1.14.js → js/genetic-0.1.15.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ window.Genetic = require('./genetic');
},{"./genetic":2}],2:[function(require,module,exports){

var Genetic = Genetic || (function(){

'use strict';

// facilitates communcation between web workers
var Serialization = {
"stringify": function (obj) {
Expand All @@ -25,19 +25,19 @@ var Genetic = Genetic || (function(){
});
}
};

var Clone = function(obj) {
if (obj == null || typeof obj != "object")
return obj;

return JSON.parse(JSON.stringify(obj));
};

var Optimize = {
"Maximize": function (a, b) { return a >= b; }
, "Minimize": function (a, b) { return a < b; }
};

var Select1 = {
"Tournament2": function(pop) {
var n = pop.length;
Expand All @@ -64,7 +64,7 @@ var Genetic = Genetic || (function(){
return pop[(this.internalGenState["seq"]++)%pop.length].entity;
}
};

var Select2 = {
"Tournament2": function(pop) {
return [Select1.Tournament2.call(this, pop), Select1.Tournament2.call(this, pop)];
Expand All @@ -80,9 +80,9 @@ var Genetic = Genetic || (function(){
return [Select1.Fittest.call(this, pop), Select1.Random.call(this, pop)];
}
};

function Genetic() {

// population
this.fitness = null;
this.seed = null;
Expand All @@ -93,7 +93,7 @@ var Genetic = Genetic || (function(){
this.optimize = null;
this.generation = null;
this.notification = null;

this.configuration = {
"size": 250
, "crossover": 0.9
Expand All @@ -104,33 +104,33 @@ var Genetic = Genetic || (function(){
, "webWorkers": true
, "skip": 0
};

this.userData = {};
this.internalGenState = {};

this.entities = [];

this.usingWebWorker = false;

this.start = function() {

var i;
var self = this;

function mutateOrNot(entity) {
// applies mutation based on mutation probability
return Math.random() <= self.configuration.mutation && self.mutate ? self.mutate(Clone(entity)) : entity;
}

// seed the population
for (i=0;i<this.configuration.size;++i) {
this.entities.push(Clone(this.seed()));
}

for (i=0;i<this.configuration.iterations;++i) {
// reset for each generation
this.internalGenState = {};

// score and sort
var pop = this.entities
.map(function (entity) {
Expand All @@ -139,13 +139,13 @@ var Genetic = Genetic || (function(){
.sort(function (a, b) {
return self.optimize(a.fitness, b.fitness) ? -1 : 1;
});

// generation notification
var mean = pop.reduce(function (a, b) { return a + b.fitness; }, 0)/pop.length;
var stdev = Math.sqrt(pop
.map(function (a) { return (a.fitness - mean) * (a.fitness - mean); })
.reduce(function (a, b) { return a+b; }, 0)/pop.length);

var stats = {
"maximum": pop[0].fitness
, "minimum": pop[pop.length-1].fitness
Expand All @@ -155,23 +155,23 @@ var Genetic = Genetic || (function(){

var r = this.generation ? this.generation(pop, i, stats) : true;
var isFinished = (typeof r != "undefined" && !r) || (i == this.configuration.iterations-1);

if (
this.notification
&& (isFinished || this.configuration["skip"] == 0 || i%this.configuration["skip"] == 0)
) {
this.sendNotification(pop.slice(0, this.maxResults), i, stats, isFinished);
}

if (isFinished)
break;

// crossover and mutate
var newPop = [];

if (this.configuration.fittestAlwaysSurvives) // lets the best solution fall through
newPop.push(pop[0].entity);

while (newPop.length < self.configuration.size) {
if (
this.crossover // if there is a crossover function
Expand All @@ -185,69 +185,71 @@ var Genetic = Genetic || (function(){
newPop.push(mutateOrNot(self.select1(pop)));
}
}

this.entities = newPop;
}
}

this.sendNotification = function(pop, generation, stats, isFinished) {
var self = this;

var response = {
"pop": pop.map(Serialization.stringify)
, "generation": generation
, "stats": stats
, "isFinished": isFinished
};


if (this.usingWebWorker) {
postMessage(response);
} else {
// self declared outside of scope
self.notification(response.pop.map(Serialization.parse), response.generation, response.stats, response.isFinished);
}

};
}

Genetic.prototype.evolve = function(config, userData) {

var k;
for (k in config) {
this.configuration[k] = config[k];
}

for (k in userData) {
this.userData[k] = userData[k];
}

// determine if we can use webworkers
this.usingWebWorker = this.configuration.webWorkers
&& typeof Blob != "undefined"
&& typeof Worker != "undefined"
&& typeof window.URL != "undefined"
&& typeof window.URL.createObjectURL != "undefined";

function addslashes(str) {
return str.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

// bootstrap webworker script
var blobScript = "'use strict'\n";
blobScript += "var Serialization = {'stringify': " + Serialization.stringify.toString() + ", 'parse': " + Serialization.parse.toString() + "};\n";
blobScript += "var Clone = " + Clone.toString() + ";\n";

// make available in webworker
blobScript += "var Optimize = Serialization.parse(\"" + addslashes(Serialization.stringify(Optimize)) + "\");\n";
blobScript += "var Select1 = Serialization.parse(\"" + addslashes(Serialization.stringify(Select1)) + "\");\n";
blobScript += "var Select2 = Serialization.parse(\"" + addslashes(Serialization.stringify(Select2)) + "\");\n";

// materialize our ga instance in the worker
blobScript += "var genetic = Serialization.parse(\"" + addslashes(Serialization.stringify(this)) + "\");\n";
blobScript += "onmessage = function(e) { genetic.start(); }\n";


var self = this;

if (this.usingWebWorker) {
// bootstrap webworker script
var blobScript = "'use strict'\n";
blobScript += "var Serialization = {'stringify': " + Serialization.stringify.toString() + ", 'parse': " + Serialization.parse.toString() + "};\n";
blobScript += "var Clone = " + Clone.toString() + ";\n";

// make available in webworker
blobScript += "var Optimize = Serialization.parse(\"" + addslashes(Serialization.stringify(Optimize)) + "\");\n";
blobScript += "var Select1 = Serialization.parse(\"" + addslashes(Serialization.stringify(Select1)) + "\");\n";
blobScript += "var Select2 = Serialization.parse(\"" + addslashes(Serialization.stringify(Select2)) + "\");\n";

// materialize our ga instance in the worker
blobScript += "var genetic = Serialization.parse(\"" + addslashes(Serialization.stringify(this)) + "\");\n";
blobScript += "onmessage = function(e) { genetic.start(); }\n";

// webworker
var blob = new Blob([blobScript]);
var worker = new Worker(window.URL.createObjectURL(blob));
Expand All @@ -260,15 +262,11 @@ var Genetic = Genetic || (function(){
};
worker.postMessage("");
} else {
// simulate webworker
(function(){
var onmessage;
eval(blobScript);
onmessage(null);
})();
// run process without webworker
self.start();
}
}

return {
"create": function() {
return new Genetic();
Expand All @@ -277,7 +275,7 @@ var Genetic = Genetic || (function(){
, "Optimize": Optimize
, "Clone": Clone
};

})();


Expand Down
Loading