|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Kmeans; |
|
4
|
|
|
|
|
5
|
|
|
use Kmeans\Concerns\HasSpaceTrait; |
|
6
|
|
|
use Kmeans\Interfaces\ClusterCollectionInterface; |
|
7
|
|
|
use Kmeans\Interfaces\ClusterInterface; |
|
8
|
|
|
use Kmeans\Interfaces\SpaceInterface; |
|
9
|
|
|
|
|
10
|
|
|
class ClusterCollection implements ClusterCollectionInterface |
|
11
|
|
|
{ |
|
12
|
|
|
use HasSpaceTrait; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @var \SplObjectStorage<ClusterInterface, null> |
|
16
|
|
|
*/ |
|
17
|
|
|
protected \SplObjectStorage $clusters; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @param array<ClusterInterface> $clusters |
|
21
|
|
|
*/ |
|
22
|
|
|
public function __construct(SpaceInterface $space, array $clusters = []) |
|
23
|
|
|
{ |
|
24
|
|
|
$this->setSpace($space); |
|
25
|
|
|
$this->clusters = new \SplObjectStorage(); |
|
26
|
|
|
|
|
27
|
|
|
foreach ($clusters as $cluster) { |
|
28
|
|
|
$this->attach($cluster); |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function contains(ClusterInterface $cluster): bool |
|
33
|
|
|
{ |
|
34
|
|
|
return $this->clusters->contains($cluster); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function attach(ClusterInterface $cluster): void |
|
38
|
|
|
{ |
|
39
|
|
|
if ($cluster->getCentroid()->getSpace() !== $this->getSpace()) { |
|
40
|
|
|
throw new \InvalidArgumentException( |
|
41
|
|
|
"Cannot add cluster to collection: cluster space is not same as collection space" |
|
42
|
|
|
); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
$this->clusters->attach($cluster); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
public function detach(ClusterInterface $cluster): void |
|
49
|
|
|
{ |
|
50
|
|
|
$this->clusters->detach($cluster); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
public function current() |
|
54
|
|
|
{ |
|
55
|
|
|
return $this->clusters->current(); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
public function key() |
|
59
|
|
|
{ |
|
60
|
|
|
return $this->clusters->key(); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
public function next(): void |
|
64
|
|
|
{ |
|
65
|
|
|
$this->clusters->next(); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
public function rewind(): void |
|
69
|
|
|
{ |
|
70
|
|
|
$this->clusters->rewind(); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
public function valid(): bool |
|
74
|
|
|
{ |
|
75
|
|
|
return $this->clusters->valid(); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
public function count(): int |
|
79
|
|
|
{ |
|
80
|
|
|
return count($this->clusters); |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|