Skip to content

Commit 7fc1456

Browse files
committed
Support for solution summaries
1 parent 78b8d76 commit 7fc1456

File tree

3 files changed

+60
-2
lines changed

3 files changed

+60
-2
lines changed

src/Solution.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,11 @@ public function chromosomes()
4747
return $this->chromosomes;
4848
}
4949

50+
public function summary()
51+
{
52+
return (object) ['fitness' => $this->fitness, 'chromosomes' => implode(':', $this->chromosomes)];
53+
}
54+
5055
protected function randomChar($chromosome)
5156
{
5257
return $chromosome[1][mt_rand(0, strlen($chromosome[1]) - 1)];

tests/SolutionSummaryTest.php

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
namespace PeterColes\GAO\Tests;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use PeterColes\GAO\Tests\Solutions\Floats;
7+
use PeterColes\GAO\Tests\Solutions\Integers;
8+
9+
class SolutionSummaryTest extends TestCase
10+
{
11+
public function setUp()
12+
{
13+
parent::setUp();
14+
15+
mt_srand(0); // seed random number generator for consistent test results
16+
}
17+
18+
/** @test */
19+
public function can_summarise_solution()
20+
{
21+
$solution = new Integers();
22+
$solution->initialise();
23+
$solution->evaluate([[10, 5, 1]]);
24+
25+
$summary = $solution->summary();
26+
27+
$this->assertEquals(446, $summary->fitness);
28+
$this->assertEquals('64:-39:1', $summary->chromosomes);
29+
}
30+
31+
/** @test */
32+
public function can_tailor_solution_summaries()
33+
{
34+
$solution = new Floats();
35+
$solution->initialise();
36+
$solution->evaluate();
37+
38+
$summary = $solution->summary();
39+
40+
$this->assertEquals(15.570, $summary->fitness);
41+
$this->assertEquals([54.88, -40.72, 0.72, 0.69], $summary->chromosomes);
42+
}
43+
}

tests/Solutions/Floats.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,18 @@ public function genome()
1616
];
1717
}
1818

19-
public function evaluate($data)
19+
public function evaluate($data = null)
2020
{
21-
//
21+
$this->fitness = collect($this->chromosomes)->sum();
22+
}
23+
24+
public function summary()
25+
{
26+
return (object) [
27+
'fitness' => number_format($this->fitness, 3),
28+
'chromosomes' => collect($this->chromosomes)->map(function ($chromosome) {
29+
return number_format($chromosome, 2);
30+
})->toArray(),
31+
];
2232
}
2333
}

0 commit comments

Comments
 (0)