Completed
Push — dev ( 6f89f3...096a57 )
by Jordan
02:12
created

Normal::pmf()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
namespace Samsara\Fermat\Provider\Stats\Distribution;
4
5
use RandomLib\Factory;
6
use Samsara\Fermat\Numbers;
7
use Samsara\Fermat\Provider\Stats\Stats;
8
use Samsara\Fermat\Types\Base\NumberInterface;
9
use Samsara\Fermat\Values\ImmutableNumber;
10
11
class Normal
12
{
13
14
    /**
15
     * @var NumberInterface
16
     */
17
    private $mean;
18
19
    /**
20
     * @var NumberInterface
21
     */
22
    private $sd;
23
24
    public function __construct($mean, $sd)
25
    {
26
        $mean = Numbers::makeOrDont(Numbers::IMMUTABLE, $mean);
27
        $sd = Numbers::makeOrDont(Numbers::IMMUTABLE, $sd);
28
29
        $this->mean = $mean;
0 ignored issues
show
Documentation Bug introduced by
It seems like $mean can also be of type array. However, the property $mean is declared as type object<Samsara\Fermat\Types\Base\NumberInterface>. 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...
30
        $this->sd = $sd;
0 ignored issues
show
Documentation Bug introduced by
It seems like $sd can also be of type array. However, the property $sd is declared as type object<Samsara\Fermat\Types\Base\NumberInterface>. 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...
31
    }
32
33 View Code Duplication
    public static function makeFromMean($p, $x, $mean)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
34
    {
35
        $one = Numbers::makeOne();
36
        $p = Numbers::makeOrDont(Numbers::IMMUTABLE, $p);
37
        $x = Numbers::makeOrDont(Numbers::IMMUTABLE, $x);
38
        $mean = Numbers::makeOrDont(Numbers::IMMUTABLE, $mean);
39
40
        $z = Stats::inverseNormalCDF($one->subtract($p));
41
42
        $sd = $x->subtract($mean)->divide($z);
43
44
        return new Normal($mean, $sd);
45
    }
46
47 View Code Duplication
    public static function makeFromSd($p, $x, $sd)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
48
    {
49
        $one = Numbers::makeOne();
50
        $p = Numbers::makeOrDont(Numbers::IMMUTABLE, $p);
51
        $x = Numbers::makeOrDont(Numbers::IMMUTABLE, $x);
52
        $sd = Numbers::makeOrDont(Numbers::IMMUTABLE, $sd);
53
54
        $z = Stats::inverseNormalCDF($one->subtract($p));
55
56
        $mean = $x->subtract($z->multiply($sd));
57
58
        return new Normal($mean, $sd);
59
    }
60
    
61
    public function cdf($x)
62
    {
63
        $x = Numbers::makeOrDont(Numbers::IMMUTABLE, $x);
64
65
        if (function_exists('stats_cdf_normal') &&
66
            $x->isLessThanOrEqualTo(PHP_INT_MAX) &&
67
            $x->isGreaterThanOrEqualTo(PHP_INT_MIN) &&
68
            $this->mean->isLessThanOrEqualTo(PHP_INT_MAX) &&
69
            $this->mean->isGreaterThanOrEqualTo(PHP_INT_MIN) &&
70
            $this->sd->isLessThanOrEqualTo(PHP_INT_MAX) &&
71
            $this->sd->isGreaterThanOrEqualTo(PHP_INT_MIN)) {
72
            return Numbers::make(Numbers::IMMUTABLE, stats_cdf_normal($x->getValue(), $this->mean, $this->sd));
73
        }
74
75
        $oneHalf = Numbers::make(Numbers::IMMUTABLE, '0.5');
76
        $one = Numbers::makeOne();
77
        $sqrtTwo = Numbers::make(Numbers::IMMUTABLE, 2)->sqrt();
78
79
        return $oneHalf->multiply($one->add(Stats::gaussErrorFunction(
80
            $x->subtract($this->mean)->divide($this->sd->multiply($sqrtTwo))
81
        )));
82
    }
83
    
84
    public function pdf($x1, $x2)
85
    {
86
        return $this->cdf($x1)->subtract($this->cdf($x2))->abs();
87
    }
88
89
    /**
90
     * @return ImmutableNumber
91
     */
92
    public function random()
93
    {
94
        if (function_exists('stats_rand_gen_normal')) {
95
            return Numbers::make(Numbers::IMMUTABLE, stats_rand_gen_normal($this->mean, $this->sd), 20);
96
        } else {
97
            $randFactory = new Factory();
98
            $generator = $randFactory->getMediumStrengthGenerator();
99
100
            $rand1 = Numbers::make(Numbers::IMMUTABLE, $generator->generateInt(), 20);
101
            $rand1 = $rand1->divide(PHP_INT_MAX);
102
            $rand2 = Numbers::make(Numbers::IMMUTABLE, $generator->generateInt(), 20);
103
            $rand2 = $rand2->divide(PHP_INT_MAX);
104
105
            $randomNumber = $rand1->ln()->multiply(-2)->sqrt()->multiply($rand2->multiply(Numbers::TAU)->cos(1, 2, 20));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Samsara\Fermat\Types\Base\NumberInterface as the method cos() does only exist in the following implementations of said interface: Samsara\Fermat\Values\Currency, Samsara\Fermat\Values\ImmutableNumber, Samsara\Fermat\Values\MutableNumber.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
106
            $randomNumber = $randomNumber->multiply($this->sd)->add($this->mean);
107
108
            return $randomNumber;
109
        }
110
    }
111
    
112
    public function rangeRandom($min = 0, $max = PHP_INT_MAX, $maxIterations = 20)
113
    {
114
        $i = 0;
115
116
        do {
117
            $randomNumber = $this->random();
118
            $i++;
119
        } while ($randomNumber->isLessThanOrEqualTo($max) && $randomNumber->isGreaterThanOrEqualTo($min) && $i < $maxIterations);
120
121
        if ($randomNumber->isGreaterThan($max) || $randomNumber->isLessThan($min)) {
122
            throw new \Exception();
123
        } else {
124
            return $randomNumber;
125
        }
126
    }
127
128
}