Examples
These examples and others examples may be found in the
examples folder.
The Traveling Salesman
import devolve.list;
import std.algorithm;
immutable uint[char[2]] distances;
static this() {
distances = [
"ab": 20u,
"ac": 42u,
"ad": 35u,
"bc": 30u,
"bd": 34u,
"cd": 12u
];
}
alias individual = char[4];
double fitness(in individual ind) {
double total = 0;
for(uint i=0; i < ind.length-1; ++i) {
char lower = min(ind[i], ind[i+1]);
char higher = max(ind[i], ind[i+1]);
total += distances[[lower, higher]];
}
return total;
};
void main() {
auto ga = new ListGA!(
individual, 10,
fitness,
generator.preset!('c', 'b', 'a', 'd'),
selector.topPar!2,
crossover.randomCopy,
mutator.randomSwap,
"a < b");
ga.mutationRate = 0.1f;
ga.statFrequency = 5;
ga.evolve(30);
}
Symbolic Regression
import devolve.tree;
import std.math, std.conv, std.range;
import std.typecons, std.algorithm;
double f(double x) {return x*x + 2*x+sin(x)*sin(x)-23;}
immutable Tuple!(double, double)[] points;
static this() {
points = array(zip(iota(-10, 10, 0.5),
map!f(iota(-10, 10, 0.5)))).idup;
}
double x;
double fitness(ref Tree!double algorithm) {
double fit = 1;
foreach(ref pair; points) {
x = pair[0];
fit += abs(algorithm.eval() - pair[1]);
}
return fit;
}
void main() {
TreeGenerator!double gen;
gen.register!"-a"("negative");
gen.register!"a*a"("square");
gen.register!"a+b"("sum");
gen.register!"a-b"("difference");
gen.register!"a*b"("product");
gen.register!((double a) {return to!double(sin(a));})("sin");
gen.register!((double a) {return to!double(cos(a));})("cos");
double div(double a, double b) {
if (!isInfinity(a/b) && b != 0) {
return a/b;
}
else {
return 0;
}
}
gen.register(&div, "div");
gen.registerInput!x;
gen.registerConstantRange(-10.0f, 10.0f);
auto ga = new TreeGA!(double,
1500,
5,
fitness,
selector.topPar!50,
crossover.singlePoint,
mutator.randomBranch,
"a < b")(gen);
ga.mutationRate = 0.07;
ga.statFrequency = 20;
ga.terminationValue = 0;
ga.autoGenerateGraph = true;
ga.evolve(600);
}