Skip to content

Commit 8610aa6

Browse files
committed
Add simple population mutation
1 parent a195bc6 commit 8610aa6

File tree

3 files changed

+36
-3
lines changed

3 files changed

+36
-3
lines changed

src/Population.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,16 @@ public function select($number)
4141
return collect($this->solutions)->sortByDesc('fitness')->take($number);
4242
}
4343

44+
public function mutate()
45+
{
46+
$this->solutions = collect($this->solutions)->map(function ($solution) {
47+
if (mt_rand(1, 7) == 1) {
48+
$solution->mutate();
49+
}
50+
return $solution;
51+
})->toArray();
52+
}
53+
4454
protected function initialise()
4555
{
4656
for ($i = 0; $i < $this->size; $i++) {

src/Solution.php

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,25 @@ abstract public function evaluate($data);
1414

1515
public function initialise()
1616
{
17-
$this->chromosomes = collect($this->genome())->map(function ($chromosome) {
18-
$randomiser = 'random' . ucfirst($chromosome[0]);
19-
return $this->$randomiser($chromosome);
17+
$this->chromosomes = collect($this->genome())->map(function ($definition) {
18+
return $this->chromosome($definition);
2019
})->toArray();
2120
}
2221

22+
public function chromosome($definition)
23+
{
24+
$randomiser = 'random' . ucfirst($definition[0]);
25+
return $this->$randomiser($definition);
26+
}
27+
28+
public function mutate()
29+
{
30+
$definition = $this->genome();
31+
$chromosomePosition = mt_rand(0, sizeof($definition) - 1);
32+
$this->chromosomes[$chromosomePosition] = $this->chromosome($definition[$chromosomePosition]);
33+
return $this;
34+
}
35+
2336
public function chromosomes()
2437
{
2538
return $this->chromosomes;

tests/PopulationTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,14 @@ public function apply_selection_strategy()
6363
$this->assertCount(6, $selections);
6464
$this->assertEquals([1052, 771, 758, 683, 641, 607], $selections->pluck('fitness')->toArray());
6565
}
66+
67+
/** @test */
68+
public function apply_mutation_strategy()
69+
{
70+
$population = new Population(Integers::class, 12);
71+
$this->assertEquals([90, -52, -1], $population->solutions()[5]->chromosomes());
72+
73+
$population->mutate();
74+
$this->assertEquals([90, -83, -1], $population->solutions()[5]->chromosomes());
75+
}
6676
}

0 commit comments

Comments
 (0)