Passed
Push — dev ( 1fc0f3...09846b )
by Jordan
42s queued 10s
created

Exponential::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.5

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 13
ccs 4
cts 8
cp 0.5
crap 2.5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Samsara\Fermat\Provider\Distribution;
4
5
use RandomLib\Factory;
6
use Samsara\Exceptions\UsageError\IntegrityConstraint;
7
use Samsara\Exceptions\UsageError\OptionalExit;
8
use Samsara\Fermat\Numbers;
9
use Samsara\Fermat\Provider\Distribution\Base\Distribution;
10
use Samsara\Fermat\Types\Base\DecimalInterface;
11
use Samsara\Fermat\Values\ImmutableNumber;
12
13
class Exponential extends Distribution
14
{
15
16
    /**
17
     * @var ImmutableNumber
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 1
    public function __construct($lambda)
29
    {
30 1
        $lambda = Numbers::makeOrDont(Numbers::IMMUTABLE, $lambda);
31
32 1
        if (!$lambda->isPositive()) {
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 1
        $this->lambda = $lambda;
0 ignored issues
show
Documentation Bug introduced by
It seems like $lambda can also be of type Samsara\Fermat\Values\MutableNumber. However, the property $lambda is declared as type Samsara\Fermat\Values\ImmutableNumber. 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 1
    }
42
43
    /**
44
     * @param int|float|DecimalInterface $x
45
     *
46
     * @return ImmutableNumber
47
     * @throws IntegrityConstraint
48
     */
49
    public function cdf($x): ImmutableNumber
50
    {
51
52
        $x = Numbers::makeOrDont(Numbers::IMMUTABLE, $x);
53
        /** @var ImmutableNumber $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
        /** @var ImmutableNumber $e */
65
        $e = Numbers::makeE();
66
67
        /** @var ImmutableNumber $cdf */
68
        $cdf = $one->subtract($e->pow($x->multiply($this->lambda)->multiply(-1)));
0 ignored issues
show
Bug introduced by
The method multiply() does not exist on Samsara\Fermat\Types\Base\DecimalInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Samsara\Fermat\Types\Base\DecimalInterface. ( Ignorable by Annotation )

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

68
        $cdf = $one->subtract($e->pow($x->multiply($this->lambda)->/** @scrutinizer ignore-call */ multiply(-1)));
Loading history...
Bug introduced by
The method multiply() does not exist on Samsara\Fermat\Types\Base\FractionInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Samsara\Fermat\Types\Base\FractionInterface. ( Ignorable by Annotation )

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

68
        $cdf = $one->subtract($e->pow($x->multiply($this->lambda)->/** @scrutinizer ignore-call */ multiply(-1)));
Loading history...
69
70
        return $cdf;
71
72
    }
73
74
    /**
75
     * @param $x
76
     *
77
     * @return ImmutableNumber
78
     * @throws IntegrityConstraint
79
     */
80
    public function pdf($x): ImmutableNumber
81
    {
82
83
        $x = Numbers::makeOrDont(Numbers::IMMUTABLE, $x);
84
85
        if (!$x->isPositive()) {
86
            throw new IntegrityConstraint(
87
                'X must be positive',
88
                'Provide a positive x',
89
                'Exponential distributions work on time to occurrence; the time to occurrence (x) must be positive'
90
            );
91
        }
92
93
        /** @var ImmutableNumber $e */
94
        $e = Numbers::makeE();
95
96
        /** @var ImmutableNumber $pdf */
97
        $pdf = $this->lambda->multiply($e->pow($this->lambda->multiply(-1)->multiply($x)));
98
99
        return $pdf;
100
101
    }
102
103
    /**
104
     * @param $x1
105
     * @param $x2
106
     *
107
     * @return ImmutableNumber
108
     * @throws IntegrityConstraint
109
     */
110
    public function rangePdf($x1, $x2): ImmutableNumber
111
    {
112
        $x1 = Numbers::makeOrDont(Numbers::IMMUTABLE, $x1);
113
        $x2 = Numbers::makeOrDont(Numbers::IMMUTABLE, $x2);
114
115
        if (!$x1->isPositive() || !$x2->isPositive()) {
116
            throw new IntegrityConstraint(
117
                'X must be positive',
118
                'Provide a positive x',
119
                'Exponential distributions work on time to occurrence; the time to occurrence (x) must be positive'
120
            );
121
        }
122
123
        /** @var ImmutableNumber $rangePdf */
124
        $rangePdf = $this->pdf($x2)->subtract($this->pdf($x1))->abs();
125
126
        return $rangePdf;
127
    }
128
129
    /**
130
     * @return ImmutableNumber
131
     */
132
    public function random(): ImmutableNumber
133
    {
134
135
        $randFactory = new Factory();
136
        $generator = $randFactory->getMediumStrengthGenerator();
137
        $one = Numbers::makeOne();
138
        $u = Numbers::make(Numbers::IMMUTABLE, $generator->generateInt(), 20);
139
        $u = $u->divide(PHP_INT_MAX);
0 ignored issues
show
Bug introduced by
The method divide() does not exist on Samsara\Fermat\Types\Base\FractionInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Samsara\Fermat\Types\Base\FractionInterface. ( Ignorable by Annotation )

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

139
        /** @scrutinizer ignore-call */ 
140
        $u = $u->divide(PHP_INT_MAX);
Loading history...
140
141
        /** @var ImmutableNumber $random */
142
        $random = $one->subtract($u)->ln()->divide($this->lambda->multiply(-1));
0 ignored issues
show
Bug introduced by
The method divide() does not exist on Samsara\Fermat\Types\Base\DecimalInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Samsara\Fermat\Types\Base\DecimalInterface. ( Ignorable by Annotation )

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

142
        $random = $one->subtract($u)->ln()->/** @scrutinizer ignore-call */ divide($this->lambda->multiply(-1));
Loading history...
143
144
        return $random;
145
146
    }
147
148
    /**
149
     * @param int|float|DecimalInterface $min
150
     * @param int|float|DecimalInterface $max
151
     * @param int $maxIterations
152
     *
153
     * @return ImmutableNumber
154
     * @throws OptionalExit
155
     */
156
    public function rangeRandom($min = 0, $max = PHP_INT_MAX, int $maxIterations = 20): ImmutableNumber
157
    {
158
159
        $i = 0;
160
161
        do {
162
            $randomNumber = $this->random();
163
            $i++;
164
        } while (($randomNumber->isGreaterThan($max) || $randomNumber->isLessThan($min)) && $i < $maxIterations);
165
166
        if ($randomNumber->isGreaterThan($max) || $randomNumber->isLessThan($min)) {
167
            throw new OptionalExit(
168
                'All random numbers generated were outside of the requested range',
169
                '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\Types\Bas...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

169
                '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\Types\Bas...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

169
                'A suitable random number, restricted by the $max ('./** @scrutinizer ignore-type */ $max.') and $min ('.$min.'), could not be found within '.$maxIterations.' iterations'
Loading history...
170
            );
171
        }
172
173
        return $randomNumber;
174
    }
175
176
}