LinearRegression::calculate()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 38
Code Lines 22

Duplication

Lines 4
Ratio 10.53 %

Importance

Changes 0
Metric Value
dl 4
loc 38
rs 8.439
c 0
b 0
f 0
cc 6
eloc 22
nc 8
nop 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Regression;
5
6
/**
7
 * Class LinearRegression
8
 *
9
 * @package Regression
10
 * @author  [email protected]
11
 */
12
class LinearRegression extends AbstractRegression
13
{
14
    /**
15
     * LinearRegression constructor.
16
     */
17
    public function __construct()
18
    {
19
        $this->sumIndex = [0, 0, 0, 0, 0, 0];
20
        $this->dimension = \count($this->sumIndex);
21
    }
22
23
    /**
24
     * @throws RegressionException
25
     */
26
    public function calculate()
27
    {
28
        if ($this->sourceSequence === null) {
29
            throw new RegressionException('The input sequence is not set');
30
        }
31
32
        if (\count($this->sourceSequence) < $this->dimension) {
33
            throw new RegressionException('The dimension of the sequence of at least ' . $this->dimension);
34
        }
35
36
        $k = 0;
37
38
        foreach ($this->sourceSequence as $k => $v) {
39
            if ($v[1] !== null) {
40
                $this->sumIndex[0] += $v[0];
41
                $this->sumIndex[1] += $v[1];
42
                $this->sumIndex[2] += $v[0] * $v[0];
43
                $this->sumIndex[3] += $v[0] * $v[1];
44
                $this->sumIndex[4] += $v[1] * $v[1];
45
            }
46
        }
47
48
        ++$k;
49
50
        $gradient = ($k * $this->sumIndex[3] - $this->sumIndex[0] * $this->sumIndex[1]) /
51
            ($k * $this->sumIndex[2] - $this->sumIndex[0] * $this->sumIndex[0]);
52
        
53
        $intercept = $this->sumIndex[1] / $k - $gradient * $this->sumIndex[0] / $k;
54
55 View Code Duplication
        foreach ($this->sourceSequence as $i => $val) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
            $coordinate = [$val[0], $val[0] * $gradient + $intercept];
57
            $this->resultSequence[] = $coordinate;
58
        }
59
60
        $this->equation = 'y = ' . \round($gradient, 1) . 'x + ' . \round($intercept, 1);
61
62
        $this->push();
63
    }
64
}
65