|
6 | 6 | use Kmeans\Euclidean\Point; |
7 | 7 | use Kmeans\Euclidean\Space; |
8 | 8 | use Kmeans\Interfaces\AlgorithmInterface; |
| 9 | +use Kmeans\Interfaces\ClusterCollectionInterface; |
9 | 10 | use Kmeans\Interfaces\InitializationSchemeInterface; |
10 | 11 | use Kmeans\Interfaces\PointCollectionInterface; |
11 | 12 | use Kmeans\Interfaces\SpaceInterface; |
12 | 13 | use Kmeans\Math; |
13 | 14 | use Kmeans\PointCollection; |
| 15 | +use Kmeans\RandomInitialization; |
14 | 16 | use Tests\Unit\AlgorithmTest as BaseAlgorithmTest; |
15 | 17 |
|
16 | 18 | /** |
|
24 | 26 | * @uses \Kmeans\Euclidean\Space |
25 | 27 | * @uses \Kmeans\Math |
26 | 28 | * @uses \Kmeans\PointCollection |
| 29 | + * @uses \Kmeans\RandomInitialization |
27 | 30 | * @phpstan-import-type ClusterizeScenarioData from BaseAlgorithmTest |
28 | 31 | */ |
29 | 32 | class AlgorithmTest extends BaseAlgorithmTest |
@@ -146,4 +149,43 @@ public function testFindCentroidException(): void |
146 | 149 | new PointCollection(new \Kmeans\Gps\Space(), []) |
147 | 150 | ); |
148 | 151 | } |
| 152 | + |
| 153 | + public function testMaxIterations(): void |
| 154 | + { |
| 155 | + $algorithm = new class (new RandomInitialization()) extends Algorithm |
| 156 | + { |
| 157 | + protected function iterate(ClusterCollectionInterface $clusters): bool |
| 158 | + { |
| 159 | + // do nothing and iterate indefinitely |
| 160 | + return true; |
| 161 | + } |
| 162 | + }; |
| 163 | + |
| 164 | + $iterations = 0; |
| 165 | + $algorithm->registerIterationCallback(function () use (&$iterations) { |
| 166 | + $iterations++; |
| 167 | + }); |
| 168 | + |
| 169 | + $space = new Space(1); |
| 170 | + $points = new PointCollection( |
| 171 | + $space, |
| 172 | + array_map([$space, 'makePoint'], [[1],[2],[3]]) |
| 173 | + ); |
| 174 | + |
| 175 | + $algorithm->clusterize($points, 3, 300); |
| 176 | + |
| 177 | + $this->assertEquals( |
| 178 | + 300, |
| 179 | + $iterations |
| 180 | + ); |
| 181 | + } |
| 182 | + |
| 183 | + public function testMaxIterationsException(): void |
| 184 | + { |
| 185 | + $this->expectException(\UnexpectedValueException::class); |
| 186 | + $this->expectExceptionMessageMatches('/^Invalid maximum number of iterations/'); |
| 187 | + |
| 188 | + $algorithm = new Algorithm(new RandomInitialization()); |
| 189 | + $algorithm->clusterize(new PointCollection(new Space(1), []), 3, 0); |
| 190 | + } |
149 | 191 | } |
0 commit comments