1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Search; |
4
|
|
|
|
5
|
|
|
use Generator; |
6
|
|
|
use KDTree\Exceptions\InvalidDimensionsCount; |
7
|
|
|
use KDTree\Exceptions\InvalidPointProvided; |
8
|
|
|
use KDTree\Exceptions\PointAlreadyExists; |
9
|
|
|
use KDTree\Interfaces\KDTreeInterface; |
10
|
|
|
use KDTree\Search\NearestSearch; |
11
|
|
|
use KDTree\Structure\KDTree; |
12
|
|
|
use KDTree\ValueObject\Point; |
13
|
|
|
use PHPUnit\Framework\ExpectationFailedException; |
14
|
|
|
use PHPUnit\Framework\TestCase; |
15
|
|
|
use SebastianBergmann\RecursionContext\InvalidArgumentException; |
16
|
|
|
|
17
|
|
|
final class NearestSearchTest extends TestCase |
18
|
|
|
{ |
19
|
|
|
public function testConstruction(): void |
20
|
|
|
{ |
21
|
|
|
$nearestSearch = new NearestSearch($this->prepareKdTree()); |
22
|
|
|
|
23
|
|
|
$this->assertEquals(PHP_INT_MAX, $nearestSearch->getNearestDistance()); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @dataProvider nearestProvider |
28
|
|
|
* |
29
|
|
|
* @param array $point |
30
|
|
|
* @param array $nearest |
31
|
|
|
* @param float $distance |
32
|
|
|
* |
33
|
|
|
* @throws InvalidDimensionsCount|InvalidPointProvided|PointAlreadyExists|ExpectationFailedException|InvalidArgumentException |
34
|
|
|
*/ |
35
|
|
|
public function testFindNearest(array $point, array $nearest, float $distance): void |
36
|
|
|
{ |
37
|
|
|
$nearestSearch = new NearestSearch($this->prepareKdTree()); |
38
|
|
|
|
39
|
|
|
$point = $nearestSearch->nearest(new Point(...$point)); |
40
|
|
|
$this->assertEquals($nearest, $point->getAxises()); |
41
|
|
|
$this->assertEquals($distance, $nearestSearch->getNearestDistance()); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @return Generator |
46
|
|
|
*/ |
47
|
|
|
public function nearestProvider(): Generator |
48
|
|
|
{ |
49
|
|
|
yield 'another point' => [ |
50
|
|
|
'point' => [1, 1], |
51
|
|
|
'nearest' => [1, 3], |
52
|
|
|
'distance' => 2.0 |
53
|
|
|
]; |
54
|
|
|
|
55
|
|
|
yield 'existing point' => [ |
56
|
|
|
'point' => [9, 1], |
57
|
|
|
'nearest' => [9, 1], |
58
|
|
|
'distance' => 0.0 |
59
|
|
|
]; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return KDTreeInterface |
64
|
|
|
* @throws InvalidDimensionsCount|InvalidPointProvided|PointAlreadyExists |
65
|
|
|
*/ |
66
|
|
|
private function prepareKdTree(): KDTreeInterface |
67
|
|
|
{ |
68
|
|
|
$kdTree = new KDTree(2); |
69
|
|
|
$kdTree->put(new Point(1, 3)) |
70
|
|
|
->put(new Point(4, 5)) |
71
|
|
|
->put(new Point(9, 1)); |
72
|
|
|
|
73
|
|
|
return $kdTree; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|