Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace Phpml\Clustering\KMeans;
6
 
7
use ArrayAccess;
8
 
9
class Point implements ArrayAccess, \Countable
10
{
11
    /**
12
     * @var int
13
     */
14
    protected $dimension;
15
 
16
    /**
17
     * @var array
18
     */
19
    protected $coordinates = [];
20
 
21
    /**
22
     * @var mixed
23
     */
24
    protected $label;
25
 
26
    /**
27
     * @param mixed $label
28
     */
29
    public function __construct(array $coordinates, $label = null)
30
    {
31
        $this->dimension = count($coordinates);
32
        $this->coordinates = $coordinates;
33
        $this->label = $label;
34
    }
35
 
36
    public function toArray(): array
37
    {
38
        return $this->coordinates;
39
    }
40
 
41
    /**
42
     * @return float|int
43
     */
44
    public function getDistanceWith(self $point, bool $precise = true)
45
    {
46
        $distance = 0;
47
        for ($n = 0; $n < $this->dimension; ++$n) {
48
            $difference = $this->coordinates[$n] - $point->coordinates[$n];
49
            $distance += $difference * $difference;
50
        }
51
 
52
        return $precise ? $distance ** .5 : $distance;
53
    }
54
 
55
    /**
56
     * @param Point[] $points
57
     */
58
    public function getClosest(array $points): ?self
59
    {
60
        $minPoint = null;
61
 
62
        foreach ($points as $point) {
63
            $distance = $this->getDistanceWith($point, false);
64
 
65
            if (!isset($minDistance)) {
66
                $minDistance = $distance;
67
                $minPoint = $point;
68
 
69
                continue;
70
            }
71
 
72
            if ($distance < $minDistance) {
73
                $minDistance = $distance;
74
                $minPoint = $point;
75
            }
76
        }
77
 
78
        return $minPoint;
79
    }
80
 
81
    public function getCoordinates(): array
82
    {
83
        return $this->coordinates;
84
    }
85
 
86
    /**
87
     * @param mixed $offset
88
     */
89
    public function offsetExists($offset): bool
90
    {
91
        return isset($this->coordinates[$offset]);
92
    }
93
 
94
    /**
95
     * @param mixed $offset
96
     *
97
     * @return mixed
98
     */
99
    public function offsetGet($offset)
100
    {
101
        return $this->coordinates[$offset];
102
    }
103
 
104
    /**
105
     * @param mixed $offset
106
     * @param mixed $value
107
     */
108
    public function offsetSet($offset, $value): void
109
    {
110
        $this->coordinates[$offset] = $value;
111
    }
112
 
113
    /**
114
     * @param mixed $offset
115
     */
116
    public function offsetUnset($offset): void
117
    {
118
        unset($this->coordinates[$offset]);
119
    }
120
 
121
    public function count(): int
122
    {
123
        return count($this->coordinates);
124
    }
125
}