Completed
Push — master ( 5d186e...d62f94 )
by Jordan
16s queued 13s
created

Exponential::rangeRandom()   A

Complexity

Conditions 6
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
dl 0
loc 18
ccs 0
cts 0
cp 0
crap 42
rs 9.2222
c 1
b 0
f 0
eloc 10
nc 2
nop 3
1
<?php
2
3
namespace Samsara\Fermat\Stats\Values\Distribution;
4
5
use Samsara\Exceptions\UsageError\IntegrityConstraint;
6
use Samsara\Exceptions\UsageError\OptionalExit;
7
use Samsara\Fermat\Core\Numbers;
8
use Samsara\Fermat\Stats\Types\Distribution;
9
use Samsara\Fermat\Core\Provider\RandomProvider;
10
use Samsara\Fermat\Core\Types\Base\Interfaces\Numbers\DecimalInterface;
11
use Samsara\Fermat\Core\Values\ImmutableDecimal;
12
13
class Exponential extends Distribution
14
{
15
16
    /**
17
     * @var ImmutableDecimal
18
     */
19
    private $lambda;
20
21
    /**
22
     * Exponential constructor.
23
     *
24
     * @param int|float|DecimalInterface $lambda This is the *rate parameter* not the *scale parameter*
25
     *
26
     * @throws IntegrityConstraint
27
     */
28 2
    public function __construct($lambda)
29
    {
30 2
        $lambda = Numbers::makeOrDont(Numbers::IMMUTABLE, $lambda);
31
32 2
        if (!$lambda->isPositive()) {
0 ignored issues
show
Bug introduced by
The method isPositive() does not exist on Samsara\Fermat\Core\Type...Numbers\NumberInterface. It seems like you code against a sub-type of Samsara\Fermat\Core\Type...Numbers\NumberInterface such as Samsara\Fermat\Core\Type...s\SimpleNumberInterface or Samsara\Fermat\Core\Types\Fraction or Samsara\Fermat\Core\Types\Decimal. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

32
        if (!$lambda->/** @scrutinizer ignore-call */ isPositive()) {
Loading history...
33
            throw new IntegrityConstraint(
34
                'Lambda must be positive',
35
                'Provide a positive lambda',
36
                'Exponential distributions work on time to occurrence; the mean time to occurrence (lambda) must be positive'
37
            );
38
        }
39
40 2
        $this->lambda = $lambda;
0 ignored issues
show
Documentation Bug introduced by
It seems like $lambda can also be of type Samsara\Fermat\Core\Type...Numbers\NumberInterface. However, the property $lambda is declared as type Samsara\Fermat\Core\Values\ImmutableDecimal. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
41
    }
42
43
    /**
44
     * @param int|float|DecimalInterface $x
45
     *
46
     * @return ImmutableDecimal
47
     * @throws IntegrityConstraint
48
     */
49
    public function cdf($x, int $scale = 10): ImmutableDecimal
50
    {
51
52
        $x = Numbers::makeOrDont(Numbers::IMMUTABLE, $x);
53
        /** @var ImmutableDecimal $one */
54
        $one = Numbers::makeOne();
55
56
        if (!$x->isPositive()) {
57
            throw new IntegrityConstraint(
58
                'X must be positive',
59
                'Provide a positive x',
60
                'Exponential distributions work on time to occurrence; the time to occurrence (x) must be positive'
61
            );
62
        }
63
64
        $internalScale = $scale + 2;
65
66
        /** @var ImmutableDecimal $e */
67
        $e = Numbers::makeE($internalScale);
68
69
        /** @var ImmutableDecimal $cdf */
70
        $cdf =
71
            $one->subtract(
72
                $e->pow(
73
                    $x->multiply($this->lambda)
74
                        ->multiply(-1)
75
                )
76
            )->truncateToScale($scale);
77
78
        return $cdf;
79
80
    }
81
82
    /**
83
     * @param $x
84
     *
85
     * @return ImmutableDecimal
86
     * @throws IntegrityConstraint
87
     */
88
    public function pdf($x, int $scale = 10): ImmutableDecimal
89
    {
90
91
        $x = Numbers::makeOrDont(Numbers::IMMUTABLE, $x);
92
93
        if (!$x->isPositive()) {
94
            throw new IntegrityConstraint(
95
                'X must be positive',
96
                'Provide a positive x',
97
                'Exponential distributions work on time to occurrence; the time to occurrence (x) must be positive'
98
            );
99
        }
100
101
        $internalScale = $scale + 2;
102
103
        /** @var ImmutableDecimal $e */
104
        $e = Numbers::makeE($internalScale);
105
106
        /** @var ImmutableDecimal $pdf */
107
        $pdf =
108
            $this->lambda
109
                ->multiply(
110
                    $e->pow(
111
                        $this->lambda
112
                            ->multiply(-1)
113
                            ->multiply($x)
114
                    )
115
                )->truncateToScale($scale);
116
117
        return $pdf;
118
119
    }
120
121
    /**
122
     * @param $x1
123
     * @param $x2
124
     *
125
     * @return ImmutableDecimal
126
     * @throws IntegrityConstraint
127
     */
128
    public function rangePdf($x1, $x2, int $scale = 10): ImmutableDecimal
129
    {
130
        $x1 = Numbers::makeOrDont(Numbers::IMMUTABLE, $x1);
131
        $x2 = Numbers::makeOrDont(Numbers::IMMUTABLE, $x2);
132
133
        if (!$x1->isPositive() || !$x2->isPositive()) {
134
            throw new IntegrityConstraint(
135
                'X must be positive',
136
                'Provide a positive x',
137
                'Exponential distributions work on time to occurrence; the time to occurrence (x) must be positive'
138
            );
139
        }
140
141
        $internalScale = $scale + 2;
142
143
        /** @var ImmutableDecimal $rangePdf */
144
        $rangePdf =
145
            $this->pdf(
146
                $x2,
147
                $internalScale
148
            )->subtract(
149
                $this->pdf(
150
                    $x1,
151
                    $internalScale)
152
            )->abs()
153
            ->truncateToScale($scale);
0 ignored issues
show
Bug introduced by
The method truncateToScale() does not exist on Samsara\Fermat\Core\Type...Numbers\NumberInterface. It seems like you code against a sub-type of Samsara\Fermat\Core\Type...Numbers\NumberInterface such as Samsara\Fermat\Core\Types\Decimal or Samsara\Fermat\Core\Type...umbers\DecimalInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

153
            ->/** @scrutinizer ignore-call */ truncateToScale($scale);
Loading history...
Bug introduced by
The method truncateToScale() does not exist on Samsara\Fermat\Core\Type...mbers\FractionInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

153
            ->/** @scrutinizer ignore-call */ truncateToScale($scale);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
154
155
        return $rangePdf;
156
    }
157
158
    /**
159
     * @return ImmutableDecimal
160
     *
161
     * @codeCoverageIgnore
162
     */
163
    public function random(): ImmutableDecimal
164
    {
165
166
        $u = RandomProvider::randomDecimal(10);
167
        $one = Numbers::makeOne();
168
169
        /** @var ImmutableDecimal $random */
170
        $random =
171
            $one->subtract($u)
172
                ->ln()
173
                ->divide(
174
                    $this->lambda
175
                        ->multiply(-1)
176
                );
177
178
        return $random;
179
180
    }
181
182
    /**
183
     * @param int|float|DecimalInterface $min
184
     * @param int|float|DecimalInterface $max
185
     * @param int $maxIterations
186
     *
187
     * @return ImmutableDecimal
188
     * @throws OptionalExit
189
     *
190
     * @codeCoverageIgnore
191
     */
192
    public function rangeRandom($min = 0, $max = PHP_INT_MAX, int $maxIterations = 20): ImmutableDecimal
193
    {
194
195
        $i = 0;
196
197
        do {
198
            $randomNumber = $this->random();
199
            $i++;
200
        } while (($randomNumber->isGreaterThan($max) || $randomNumber->isLessThan($min)) && $i < $maxIterations);
201
202
        if ($randomNumber->isGreaterThan($max) || $randomNumber->isLessThan($min)) {
203
            throw new OptionalExit(
204
                'All random numbers generated were outside of the requested range',
205
                'A suitable random number, restricted by the $max ('.$max.') and $min ('.$min.'), could not be found within '.$maxIterations.' iterations'
0 ignored issues
show
Bug introduced by
Are you sure $min of type Samsara\Fermat\Core\Type...nterface|double|integer can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

205
                'A suitable random number, restricted by the $max ('.$max.') and $min ('./** @scrutinizer ignore-type */ $min.'), could not be found within '.$maxIterations.' iterations'
Loading history...
Bug introduced by
Are you sure $max of type Samsara\Fermat\Core\Type...nterface|double|integer can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

205
                'A suitable random number, restricted by the $max ('./** @scrutinizer ignore-type */ $max.') and $min ('.$min.'), could not be found within '.$maxIterations.' iterations'
Loading history...
206
            );
207
        }
208
209
        return $randomNumber;
210
    }
211
212
}