Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/sympy/ntheory/digits.py +143 -0
- env-llmeval/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py +398 -0
- env-llmeval/lib/python3.10/site-packages/sympy/ntheory/multinomial.py +188 -0
- env-llmeval/lib/python3.10/site-packages/sympy/ntheory/partitions_.py +192 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_approximants.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_demidovich.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_formal.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_kauers.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_limitseq.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_lseries.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_nseries.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_order.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_sequences.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_series.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/__init__.py +202 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/compound_rv.py +223 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/crv.py +570 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/crv_types.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/drv.py +350 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/drv_types.py +835 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/error_prop.py +100 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/frv.py +512 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/frv_types.py +870 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/joint_rv.py +426 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/joint_rv_types.py +946 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/matrix_distributions.py +610 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/random_matrix.py +30 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/random_matrix_models.py +457 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/rv.py +1792 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/rv_interface.py +519 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_numpy.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_pymc.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_scipy.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/sample_numpy.py +105 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/sample_pymc.py +99 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/sample_scipy.py +167 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/test_sample_continuous_rv.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/test_sample_discrete_rv.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/test_sample_finite_rv.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/test_sample_continuous_rv.py +181 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/test_sample_discrete_rv.py +99 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/test_sample_finite_rv.py +94 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/stochastic_process.py +66 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/stochastic_process_types.py +2382 -0
- env-llmeval/lib/python3.10/site-packages/sympy/stats/symbolic_multivariate_probability.py +308 -0
env-llmeval/lib/python3.10/site-packages/sympy/ntheory/digits.py
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from collections import defaultdict
|
2 |
+
|
3 |
+
from sympy.utilities.iterables import multiset, is_palindromic as _palindromic
|
4 |
+
from sympy.utilities.misc import as_int
|
5 |
+
|
6 |
+
|
7 |
+
def digits(n, b=10, digits=None):
|
8 |
+
"""
|
9 |
+
Return a list of the digits of ``n`` in base ``b``. The first
|
10 |
+
element in the list is ``b`` (or ``-b`` if ``n`` is negative).
|
11 |
+
|
12 |
+
Examples
|
13 |
+
========
|
14 |
+
|
15 |
+
>>> from sympy.ntheory.digits import digits
|
16 |
+
>>> digits(35)
|
17 |
+
[10, 3, 5]
|
18 |
+
|
19 |
+
If the number is negative, the negative sign will be placed on the
|
20 |
+
base (which is the first element in the returned list):
|
21 |
+
|
22 |
+
>>> digits(-35)
|
23 |
+
[-10, 3, 5]
|
24 |
+
|
25 |
+
Bases other than 10 (and greater than 1) can be selected with ``b``:
|
26 |
+
|
27 |
+
>>> digits(27, b=2)
|
28 |
+
[2, 1, 1, 0, 1, 1]
|
29 |
+
|
30 |
+
Use the ``digits`` keyword if a certain number of digits is desired:
|
31 |
+
|
32 |
+
>>> digits(35, digits=4)
|
33 |
+
[10, 0, 0, 3, 5]
|
34 |
+
|
35 |
+
Parameters
|
36 |
+
==========
|
37 |
+
|
38 |
+
n: integer
|
39 |
+
The number whose digits are returned.
|
40 |
+
|
41 |
+
b: integer
|
42 |
+
The base in which digits are computed.
|
43 |
+
|
44 |
+
digits: integer (or None for all digits)
|
45 |
+
The number of digits to be returned (padded with zeros, if
|
46 |
+
necessary).
|
47 |
+
|
48 |
+
"""
|
49 |
+
|
50 |
+
b = as_int(b)
|
51 |
+
n = as_int(n)
|
52 |
+
if b < 2:
|
53 |
+
raise ValueError("b must be greater than 1")
|
54 |
+
else:
|
55 |
+
x, y = abs(n), []
|
56 |
+
while x >= b:
|
57 |
+
x, r = divmod(x, b)
|
58 |
+
y.append(r)
|
59 |
+
y.append(x)
|
60 |
+
y.append(-b if n < 0 else b)
|
61 |
+
y.reverse()
|
62 |
+
ndig = len(y) - 1
|
63 |
+
if digits is not None:
|
64 |
+
if ndig > digits:
|
65 |
+
raise ValueError(
|
66 |
+
"For %s, at least %s digits are needed." % (n, ndig))
|
67 |
+
elif ndig < digits:
|
68 |
+
y[1:1] = [0]*(digits - ndig)
|
69 |
+
return y
|
70 |
+
|
71 |
+
|
72 |
+
def count_digits(n, b=10):
|
73 |
+
"""
|
74 |
+
Return a dictionary whose keys are the digits of ``n`` in the
|
75 |
+
given base, ``b``, with keys indicating the digits appearing in the
|
76 |
+
number and values indicating how many times that digit appeared.
|
77 |
+
|
78 |
+
Examples
|
79 |
+
========
|
80 |
+
|
81 |
+
>>> from sympy.ntheory import count_digits
|
82 |
+
|
83 |
+
>>> count_digits(1111339)
|
84 |
+
{1: 4, 3: 2, 9: 1}
|
85 |
+
|
86 |
+
The digits returned are always represented in base-10
|
87 |
+
but the number itself can be entered in any format that is
|
88 |
+
understood by Python; the base of the number can also be
|
89 |
+
given if it is different than 10:
|
90 |
+
|
91 |
+
>>> n = 0xFA; n
|
92 |
+
250
|
93 |
+
>>> count_digits(_)
|
94 |
+
{0: 1, 2: 1, 5: 1}
|
95 |
+
>>> count_digits(n, 16)
|
96 |
+
{10: 1, 15: 1}
|
97 |
+
|
98 |
+
The default dictionary will return a 0 for any digit that did
|
99 |
+
not appear in the number. For example, which digits appear 7
|
100 |
+
times in ``77!``:
|
101 |
+
|
102 |
+
>>> from sympy import factorial
|
103 |
+
>>> c77 = count_digits(factorial(77))
|
104 |
+
>>> [i for i in range(10) if c77[i] == 7]
|
105 |
+
[1, 3, 7, 9]
|
106 |
+
"""
|
107 |
+
rv = defaultdict(int, multiset(digits(n, b)).items())
|
108 |
+
rv.pop(b) if b in rv else rv.pop(-b) # b or -b is there
|
109 |
+
return rv
|
110 |
+
|
111 |
+
|
112 |
+
def is_palindromic(n, b=10):
|
113 |
+
"""return True if ``n`` is the same when read from left to right
|
114 |
+
or right to left in the given base, ``b``.
|
115 |
+
|
116 |
+
Examples
|
117 |
+
========
|
118 |
+
|
119 |
+
>>> from sympy.ntheory import is_palindromic
|
120 |
+
|
121 |
+
>>> all(is_palindromic(i) for i in (-11, 1, 22, 121))
|
122 |
+
True
|
123 |
+
|
124 |
+
The second argument allows you to test numbers in other
|
125 |
+
bases. For example, 88 is palindromic in base-10 but not
|
126 |
+
in base-8:
|
127 |
+
|
128 |
+
>>> is_palindromic(88, 8)
|
129 |
+
False
|
130 |
+
|
131 |
+
On the other hand, a number can be palindromic in base-8 but
|
132 |
+
not in base-10:
|
133 |
+
|
134 |
+
>>> 0o121, is_palindromic(0o121)
|
135 |
+
(81, False)
|
136 |
+
|
137 |
+
Or it might be palindromic in both bases:
|
138 |
+
|
139 |
+
>>> oct(121), is_palindromic(121, 8) and is_palindromic(121)
|
140 |
+
('0o171', True)
|
141 |
+
|
142 |
+
"""
|
143 |
+
return _palindromic(digits(n, b), 1)
|
env-llmeval/lib/python3.10/site-packages/sympy/ntheory/elliptic_curve.py
ADDED
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import oo
|
2 |
+
from sympy.core.relational import Eq
|
3 |
+
from sympy.core.symbol import symbols
|
4 |
+
from sympy.polys.domains import FiniteField, QQ, RationalField, FF
|
5 |
+
from sympy.solvers.solvers import solve
|
6 |
+
from sympy.utilities.iterables import is_sequence
|
7 |
+
from sympy.utilities.misc import as_int
|
8 |
+
from .factor_ import divisors
|
9 |
+
from .residue_ntheory import polynomial_congruence
|
10 |
+
|
11 |
+
|
12 |
+
|
13 |
+
class EllipticCurve:
|
14 |
+
"""
|
15 |
+
Create the following Elliptic Curve over domain.
|
16 |
+
|
17 |
+
`y^{2} + a_{1} x y + a_{3} y = x^{3} + a_{2} x^{2} + a_{4} x + a_{6}`
|
18 |
+
|
19 |
+
The default domain is ``QQ``. If no coefficient ``a1``, ``a2``, ``a3``,
|
20 |
+
it create curve as following form.
|
21 |
+
|
22 |
+
`y^{2} = x^{3} + a_{4} x + a_{6}`
|
23 |
+
|
24 |
+
Examples
|
25 |
+
========
|
26 |
+
|
27 |
+
References
|
28 |
+
==========
|
29 |
+
|
30 |
+
.. [1] J. Silverman "A Friendly Introduction to Number Theory" Third Edition
|
31 |
+
.. [2] https://mathworld.wolfram.com/EllipticDiscriminant.html
|
32 |
+
.. [3] G. Hardy, E. Wright "An Introduction to the Theory of Numbers" Sixth Edition
|
33 |
+
|
34 |
+
"""
|
35 |
+
|
36 |
+
def __init__(self, a4, a6, a1=0, a2=0, a3=0, modulus = 0):
|
37 |
+
if modulus == 0:
|
38 |
+
domain = QQ
|
39 |
+
else:
|
40 |
+
domain = FF(modulus)
|
41 |
+
a1, a2, a3, a4, a6 = map(domain.convert, (a1, a2, a3, a4, a6))
|
42 |
+
self._domain = domain
|
43 |
+
self.modulus = modulus
|
44 |
+
# Calculate discriminant
|
45 |
+
b2 = a1**2 + 4 * a2
|
46 |
+
b4 = 2 * a4 + a1 * a3
|
47 |
+
b6 = a3**2 + 4 * a6
|
48 |
+
b8 = a1**2 * a6 + 4 * a2 * a6 - a1 * a3 * a4 + a2 * a3**2 - a4**2
|
49 |
+
self._b2, self._b4, self._b6, self._b8 = b2, b4, b6, b8
|
50 |
+
self._discrim = -b2**2 * b8 - 8 * b4**3 - 27 * b6**2 + 9 * b2 * b4 * b6
|
51 |
+
self._a1 = a1
|
52 |
+
self._a2 = a2
|
53 |
+
self._a3 = a3
|
54 |
+
self._a4 = a4
|
55 |
+
self._a6 = a6
|
56 |
+
x, y, z = symbols('x y z')
|
57 |
+
self.x, self.y, self.z = x, y, z
|
58 |
+
self._eq = Eq(y**2*z + a1*x*y*z + a3*y*z**2, x**3 + a2*x**2*z + a4*x*z**2 + a6*z**3)
|
59 |
+
if isinstance(self._domain, FiniteField):
|
60 |
+
self._rank = 0
|
61 |
+
elif isinstance(self._domain, RationalField):
|
62 |
+
self._rank = None
|
63 |
+
|
64 |
+
def __call__(self, x, y, z=1):
|
65 |
+
return EllipticCurvePoint(x, y, z, self)
|
66 |
+
|
67 |
+
def __contains__(self, point):
|
68 |
+
if is_sequence(point):
|
69 |
+
if len(point) == 2:
|
70 |
+
z1 = 1
|
71 |
+
else:
|
72 |
+
z1 = point[2]
|
73 |
+
x1, y1 = point[:2]
|
74 |
+
elif isinstance(point, EllipticCurvePoint):
|
75 |
+
x1, y1, z1 = point.x, point.y, point.z
|
76 |
+
else:
|
77 |
+
raise ValueError('Invalid point.')
|
78 |
+
if self.characteristic == 0 and z1 == 0:
|
79 |
+
return True
|
80 |
+
return self._eq.subs({self.x: x1, self.y: y1, self.z: z1})
|
81 |
+
|
82 |
+
def __repr__(self):
|
83 |
+
return 'E({}): {}'.format(self._domain, self._eq)
|
84 |
+
|
85 |
+
def minimal(self):
|
86 |
+
"""
|
87 |
+
Return minimal Weierstrass equation.
|
88 |
+
|
89 |
+
Examples
|
90 |
+
========
|
91 |
+
|
92 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
93 |
+
|
94 |
+
>>> e1 = EllipticCurve(-10, -20, 0, -1, 1)
|
95 |
+
>>> e1.minimal()
|
96 |
+
E(QQ): Eq(y**2*z, x**3 - 13392*x*z**2 - 1080432*z**3)
|
97 |
+
|
98 |
+
"""
|
99 |
+
char = self.characteristic
|
100 |
+
if char == 2:
|
101 |
+
return self
|
102 |
+
if char == 3:
|
103 |
+
return EllipticCurve(self._b4/2, self._b6/4, a2=self._b2/4, modulus=self.modulus)
|
104 |
+
c4 = self._b2**2 - 24*self._b4
|
105 |
+
c6 = -self._b2**3 + 36*self._b2*self._b4 - 216*self._b6
|
106 |
+
return EllipticCurve(-27*c4, -54*c6, modulus=self.modulus)
|
107 |
+
|
108 |
+
def points(self):
|
109 |
+
"""
|
110 |
+
Return points of curve over Finite Field.
|
111 |
+
|
112 |
+
Examples
|
113 |
+
========
|
114 |
+
|
115 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
116 |
+
>>> e2 = EllipticCurve(1, 1, 1, 1, 1, modulus=5)
|
117 |
+
>>> e2.points()
|
118 |
+
{(0, 2), (1, 4), (2, 0), (2, 2), (3, 0), (3, 1), (4, 0)}
|
119 |
+
|
120 |
+
"""
|
121 |
+
|
122 |
+
char = self.characteristic
|
123 |
+
all_pt = set()
|
124 |
+
if char >= 1:
|
125 |
+
for i in range(char):
|
126 |
+
congruence_eq = ((self._eq.lhs - self._eq.rhs).subs({self.x: i, self.z: 1}))
|
127 |
+
sol = polynomial_congruence(congruence_eq, char)
|
128 |
+
for num in sol:
|
129 |
+
all_pt.add((i, num))
|
130 |
+
return all_pt
|
131 |
+
else:
|
132 |
+
raise ValueError("Infinitely many points")
|
133 |
+
|
134 |
+
def points_x(self, x):
|
135 |
+
"Returns points on with curve where xcoordinate = x"
|
136 |
+
pt = []
|
137 |
+
if self._domain == QQ:
|
138 |
+
for y in solve(self._eq.subs(self.x, x)):
|
139 |
+
pt.append((x, y))
|
140 |
+
congruence_eq = ((self._eq.lhs - self._eq.rhs).subs({self.x: x, self.z: 1}))
|
141 |
+
for y in polynomial_congruence(congruence_eq, self.characteristic):
|
142 |
+
pt.append((x, y))
|
143 |
+
return pt
|
144 |
+
|
145 |
+
def torsion_points(self):
|
146 |
+
"""
|
147 |
+
Return torsion points of curve over Rational number.
|
148 |
+
|
149 |
+
Return point objects those are finite order.
|
150 |
+
According to Nagell-Lutz theorem, torsion point p(x, y)
|
151 |
+
x and y are integers, either y = 0 or y**2 is divisor
|
152 |
+
of discriminent. According to Mazur's theorem, there are
|
153 |
+
at most 15 points in torsion collection.
|
154 |
+
|
155 |
+
Examples
|
156 |
+
========
|
157 |
+
|
158 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
159 |
+
>>> e2 = EllipticCurve(-43, 166)
|
160 |
+
>>> sorted(e2.torsion_points())
|
161 |
+
[(-5, -16), (-5, 16), O, (3, -8), (3, 8), (11, -32), (11, 32)]
|
162 |
+
|
163 |
+
"""
|
164 |
+
if self.characteristic > 0:
|
165 |
+
raise ValueError("No torsion point for Finite Field.")
|
166 |
+
l = [EllipticCurvePoint.point_at_infinity(self)]
|
167 |
+
for xx in solve(self._eq.subs({self.y: 0, self.z: 1})):
|
168 |
+
if xx.is_rational:
|
169 |
+
l.append(self(xx, 0))
|
170 |
+
for i in divisors(self.discriminant, generator=True):
|
171 |
+
j = int(i**.5)
|
172 |
+
if j**2 == i:
|
173 |
+
for xx in solve(self._eq.subs({self.y: j, self.z: 1})):
|
174 |
+
if not xx.is_rational:
|
175 |
+
continue
|
176 |
+
p = self(xx, j)
|
177 |
+
if p.order() != oo:
|
178 |
+
l.extend([p, -p])
|
179 |
+
return l
|
180 |
+
|
181 |
+
@property
|
182 |
+
def characteristic(self):
|
183 |
+
"""
|
184 |
+
Return domain characteristic.
|
185 |
+
|
186 |
+
Examples
|
187 |
+
========
|
188 |
+
|
189 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
190 |
+
>>> e2 = EllipticCurve(-43, 166)
|
191 |
+
>>> e2.characteristic
|
192 |
+
0
|
193 |
+
|
194 |
+
"""
|
195 |
+
return self._domain.characteristic()
|
196 |
+
|
197 |
+
@property
|
198 |
+
def discriminant(self):
|
199 |
+
"""
|
200 |
+
Return curve discriminant.
|
201 |
+
|
202 |
+
Examples
|
203 |
+
========
|
204 |
+
|
205 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
206 |
+
>>> e2 = EllipticCurve(0, 17)
|
207 |
+
>>> e2.discriminant
|
208 |
+
-124848
|
209 |
+
|
210 |
+
"""
|
211 |
+
return int(self._discrim)
|
212 |
+
|
213 |
+
@property
|
214 |
+
def is_singular(self):
|
215 |
+
"""
|
216 |
+
Return True if curve discriminant is equal to zero.
|
217 |
+
"""
|
218 |
+
return self.discriminant == 0
|
219 |
+
|
220 |
+
@property
|
221 |
+
def j_invariant(self):
|
222 |
+
"""
|
223 |
+
Return curve j-invariant.
|
224 |
+
|
225 |
+
Examples
|
226 |
+
========
|
227 |
+
|
228 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
229 |
+
>>> e1 = EllipticCurve(-2, 0, 0, 1, 1)
|
230 |
+
>>> e1.j_invariant
|
231 |
+
1404928/389
|
232 |
+
|
233 |
+
"""
|
234 |
+
c4 = self._b2**2 - 24*self._b4
|
235 |
+
return self._domain.to_sympy(c4**3 / self._discrim)
|
236 |
+
|
237 |
+
@property
|
238 |
+
def order(self):
|
239 |
+
"""
|
240 |
+
Number of points in Finite field.
|
241 |
+
|
242 |
+
Examples
|
243 |
+
========
|
244 |
+
|
245 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
246 |
+
>>> e2 = EllipticCurve(1, 0, modulus=19)
|
247 |
+
>>> e2.order
|
248 |
+
19
|
249 |
+
|
250 |
+
"""
|
251 |
+
if self.characteristic == 0:
|
252 |
+
raise NotImplementedError("Still not implemented")
|
253 |
+
return len(self.points())
|
254 |
+
|
255 |
+
@property
|
256 |
+
def rank(self):
|
257 |
+
"""
|
258 |
+
Number of independent points of infinite order.
|
259 |
+
|
260 |
+
For Finite field, it must be 0.
|
261 |
+
"""
|
262 |
+
if self._rank is not None:
|
263 |
+
return self._rank
|
264 |
+
raise NotImplementedError("Still not implemented")
|
265 |
+
|
266 |
+
|
267 |
+
class EllipticCurvePoint:
|
268 |
+
"""
|
269 |
+
Point of Elliptic Curve
|
270 |
+
|
271 |
+
Examples
|
272 |
+
========
|
273 |
+
|
274 |
+
>>> from sympy.ntheory.elliptic_curve import EllipticCurve
|
275 |
+
>>> e1 = EllipticCurve(-17, 16)
|
276 |
+
>>> p1 = e1(0, -4, 1)
|
277 |
+
>>> p2 = e1(1, 0)
|
278 |
+
>>> p1 + p2
|
279 |
+
(15, -56)
|
280 |
+
>>> e3 = EllipticCurve(-1, 9)
|
281 |
+
>>> e3(1, -3) * 3
|
282 |
+
(664/169, 17811/2197)
|
283 |
+
>>> (e3(1, -3) * 3).order()
|
284 |
+
oo
|
285 |
+
>>> e2 = EllipticCurve(-2, 0, 0, 1, 1)
|
286 |
+
>>> p = e2(-1,1)
|
287 |
+
>>> q = e2(0, -1)
|
288 |
+
>>> p+q
|
289 |
+
(4, 8)
|
290 |
+
>>> p-q
|
291 |
+
(1, 0)
|
292 |
+
>>> 3*p-5*q
|
293 |
+
(328/361, -2800/6859)
|
294 |
+
"""
|
295 |
+
|
296 |
+
@staticmethod
|
297 |
+
def point_at_infinity(curve):
|
298 |
+
return EllipticCurvePoint(0, 1, 0, curve)
|
299 |
+
|
300 |
+
def __init__(self, x, y, z, curve):
|
301 |
+
dom = curve._domain.convert
|
302 |
+
self.x = dom(x)
|
303 |
+
self.y = dom(y)
|
304 |
+
self.z = dom(z)
|
305 |
+
self._curve = curve
|
306 |
+
self._domain = self._curve._domain
|
307 |
+
if not self._curve.__contains__(self):
|
308 |
+
raise ValueError("The curve does not contain this point")
|
309 |
+
|
310 |
+
def __add__(self, p):
|
311 |
+
if self.z == 0:
|
312 |
+
return p
|
313 |
+
if p.z == 0:
|
314 |
+
return self
|
315 |
+
x1, y1 = self.x/self.z, self.y/self.z
|
316 |
+
x2, y2 = p.x/p.z, p.y/p.z
|
317 |
+
a1 = self._curve._a1
|
318 |
+
a2 = self._curve._a2
|
319 |
+
a3 = self._curve._a3
|
320 |
+
a4 = self._curve._a4
|
321 |
+
a6 = self._curve._a6
|
322 |
+
if x1 != x2:
|
323 |
+
slope = (y1 - y2) / (x1 - x2)
|
324 |
+
yint = (y1 * x2 - y2 * x1) / (x2 - x1)
|
325 |
+
else:
|
326 |
+
if (y1 + y2) == 0:
|
327 |
+
return self.point_at_infinity(self._curve)
|
328 |
+
slope = (3 * x1**2 + 2*a2*x1 + a4 - a1*y1) / (a1 * x1 + a3 + 2 * y1)
|
329 |
+
yint = (-x1**3 + a4*x1 + 2*a6 - a3*y1) / (a1*x1 + a3 + 2*y1)
|
330 |
+
x3 = slope**2 + a1*slope - a2 - x1 - x2
|
331 |
+
y3 = -(slope + a1) * x3 - yint - a3
|
332 |
+
return self._curve(x3, y3, 1)
|
333 |
+
|
334 |
+
def __lt__(self, other):
|
335 |
+
return (self.x, self.y, self.z) < (other.x, other.y, other.z)
|
336 |
+
|
337 |
+
def __mul__(self, n):
|
338 |
+
n = as_int(n)
|
339 |
+
r = self.point_at_infinity(self._curve)
|
340 |
+
if n == 0:
|
341 |
+
return r
|
342 |
+
if n < 0:
|
343 |
+
return -self * -n
|
344 |
+
p = self
|
345 |
+
while n:
|
346 |
+
if n & 1:
|
347 |
+
r = r + p
|
348 |
+
n >>= 1
|
349 |
+
p = p + p
|
350 |
+
return r
|
351 |
+
|
352 |
+
def __rmul__(self, n):
|
353 |
+
return self * n
|
354 |
+
|
355 |
+
def __neg__(self):
|
356 |
+
return EllipticCurvePoint(self.x, -self.y - self._curve._a1*self.x - self._curve._a3, self.z, self._curve)
|
357 |
+
|
358 |
+
def __repr__(self):
|
359 |
+
if self.z == 0:
|
360 |
+
return 'O'
|
361 |
+
dom = self._curve._domain
|
362 |
+
try:
|
363 |
+
return '({}, {})'.format(dom.to_sympy(self.x), dom.to_sympy(self.y))
|
364 |
+
except TypeError:
|
365 |
+
pass
|
366 |
+
return '({}, {})'.format(self.x, self.y)
|
367 |
+
|
368 |
+
def __sub__(self, other):
|
369 |
+
return self.__add__(-other)
|
370 |
+
|
371 |
+
def order(self):
|
372 |
+
"""
|
373 |
+
Return point order n where nP = 0.
|
374 |
+
|
375 |
+
"""
|
376 |
+
if self.z == 0:
|
377 |
+
return 1
|
378 |
+
if self.y == 0: # P = -P
|
379 |
+
return 2
|
380 |
+
p = self * 2
|
381 |
+
if p.y == -self.y: # 2P = -P
|
382 |
+
return 3
|
383 |
+
i = 2
|
384 |
+
if self._domain != QQ:
|
385 |
+
while int(p.x) == p.x and int(p.y) == p.y:
|
386 |
+
p = self + p
|
387 |
+
i += 1
|
388 |
+
if p.z == 0:
|
389 |
+
return i
|
390 |
+
return oo
|
391 |
+
while p.x.numerator == p.x and p.y.numerator == p.y:
|
392 |
+
p = self + p
|
393 |
+
i += 1
|
394 |
+
if i > 12:
|
395 |
+
return oo
|
396 |
+
if p.z == 0:
|
397 |
+
return i
|
398 |
+
return oo
|
env-llmeval/lib/python3.10/site-packages/sympy/ntheory/multinomial.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.utilities.misc import as_int
|
2 |
+
|
3 |
+
|
4 |
+
def binomial_coefficients(n):
|
5 |
+
"""Return a dictionary containing pairs :math:`{(k1,k2) : C_kn}` where
|
6 |
+
:math:`C_kn` are binomial coefficients and :math:`n=k1+k2`.
|
7 |
+
|
8 |
+
Examples
|
9 |
+
========
|
10 |
+
|
11 |
+
>>> from sympy.ntheory import binomial_coefficients
|
12 |
+
>>> binomial_coefficients(9)
|
13 |
+
{(0, 9): 1, (1, 8): 9, (2, 7): 36, (3, 6): 84,
|
14 |
+
(4, 5): 126, (5, 4): 126, (6, 3): 84, (7, 2): 36, (8, 1): 9, (9, 0): 1}
|
15 |
+
|
16 |
+
See Also
|
17 |
+
========
|
18 |
+
|
19 |
+
binomial_coefficients_list, multinomial_coefficients
|
20 |
+
"""
|
21 |
+
n = as_int(n)
|
22 |
+
d = {(0, n): 1, (n, 0): 1}
|
23 |
+
a = 1
|
24 |
+
for k in range(1, n//2 + 1):
|
25 |
+
a = (a * (n - k + 1))//k
|
26 |
+
d[k, n - k] = d[n - k, k] = a
|
27 |
+
return d
|
28 |
+
|
29 |
+
|
30 |
+
def binomial_coefficients_list(n):
|
31 |
+
""" Return a list of binomial coefficients as rows of the Pascal's
|
32 |
+
triangle.
|
33 |
+
|
34 |
+
Examples
|
35 |
+
========
|
36 |
+
|
37 |
+
>>> from sympy.ntheory import binomial_coefficients_list
|
38 |
+
>>> binomial_coefficients_list(9)
|
39 |
+
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
|
40 |
+
|
41 |
+
See Also
|
42 |
+
========
|
43 |
+
|
44 |
+
binomial_coefficients, multinomial_coefficients
|
45 |
+
"""
|
46 |
+
n = as_int(n)
|
47 |
+
d = [1] * (n + 1)
|
48 |
+
a = 1
|
49 |
+
for k in range(1, n//2 + 1):
|
50 |
+
a = (a * (n - k + 1))//k
|
51 |
+
d[k] = d[n - k] = a
|
52 |
+
return d
|
53 |
+
|
54 |
+
|
55 |
+
def multinomial_coefficients(m, n):
|
56 |
+
r"""Return a dictionary containing pairs ``{(k1,k2,..,km) : C_kn}``
|
57 |
+
where ``C_kn`` are multinomial coefficients such that
|
58 |
+
``n=k1+k2+..+km``.
|
59 |
+
|
60 |
+
Examples
|
61 |
+
========
|
62 |
+
|
63 |
+
>>> from sympy.ntheory import multinomial_coefficients
|
64 |
+
>>> multinomial_coefficients(2, 5) # indirect doctest
|
65 |
+
{(0, 5): 1, (1, 4): 5, (2, 3): 10, (3, 2): 10, (4, 1): 5, (5, 0): 1}
|
66 |
+
|
67 |
+
Notes
|
68 |
+
=====
|
69 |
+
|
70 |
+
The algorithm is based on the following result:
|
71 |
+
|
72 |
+
.. math::
|
73 |
+
\binom{n}{k_1, \ldots, k_m} =
|
74 |
+
\frac{k_1 + 1}{n - k_1} \sum_{i=2}^m \binom{n}{k_1 + 1, \ldots, k_i - 1, \ldots}
|
75 |
+
|
76 |
+
Code contributed to Sage by Yann Laigle-Chapuy, copied with permission
|
77 |
+
of the author.
|
78 |
+
|
79 |
+
See Also
|
80 |
+
========
|
81 |
+
|
82 |
+
binomial_coefficients_list, binomial_coefficients
|
83 |
+
"""
|
84 |
+
m = as_int(m)
|
85 |
+
n = as_int(n)
|
86 |
+
if not m:
|
87 |
+
if n:
|
88 |
+
return {}
|
89 |
+
return {(): 1}
|
90 |
+
if m == 2:
|
91 |
+
return binomial_coefficients(n)
|
92 |
+
if m >= 2*n and n > 1:
|
93 |
+
return dict(multinomial_coefficients_iterator(m, n))
|
94 |
+
t = [n] + [0] * (m - 1)
|
95 |
+
r = {tuple(t): 1}
|
96 |
+
if n:
|
97 |
+
j = 0 # j will be the leftmost nonzero position
|
98 |
+
else:
|
99 |
+
j = m
|
100 |
+
# enumerate tuples in co-lex order
|
101 |
+
while j < m - 1:
|
102 |
+
# compute next tuple
|
103 |
+
tj = t[j]
|
104 |
+
if j:
|
105 |
+
t[j] = 0
|
106 |
+
t[0] = tj
|
107 |
+
if tj > 1:
|
108 |
+
t[j + 1] += 1
|
109 |
+
j = 0
|
110 |
+
start = 1
|
111 |
+
v = 0
|
112 |
+
else:
|
113 |
+
j += 1
|
114 |
+
start = j + 1
|
115 |
+
v = r[tuple(t)]
|
116 |
+
t[j] += 1
|
117 |
+
# compute the value
|
118 |
+
# NB: the initialization of v was done above
|
119 |
+
for k in range(start, m):
|
120 |
+
if t[k]:
|
121 |
+
t[k] -= 1
|
122 |
+
v += r[tuple(t)]
|
123 |
+
t[k] += 1
|
124 |
+
t[0] -= 1
|
125 |
+
r[tuple(t)] = (v * tj) // (n - t[0])
|
126 |
+
return r
|
127 |
+
|
128 |
+
|
129 |
+
def multinomial_coefficients_iterator(m, n, _tuple=tuple):
|
130 |
+
"""multinomial coefficient iterator
|
131 |
+
|
132 |
+
This routine has been optimized for `m` large with respect to `n` by taking
|
133 |
+
advantage of the fact that when the monomial tuples `t` are stripped of
|
134 |
+
zeros, their coefficient is the same as that of the monomial tuples from
|
135 |
+
``multinomial_coefficients(n, n)``. Therefore, the latter coefficients are
|
136 |
+
precomputed to save memory and time.
|
137 |
+
|
138 |
+
>>> from sympy.ntheory.multinomial import multinomial_coefficients
|
139 |
+
>>> m53, m33 = multinomial_coefficients(5,3), multinomial_coefficients(3,3)
|
140 |
+
>>> m53[(0,0,0,1,2)] == m53[(0,0,1,0,2)] == m53[(1,0,2,0,0)] == m33[(0,1,2)]
|
141 |
+
True
|
142 |
+
|
143 |
+
Examples
|
144 |
+
========
|
145 |
+
|
146 |
+
>>> from sympy.ntheory.multinomial import multinomial_coefficients_iterator
|
147 |
+
>>> it = multinomial_coefficients_iterator(20,3)
|
148 |
+
>>> next(it)
|
149 |
+
((3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), 1)
|
150 |
+
"""
|
151 |
+
m = as_int(m)
|
152 |
+
n = as_int(n)
|
153 |
+
if m < 2*n or n == 1:
|
154 |
+
mc = multinomial_coefficients(m, n)
|
155 |
+
yield from mc.items()
|
156 |
+
else:
|
157 |
+
mc = multinomial_coefficients(n, n)
|
158 |
+
mc1 = {}
|
159 |
+
for k, v in mc.items():
|
160 |
+
mc1[_tuple(filter(None, k))] = v
|
161 |
+
mc = mc1
|
162 |
+
|
163 |
+
t = [n] + [0] * (m - 1)
|
164 |
+
t1 = _tuple(t)
|
165 |
+
b = _tuple(filter(None, t1))
|
166 |
+
yield (t1, mc[b])
|
167 |
+
if n:
|
168 |
+
j = 0 # j will be the leftmost nonzero position
|
169 |
+
else:
|
170 |
+
j = m
|
171 |
+
# enumerate tuples in co-lex order
|
172 |
+
while j < m - 1:
|
173 |
+
# compute next tuple
|
174 |
+
tj = t[j]
|
175 |
+
if j:
|
176 |
+
t[j] = 0
|
177 |
+
t[0] = tj
|
178 |
+
if tj > 1:
|
179 |
+
t[j + 1] += 1
|
180 |
+
j = 0
|
181 |
+
else:
|
182 |
+
j += 1
|
183 |
+
t[j] += 1
|
184 |
+
|
185 |
+
t[0] -= 1
|
186 |
+
t1 = _tuple(t)
|
187 |
+
b = _tuple(filter(None, t1))
|
188 |
+
yield (t1, mc[b])
|
env-llmeval/lib/python3.10/site-packages/sympy/ntheory/partitions_.py
ADDED
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from mpmath.libmp import (fzero, from_int, from_rational,
|
2 |
+
fone, fhalf, bitcount, to_int, to_str, mpf_mul, mpf_div, mpf_sub,
|
3 |
+
mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin)
|
4 |
+
from sympy.core.numbers import igcd
|
5 |
+
from .residue_ntheory import (_sqrt_mod_prime_power,
|
6 |
+
legendre_symbol, jacobi_symbol, is_quad_residue)
|
7 |
+
|
8 |
+
import math
|
9 |
+
|
10 |
+
def _pre():
|
11 |
+
maxn = 10**5
|
12 |
+
global _factor
|
13 |
+
global _totient
|
14 |
+
_factor = [0]*maxn
|
15 |
+
_totient = [1]*maxn
|
16 |
+
lim = int(maxn**0.5) + 5
|
17 |
+
for i in range(2, lim):
|
18 |
+
if _factor[i] == 0:
|
19 |
+
for j in range(i*i, maxn, i):
|
20 |
+
if _factor[j] == 0:
|
21 |
+
_factor[j] = i
|
22 |
+
for i in range(2, maxn):
|
23 |
+
if _factor[i] == 0:
|
24 |
+
_factor[i] = i
|
25 |
+
_totient[i] = i-1
|
26 |
+
continue
|
27 |
+
x = _factor[i]
|
28 |
+
y = i//x
|
29 |
+
if y % x == 0:
|
30 |
+
_totient[i] = _totient[y]*x
|
31 |
+
else:
|
32 |
+
_totient[i] = _totient[y]*(x - 1)
|
33 |
+
|
34 |
+
def _a(n, k, prec):
|
35 |
+
""" Compute the inner sum in HRR formula [1]_
|
36 |
+
|
37 |
+
References
|
38 |
+
==========
|
39 |
+
|
40 |
+
.. [1] https://msp.org/pjm/1956/6-1/pjm-v6-n1-p18-p.pdf
|
41 |
+
|
42 |
+
"""
|
43 |
+
if k == 1:
|
44 |
+
return fone
|
45 |
+
|
46 |
+
k1 = k
|
47 |
+
e = 0
|
48 |
+
p = _factor[k]
|
49 |
+
while k1 % p == 0:
|
50 |
+
k1 //= p
|
51 |
+
e += 1
|
52 |
+
k2 = k//k1 # k2 = p^e
|
53 |
+
v = 1 - 24*n
|
54 |
+
pi = mpf_pi(prec)
|
55 |
+
|
56 |
+
if k1 == 1:
|
57 |
+
# k = p^e
|
58 |
+
if p == 2:
|
59 |
+
mod = 8*k
|
60 |
+
v = mod + v % mod
|
61 |
+
v = (v*pow(9, k - 1, mod)) % mod
|
62 |
+
m = _sqrt_mod_prime_power(v, 2, e + 3)[0]
|
63 |
+
arg = mpf_div(mpf_mul(
|
64 |
+
from_int(4*m), pi, prec), from_int(mod), prec)
|
65 |
+
return mpf_mul(mpf_mul(
|
66 |
+
from_int((-1)**e*jacobi_symbol(m - 1, m)),
|
67 |
+
mpf_sqrt(from_int(k), prec), prec),
|
68 |
+
mpf_sin(arg, prec), prec)
|
69 |
+
if p == 3:
|
70 |
+
mod = 3*k
|
71 |
+
v = mod + v % mod
|
72 |
+
if e > 1:
|
73 |
+
v = (v*pow(64, k//3 - 1, mod)) % mod
|
74 |
+
m = _sqrt_mod_prime_power(v, 3, e + 1)[0]
|
75 |
+
arg = mpf_div(mpf_mul(from_int(4*m), pi, prec),
|
76 |
+
from_int(mod), prec)
|
77 |
+
return mpf_mul(mpf_mul(
|
78 |
+
from_int(2*(-1)**(e + 1)*legendre_symbol(m, 3)),
|
79 |
+
mpf_sqrt(from_int(k//3), prec), prec),
|
80 |
+
mpf_sin(arg, prec), prec)
|
81 |
+
v = k + v % k
|
82 |
+
if v % p == 0:
|
83 |
+
if e == 1:
|
84 |
+
return mpf_mul(
|
85 |
+
from_int(jacobi_symbol(3, k)),
|
86 |
+
mpf_sqrt(from_int(k), prec), prec)
|
87 |
+
return fzero
|
88 |
+
if not is_quad_residue(v, p):
|
89 |
+
return fzero
|
90 |
+
_phi = p**(e - 1)*(p - 1)
|
91 |
+
v = (v*pow(576, _phi - 1, k))
|
92 |
+
m = _sqrt_mod_prime_power(v, p, e)[0]
|
93 |
+
arg = mpf_div(
|
94 |
+
mpf_mul(from_int(4*m), pi, prec),
|
95 |
+
from_int(k), prec)
|
96 |
+
return mpf_mul(mpf_mul(
|
97 |
+
from_int(2*jacobi_symbol(3, k)),
|
98 |
+
mpf_sqrt(from_int(k), prec), prec),
|
99 |
+
mpf_cos(arg, prec), prec)
|
100 |
+
|
101 |
+
if p != 2 or e >= 3:
|
102 |
+
d1, d2 = igcd(k1, 24), igcd(k2, 24)
|
103 |
+
e = 24//(d1*d2)
|
104 |
+
n1 = ((d2*e*n + (k2**2 - 1)//d1)*
|
105 |
+
pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1
|
106 |
+
n2 = ((d1*e*n + (k1**2 - 1)//d2)*
|
107 |
+
pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2
|
108 |
+
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
|
109 |
+
if e == 2:
|
110 |
+
n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1
|
111 |
+
n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4
|
112 |
+
return mpf_mul(mpf_mul(
|
113 |
+
from_int(-1),
|
114 |
+
_a(n1, k1, prec), prec),
|
115 |
+
_a(n2, k2, prec))
|
116 |
+
n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1
|
117 |
+
n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2
|
118 |
+
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
|
119 |
+
|
120 |
+
def _d(n, j, prec, sq23pi, sqrt8):
|
121 |
+
"""
|
122 |
+
Compute the sinh term in the outer sum of the HRR formula.
|
123 |
+
The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
|
124 |
+
"""
|
125 |
+
j = from_int(j)
|
126 |
+
pi = mpf_pi(prec)
|
127 |
+
a = mpf_div(sq23pi, j, prec)
|
128 |
+
b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec)
|
129 |
+
c = mpf_sqrt(b, prec)
|
130 |
+
ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec)
|
131 |
+
D = mpf_div(
|
132 |
+
mpf_sqrt(j, prec),
|
133 |
+
mpf_mul(mpf_mul(sqrt8, b), pi), prec)
|
134 |
+
E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec)
|
135 |
+
return mpf_mul(D, E)
|
136 |
+
|
137 |
+
|
138 |
+
def npartitions(n, verbose=False):
|
139 |
+
"""
|
140 |
+
Calculate the partition function P(n), i.e. the number of ways that
|
141 |
+
n can be written as a sum of positive integers.
|
142 |
+
|
143 |
+
P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_.
|
144 |
+
|
145 |
+
|
146 |
+
The correctness of this implementation has been tested through $10^{10}$.
|
147 |
+
|
148 |
+
Examples
|
149 |
+
========
|
150 |
+
|
151 |
+
>>> from sympy.ntheory import npartitions
|
152 |
+
>>> npartitions(25)
|
153 |
+
1958
|
154 |
+
|
155 |
+
References
|
156 |
+
==========
|
157 |
+
|
158 |
+
.. [1] https://mathworld.wolfram.com/PartitionFunctionP.html
|
159 |
+
|
160 |
+
"""
|
161 |
+
n = int(n)
|
162 |
+
if n < 0:
|
163 |
+
return 0
|
164 |
+
if n <= 5:
|
165 |
+
return [1, 1, 2, 3, 5, 7][n]
|
166 |
+
if '_factor' not in globals():
|
167 |
+
_pre()
|
168 |
+
# Estimate number of bits in p(n). This formula could be tidied
|
169 |
+
pbits = int((
|
170 |
+
math.pi*(2*n/3.)**0.5 -
|
171 |
+
math.log(4*n))/math.log(10) + 1) * \
|
172 |
+
math.log(10, 2)
|
173 |
+
prec = p = int(pbits*1.1 + 100)
|
174 |
+
s = fzero
|
175 |
+
M = max(6, int(0.24*n**0.5 + 4))
|
176 |
+
if M > 10**5:
|
177 |
+
raise ValueError("Input too big") # Corresponds to n > 1.7e11
|
178 |
+
sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p)
|
179 |
+
sqrt8 = mpf_sqrt(from_int(8), p)
|
180 |
+
for q in range(1, M):
|
181 |
+
a = _a(n, q, p)
|
182 |
+
d = _d(n, q, p, sq23pi, sqrt8)
|
183 |
+
s = mpf_add(s, mpf_mul(a, d), prec)
|
184 |
+
if verbose:
|
185 |
+
print("step", q, "of", M, to_str(a, 10), to_str(d, 10))
|
186 |
+
# On average, the terms decrease rapidly in magnitude.
|
187 |
+
# Dynamically reducing the precision greatly improves
|
188 |
+
# performance.
|
189 |
+
p = bitcount(abs(to_int(d))) + 50
|
190 |
+
return int(to_int(mpf_add(s, fhalf, prec)))
|
191 |
+
|
192 |
+
__all__ = ['npartitions']
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (183 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_approximants.cpython-310.pyc
ADDED
Binary file (1.92 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_demidovich.cpython-310.pyc
ADDED
Binary file (6.27 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_formal.cpython-310.pyc
ADDED
Binary file (24.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_kauers.cpython-310.pyc
ADDED
Binary file (1.48 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_limitseq.cpython-310.pyc
ADDED
Binary file (7.57 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_lseries.cpython-310.pyc
ADDED
Binary file (2.74 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_nseries.cpython-310.pyc
ADDED
Binary file (26.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_order.cpython-310.pyc
ADDED
Binary file (20.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_sequences.cpython-310.pyc
ADDED
Binary file (12.2 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/series/tests/__pycache__/test_series.cpython-310.pyc
ADDED
Binary file (18.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/__init__.py
ADDED
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
SymPy statistics module
|
3 |
+
|
4 |
+
Introduces a random variable type into the SymPy language.
|
5 |
+
|
6 |
+
Random variables may be declared using prebuilt functions such as
|
7 |
+
Normal, Exponential, Coin, Die, etc... or built with functions like FiniteRV.
|
8 |
+
|
9 |
+
Queries on random expressions can be made using the functions
|
10 |
+
|
11 |
+
========================= =============================
|
12 |
+
Expression Meaning
|
13 |
+
------------------------- -----------------------------
|
14 |
+
``P(condition)`` Probability
|
15 |
+
``E(expression)`` Expected value
|
16 |
+
``H(expression)`` Entropy
|
17 |
+
``variance(expression)`` Variance
|
18 |
+
``density(expression)`` Probability Density Function
|
19 |
+
``sample(expression)`` Produce a realization
|
20 |
+
``where(condition)`` Where the condition is true
|
21 |
+
========================= =============================
|
22 |
+
|
23 |
+
Examples
|
24 |
+
========
|
25 |
+
|
26 |
+
>>> from sympy.stats import P, E, variance, Die, Normal
|
27 |
+
>>> from sympy import simplify
|
28 |
+
>>> X, Y = Die('X', 6), Die('Y', 6) # Define two six sided dice
|
29 |
+
>>> Z = Normal('Z', 0, 1) # Declare a Normal random variable with mean 0, std 1
|
30 |
+
>>> P(X>3) # Probability X is greater than 3
|
31 |
+
1/2
|
32 |
+
>>> E(X+Y) # Expectation of the sum of two dice
|
33 |
+
7
|
34 |
+
>>> variance(X+Y) # Variance of the sum of two dice
|
35 |
+
35/6
|
36 |
+
>>> simplify(P(Z>1)) # Probability of Z being greater than 1
|
37 |
+
1/2 - erf(sqrt(2)/2)/2
|
38 |
+
|
39 |
+
|
40 |
+
One could also create custom distribution and define custom random variables
|
41 |
+
as follows:
|
42 |
+
|
43 |
+
1. If you want to create a Continuous Random Variable:
|
44 |
+
|
45 |
+
>>> from sympy.stats import ContinuousRV, P, E
|
46 |
+
>>> from sympy import exp, Symbol, Interval, oo
|
47 |
+
>>> x = Symbol('x')
|
48 |
+
>>> pdf = exp(-x) # pdf of the Continuous Distribution
|
49 |
+
>>> Z = ContinuousRV(x, pdf, set=Interval(0, oo))
|
50 |
+
>>> E(Z)
|
51 |
+
1
|
52 |
+
>>> P(Z > 5)
|
53 |
+
exp(-5)
|
54 |
+
|
55 |
+
1.1 To create an instance of Continuous Distribution:
|
56 |
+
|
57 |
+
>>> from sympy.stats import ContinuousDistributionHandmade
|
58 |
+
>>> from sympy import Lambda
|
59 |
+
>>> dist = ContinuousDistributionHandmade(Lambda(x, pdf), set=Interval(0, oo))
|
60 |
+
>>> dist.pdf(x)
|
61 |
+
exp(-x)
|
62 |
+
|
63 |
+
2. If you want to create a Discrete Random Variable:
|
64 |
+
|
65 |
+
>>> from sympy.stats import DiscreteRV, P, E
|
66 |
+
>>> from sympy import Symbol, S
|
67 |
+
>>> p = S(1)/2
|
68 |
+
>>> x = Symbol('x', integer=True, positive=True)
|
69 |
+
>>> pdf = p*(1 - p)**(x - 1)
|
70 |
+
>>> D = DiscreteRV(x, pdf, set=S.Naturals)
|
71 |
+
>>> E(D)
|
72 |
+
2
|
73 |
+
>>> P(D > 3)
|
74 |
+
1/8
|
75 |
+
|
76 |
+
2.1 To create an instance of Discrete Distribution:
|
77 |
+
|
78 |
+
>>> from sympy.stats import DiscreteDistributionHandmade
|
79 |
+
>>> from sympy import Lambda
|
80 |
+
>>> dist = DiscreteDistributionHandmade(Lambda(x, pdf), set=S.Naturals)
|
81 |
+
>>> dist.pdf(x)
|
82 |
+
2**(1 - x)/2
|
83 |
+
|
84 |
+
3. If you want to create a Finite Random Variable:
|
85 |
+
|
86 |
+
>>> from sympy.stats import FiniteRV, P, E
|
87 |
+
>>> from sympy import Rational, Eq
|
88 |
+
>>> pmf = {1: Rational(1, 3), 2: Rational(1, 6), 3: Rational(1, 4), 4: Rational(1, 4)}
|
89 |
+
>>> X = FiniteRV('X', pmf)
|
90 |
+
>>> E(X)
|
91 |
+
29/12
|
92 |
+
>>> P(X > 3)
|
93 |
+
1/4
|
94 |
+
|
95 |
+
3.1 To create an instance of Finite Distribution:
|
96 |
+
|
97 |
+
>>> from sympy.stats import FiniteDistributionHandmade
|
98 |
+
>>> dist = FiniteDistributionHandmade(pmf)
|
99 |
+
>>> dist.pmf(x)
|
100 |
+
Lambda(x, Piecewise((1/3, Eq(x, 1)), (1/6, Eq(x, 2)), (1/4, Eq(x, 3) | Eq(x, 4)), (0, True)))
|
101 |
+
"""
|
102 |
+
|
103 |
+
__all__ = [
|
104 |
+
'P', 'E', 'H', 'density', 'where', 'given', 'sample', 'cdf','median',
|
105 |
+
'characteristic_function', 'pspace', 'sample_iter', 'variance', 'std',
|
106 |
+
'skewness', 'kurtosis', 'covariance', 'dependent', 'entropy', 'independent',
|
107 |
+
'random_symbols', 'correlation', 'factorial_moment', 'moment', 'cmoment',
|
108 |
+
'sampling_density', 'moment_generating_function', 'smoment', 'quantile',
|
109 |
+
'coskewness', 'sample_stochastic_process',
|
110 |
+
|
111 |
+
'FiniteRV', 'DiscreteUniform', 'Die', 'Bernoulli', 'Coin', 'Binomial',
|
112 |
+
'BetaBinomial', 'Hypergeometric', 'Rademacher', 'IdealSoliton', 'RobustSoliton',
|
113 |
+
'FiniteDistributionHandmade',
|
114 |
+
|
115 |
+
'ContinuousRV', 'Arcsin', 'Benini', 'Beta', 'BetaNoncentral', 'BetaPrime',
|
116 |
+
'BoundedPareto', 'Cauchy', 'Chi', 'ChiNoncentral', 'ChiSquared', 'Dagum', 'Erlang',
|
117 |
+
'ExGaussian', 'Exponential', 'ExponentialPower', 'FDistribution',
|
118 |
+
'FisherZ', 'Frechet', 'Gamma', 'GammaInverse', 'Gompertz', 'Gumbel',
|
119 |
+
'Kumaraswamy', 'Laplace', 'Levy', 'Logistic','LogCauchy', 'LogLogistic', 'LogitNormal', 'LogNormal', 'Lomax',
|
120 |
+
'Moyal', 'Maxwell', 'Nakagami', 'Normal', 'GaussianInverse', 'Pareto', 'PowerFunction',
|
121 |
+
'QuadraticU', 'RaisedCosine', 'Rayleigh','Reciprocal', 'StudentT', 'ShiftedGompertz',
|
122 |
+
'Trapezoidal', 'Triangular', 'Uniform', 'UniformSum', 'VonMises', 'Wald',
|
123 |
+
'Weibull', 'WignerSemicircle', 'ContinuousDistributionHandmade',
|
124 |
+
|
125 |
+
'FlorySchulz', 'Geometric','Hermite', 'Logarithmic', 'NegativeBinomial', 'Poisson', 'Skellam',
|
126 |
+
'YuleSimon', 'Zeta', 'DiscreteRV', 'DiscreteDistributionHandmade',
|
127 |
+
|
128 |
+
'JointRV', 'Dirichlet', 'GeneralizedMultivariateLogGamma',
|
129 |
+
'GeneralizedMultivariateLogGammaOmega', 'Multinomial', 'MultivariateBeta',
|
130 |
+
'MultivariateEwens', 'MultivariateT', 'NegativeMultinomial',
|
131 |
+
'NormalGamma', 'MultivariateNormal', 'MultivariateLaplace', 'marginal_distribution',
|
132 |
+
|
133 |
+
'StochasticProcess', 'DiscreteTimeStochasticProcess',
|
134 |
+
'DiscreteMarkovChain', 'TransitionMatrixOf', 'StochasticStateSpaceOf',
|
135 |
+
'GeneratorMatrixOf', 'ContinuousMarkovChain', 'BernoulliProcess',
|
136 |
+
'PoissonProcess', 'WienerProcess', 'GammaProcess',
|
137 |
+
|
138 |
+
'CircularEnsemble', 'CircularUnitaryEnsemble',
|
139 |
+
'CircularOrthogonalEnsemble', 'CircularSymplecticEnsemble',
|
140 |
+
'GaussianEnsemble', 'GaussianUnitaryEnsemble',
|
141 |
+
'GaussianOrthogonalEnsemble', 'GaussianSymplecticEnsemble',
|
142 |
+
'joint_eigen_distribution', 'JointEigenDistribution',
|
143 |
+
'level_spacing_distribution',
|
144 |
+
|
145 |
+
'MatrixGamma', 'Wishart', 'MatrixNormal', 'MatrixStudentT',
|
146 |
+
|
147 |
+
'Probability', 'Expectation', 'Variance', 'Covariance', 'Moment',
|
148 |
+
'CentralMoment',
|
149 |
+
|
150 |
+
'ExpectationMatrix', 'VarianceMatrix', 'CrossCovarianceMatrix'
|
151 |
+
|
152 |
+
]
|
153 |
+
from .rv_interface import (P, E, H, density, where, given, sample, cdf, median,
|
154 |
+
characteristic_function, pspace, sample_iter, variance, std, skewness,
|
155 |
+
kurtosis, covariance, dependent, entropy, independent, random_symbols,
|
156 |
+
correlation, factorial_moment, moment, cmoment, sampling_density,
|
157 |
+
moment_generating_function, smoment, quantile, coskewness,
|
158 |
+
sample_stochastic_process)
|
159 |
+
|
160 |
+
from .frv_types import (FiniteRV, DiscreteUniform, Die, Bernoulli, Coin,
|
161 |
+
Binomial, BetaBinomial, Hypergeometric, Rademacher,
|
162 |
+
FiniteDistributionHandmade, IdealSoliton, RobustSoliton)
|
163 |
+
|
164 |
+
from .crv_types import (ContinuousRV, Arcsin, Benini, Beta, BetaNoncentral,
|
165 |
+
BetaPrime, BoundedPareto, Cauchy, Chi, ChiNoncentral, ChiSquared,
|
166 |
+
Dagum, Erlang, ExGaussian, Exponential, ExponentialPower,
|
167 |
+
FDistribution, FisherZ, Frechet, Gamma, GammaInverse, GaussianInverse,
|
168 |
+
Gompertz, Gumbel, Kumaraswamy, Laplace, Levy, Logistic, LogCauchy,
|
169 |
+
LogLogistic, LogitNormal, LogNormal, Lomax, Maxwell, Moyal, Nakagami,
|
170 |
+
Normal, Pareto, QuadraticU, RaisedCosine, Rayleigh, Reciprocal,
|
171 |
+
StudentT, PowerFunction, ShiftedGompertz, Trapezoidal, Triangular,
|
172 |
+
Uniform, UniformSum, VonMises, Wald, Weibull, WignerSemicircle,
|
173 |
+
ContinuousDistributionHandmade)
|
174 |
+
|
175 |
+
from .drv_types import (FlorySchulz, Geometric, Hermite, Logarithmic, NegativeBinomial, Poisson,
|
176 |
+
Skellam, YuleSimon, Zeta, DiscreteRV, DiscreteDistributionHandmade)
|
177 |
+
|
178 |
+
from .joint_rv_types import (JointRV, Dirichlet,
|
179 |
+
GeneralizedMultivariateLogGamma, GeneralizedMultivariateLogGammaOmega,
|
180 |
+
Multinomial, MultivariateBeta, MultivariateEwens, MultivariateT,
|
181 |
+
NegativeMultinomial, NormalGamma, MultivariateNormal, MultivariateLaplace,
|
182 |
+
marginal_distribution)
|
183 |
+
|
184 |
+
from .stochastic_process_types import (StochasticProcess,
|
185 |
+
DiscreteTimeStochasticProcess, DiscreteMarkovChain,
|
186 |
+
TransitionMatrixOf, StochasticStateSpaceOf, GeneratorMatrixOf,
|
187 |
+
ContinuousMarkovChain, BernoulliProcess, PoissonProcess, WienerProcess,
|
188 |
+
GammaProcess)
|
189 |
+
|
190 |
+
from .random_matrix_models import (CircularEnsemble, CircularUnitaryEnsemble,
|
191 |
+
CircularOrthogonalEnsemble, CircularSymplecticEnsemble,
|
192 |
+
GaussianEnsemble, GaussianUnitaryEnsemble, GaussianOrthogonalEnsemble,
|
193 |
+
GaussianSymplecticEnsemble, joint_eigen_distribution,
|
194 |
+
JointEigenDistribution, level_spacing_distribution)
|
195 |
+
|
196 |
+
from .matrix_distributions import MatrixGamma, Wishart, MatrixNormal, MatrixStudentT
|
197 |
+
|
198 |
+
from .symbolic_probability import (Probability, Expectation, Variance,
|
199 |
+
Covariance, Moment, CentralMoment)
|
200 |
+
|
201 |
+
from .symbolic_multivariate_probability import (ExpectationMatrix, VarianceMatrix,
|
202 |
+
CrossCovarianceMatrix)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/compound_rv.py
ADDED
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.summations import Sum
|
2 |
+
from sympy.core.basic import Basic
|
3 |
+
from sympy.core.function import Lambda
|
4 |
+
from sympy.core.symbol import Dummy
|
5 |
+
from sympy.integrals.integrals import Integral
|
6 |
+
from sympy.stats.rv import (NamedArgsMixin, random_symbols, _symbol_converter,
|
7 |
+
PSpace, RandomSymbol, is_random, Distribution)
|
8 |
+
from sympy.stats.crv import ContinuousDistribution, SingleContinuousPSpace
|
9 |
+
from sympy.stats.drv import DiscreteDistribution, SingleDiscretePSpace
|
10 |
+
from sympy.stats.frv import SingleFiniteDistribution, SingleFinitePSpace
|
11 |
+
from sympy.stats.crv_types import ContinuousDistributionHandmade
|
12 |
+
from sympy.stats.drv_types import DiscreteDistributionHandmade
|
13 |
+
from sympy.stats.frv_types import FiniteDistributionHandmade
|
14 |
+
|
15 |
+
|
16 |
+
class CompoundPSpace(PSpace):
|
17 |
+
"""
|
18 |
+
A temporary Probability Space for the Compound Distribution. After
|
19 |
+
Marginalization, this returns the corresponding Probability Space of the
|
20 |
+
parent distribution.
|
21 |
+
"""
|
22 |
+
|
23 |
+
def __new__(cls, s, distribution):
|
24 |
+
s = _symbol_converter(s)
|
25 |
+
if isinstance(distribution, ContinuousDistribution):
|
26 |
+
return SingleContinuousPSpace(s, distribution)
|
27 |
+
if isinstance(distribution, DiscreteDistribution):
|
28 |
+
return SingleDiscretePSpace(s, distribution)
|
29 |
+
if isinstance(distribution, SingleFiniteDistribution):
|
30 |
+
return SingleFinitePSpace(s, distribution)
|
31 |
+
if not isinstance(distribution, CompoundDistribution):
|
32 |
+
raise ValueError("%s should be an isinstance of "
|
33 |
+
"CompoundDistribution"%(distribution))
|
34 |
+
return Basic.__new__(cls, s, distribution)
|
35 |
+
|
36 |
+
@property
|
37 |
+
def value(self):
|
38 |
+
return RandomSymbol(self.symbol, self)
|
39 |
+
|
40 |
+
@property
|
41 |
+
def symbol(self):
|
42 |
+
return self.args[0]
|
43 |
+
|
44 |
+
@property
|
45 |
+
def is_Continuous(self):
|
46 |
+
return self.distribution.is_Continuous
|
47 |
+
|
48 |
+
@property
|
49 |
+
def is_Finite(self):
|
50 |
+
return self.distribution.is_Finite
|
51 |
+
|
52 |
+
@property
|
53 |
+
def is_Discrete(self):
|
54 |
+
return self.distribution.is_Discrete
|
55 |
+
|
56 |
+
@property
|
57 |
+
def distribution(self):
|
58 |
+
return self.args[1]
|
59 |
+
|
60 |
+
@property
|
61 |
+
def pdf(self):
|
62 |
+
return self.distribution.pdf(self.symbol)
|
63 |
+
|
64 |
+
@property
|
65 |
+
def set(self):
|
66 |
+
return self.distribution.set
|
67 |
+
|
68 |
+
@property
|
69 |
+
def domain(self):
|
70 |
+
return self._get_newpspace().domain
|
71 |
+
|
72 |
+
def _get_newpspace(self, evaluate=False):
|
73 |
+
x = Dummy('x')
|
74 |
+
parent_dist = self.distribution.args[0]
|
75 |
+
func = Lambda(x, self.distribution.pdf(x, evaluate))
|
76 |
+
new_pspace = self._transform_pspace(self.symbol, parent_dist, func)
|
77 |
+
if new_pspace is not None:
|
78 |
+
return new_pspace
|
79 |
+
message = ("Compound Distribution for %s is not implemented yet" % str(parent_dist))
|
80 |
+
raise NotImplementedError(message)
|
81 |
+
|
82 |
+
def _transform_pspace(self, sym, dist, pdf):
|
83 |
+
"""
|
84 |
+
This function returns the new pspace of the distribution using handmade
|
85 |
+
Distributions and their corresponding pspace.
|
86 |
+
"""
|
87 |
+
pdf = Lambda(sym, pdf(sym))
|
88 |
+
_set = dist.set
|
89 |
+
if isinstance(dist, ContinuousDistribution):
|
90 |
+
return SingleContinuousPSpace(sym, ContinuousDistributionHandmade(pdf, _set))
|
91 |
+
elif isinstance(dist, DiscreteDistribution):
|
92 |
+
return SingleDiscretePSpace(sym, DiscreteDistributionHandmade(pdf, _set))
|
93 |
+
elif isinstance(dist, SingleFiniteDistribution):
|
94 |
+
dens = {k: pdf(k) for k in _set}
|
95 |
+
return SingleFinitePSpace(sym, FiniteDistributionHandmade(dens))
|
96 |
+
|
97 |
+
def compute_density(self, expr, *, compound_evaluate=True, **kwargs):
|
98 |
+
new_pspace = self._get_newpspace(compound_evaluate)
|
99 |
+
expr = expr.subs({self.value: new_pspace.value})
|
100 |
+
return new_pspace.compute_density(expr, **kwargs)
|
101 |
+
|
102 |
+
def compute_cdf(self, expr, *, compound_evaluate=True, **kwargs):
|
103 |
+
new_pspace = self._get_newpspace(compound_evaluate)
|
104 |
+
expr = expr.subs({self.value: new_pspace.value})
|
105 |
+
return new_pspace.compute_cdf(expr, **kwargs)
|
106 |
+
|
107 |
+
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
|
108 |
+
new_pspace = self._get_newpspace(evaluate)
|
109 |
+
expr = expr.subs({self.value: new_pspace.value})
|
110 |
+
if rvs:
|
111 |
+
rvs = rvs.subs({self.value: new_pspace.value})
|
112 |
+
if isinstance(new_pspace, SingleFinitePSpace):
|
113 |
+
return new_pspace.compute_expectation(expr, rvs, **kwargs)
|
114 |
+
return new_pspace.compute_expectation(expr, rvs, evaluate, **kwargs)
|
115 |
+
|
116 |
+
def probability(self, condition, *, compound_evaluate=True, **kwargs):
|
117 |
+
new_pspace = self._get_newpspace(compound_evaluate)
|
118 |
+
condition = condition.subs({self.value: new_pspace.value})
|
119 |
+
return new_pspace.probability(condition)
|
120 |
+
|
121 |
+
def conditional_space(self, condition, *, compound_evaluate=True, **kwargs):
|
122 |
+
new_pspace = self._get_newpspace(compound_evaluate)
|
123 |
+
condition = condition.subs({self.value: new_pspace.value})
|
124 |
+
return new_pspace.conditional_space(condition)
|
125 |
+
|
126 |
+
|
127 |
+
class CompoundDistribution(Distribution, NamedArgsMixin):
|
128 |
+
"""
|
129 |
+
Class for Compound Distributions.
|
130 |
+
|
131 |
+
Parameters
|
132 |
+
==========
|
133 |
+
|
134 |
+
dist : Distribution
|
135 |
+
Distribution must contain a random parameter
|
136 |
+
|
137 |
+
Examples
|
138 |
+
========
|
139 |
+
|
140 |
+
>>> from sympy.stats.compound_rv import CompoundDistribution
|
141 |
+
>>> from sympy.stats.crv_types import NormalDistribution
|
142 |
+
>>> from sympy.stats import Normal
|
143 |
+
>>> from sympy.abc import x
|
144 |
+
>>> X = Normal('X', 2, 4)
|
145 |
+
>>> N = NormalDistribution(X, 4)
|
146 |
+
>>> C = CompoundDistribution(N)
|
147 |
+
>>> C.set
|
148 |
+
Interval(-oo, oo)
|
149 |
+
>>> C.pdf(x, evaluate=True).simplify()
|
150 |
+
exp(-x**2/64 + x/16 - 1/16)/(8*sqrt(pi))
|
151 |
+
|
152 |
+
References
|
153 |
+
==========
|
154 |
+
|
155 |
+
.. [1] https://en.wikipedia.org/wiki/Compound_probability_distribution
|
156 |
+
|
157 |
+
"""
|
158 |
+
|
159 |
+
def __new__(cls, dist):
|
160 |
+
if not isinstance(dist, (ContinuousDistribution,
|
161 |
+
SingleFiniteDistribution, DiscreteDistribution)):
|
162 |
+
message = "Compound Distribution for %s is not implemented yet" % str(dist)
|
163 |
+
raise NotImplementedError(message)
|
164 |
+
if not cls._compound_check(dist):
|
165 |
+
return dist
|
166 |
+
return Basic.__new__(cls, dist)
|
167 |
+
|
168 |
+
@property
|
169 |
+
def set(self):
|
170 |
+
return self.args[0].set
|
171 |
+
|
172 |
+
@property
|
173 |
+
def is_Continuous(self):
|
174 |
+
return isinstance(self.args[0], ContinuousDistribution)
|
175 |
+
|
176 |
+
@property
|
177 |
+
def is_Finite(self):
|
178 |
+
return isinstance(self.args[0], SingleFiniteDistribution)
|
179 |
+
|
180 |
+
@property
|
181 |
+
def is_Discrete(self):
|
182 |
+
return isinstance(self.args[0], DiscreteDistribution)
|
183 |
+
|
184 |
+
def pdf(self, x, evaluate=False):
|
185 |
+
dist = self.args[0]
|
186 |
+
randoms = [rv for rv in dist.args if is_random(rv)]
|
187 |
+
if isinstance(dist, SingleFiniteDistribution):
|
188 |
+
y = Dummy('y', integer=True, negative=False)
|
189 |
+
expr = dist.pmf(y)
|
190 |
+
else:
|
191 |
+
y = Dummy('y')
|
192 |
+
expr = dist.pdf(y)
|
193 |
+
for rv in randoms:
|
194 |
+
expr = self._marginalise(expr, rv, evaluate)
|
195 |
+
return Lambda(y, expr)(x)
|
196 |
+
|
197 |
+
def _marginalise(self, expr, rv, evaluate):
|
198 |
+
if isinstance(rv.pspace.distribution, SingleFiniteDistribution):
|
199 |
+
rv_dens = rv.pspace.distribution.pmf(rv)
|
200 |
+
else:
|
201 |
+
rv_dens = rv.pspace.distribution.pdf(rv)
|
202 |
+
rv_dom = rv.pspace.domain.set
|
203 |
+
if rv.pspace.is_Discrete or rv.pspace.is_Finite:
|
204 |
+
expr = Sum(expr*rv_dens, (rv, rv_dom._inf,
|
205 |
+
rv_dom._sup))
|
206 |
+
else:
|
207 |
+
expr = Integral(expr*rv_dens, (rv, rv_dom._inf,
|
208 |
+
rv_dom._sup))
|
209 |
+
if evaluate:
|
210 |
+
return expr.doit()
|
211 |
+
return expr
|
212 |
+
|
213 |
+
@classmethod
|
214 |
+
def _compound_check(self, dist):
|
215 |
+
"""
|
216 |
+
Checks if the given distribution contains random parameters.
|
217 |
+
"""
|
218 |
+
randoms = []
|
219 |
+
for arg in dist.args:
|
220 |
+
randoms.extend(random_symbols(arg))
|
221 |
+
if len(randoms) == 0:
|
222 |
+
return False
|
223 |
+
return True
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/crv.py
ADDED
@@ -0,0 +1,570 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Continuous Random Variables Module
|
3 |
+
|
4 |
+
See Also
|
5 |
+
========
|
6 |
+
sympy.stats.crv_types
|
7 |
+
sympy.stats.rv
|
8 |
+
sympy.stats.frv
|
9 |
+
"""
|
10 |
+
|
11 |
+
|
12 |
+
from sympy.core.basic import Basic
|
13 |
+
from sympy.core.cache import cacheit
|
14 |
+
from sympy.core.function import Lambda, PoleError
|
15 |
+
from sympy.core.numbers import (I, nan, oo)
|
16 |
+
from sympy.core.relational import (Eq, Ne)
|
17 |
+
from sympy.core.singleton import S
|
18 |
+
from sympy.core.symbol import (Dummy, symbols)
|
19 |
+
from sympy.core.sympify import _sympify, sympify
|
20 |
+
from sympy.functions.combinatorial.factorials import factorial
|
21 |
+
from sympy.functions.elementary.exponential import exp
|
22 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
23 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
24 |
+
from sympy.integrals.integrals import (Integral, integrate)
|
25 |
+
from sympy.logic.boolalg import (And, Or)
|
26 |
+
from sympy.polys.polyerrors import PolynomialError
|
27 |
+
from sympy.polys.polytools import poly
|
28 |
+
from sympy.series.series import series
|
29 |
+
from sympy.sets.sets import (FiniteSet, Intersection, Interval, Union)
|
30 |
+
from sympy.solvers.solveset import solveset
|
31 |
+
from sympy.solvers.inequalities import reduce_rational_inequalities
|
32 |
+
from sympy.stats.rv import (RandomDomain, SingleDomain, ConditionalDomain, is_random,
|
33 |
+
ProductDomain, PSpace, SinglePSpace, random_symbols, NamedArgsMixin, Distribution)
|
34 |
+
|
35 |
+
|
36 |
+
class ContinuousDomain(RandomDomain):
|
37 |
+
"""
|
38 |
+
A domain with continuous support
|
39 |
+
|
40 |
+
Represented using symbols and Intervals.
|
41 |
+
"""
|
42 |
+
is_Continuous = True
|
43 |
+
|
44 |
+
def as_boolean(self):
|
45 |
+
raise NotImplementedError("Not Implemented for generic Domains")
|
46 |
+
|
47 |
+
|
48 |
+
class SingleContinuousDomain(ContinuousDomain, SingleDomain):
|
49 |
+
"""
|
50 |
+
A univariate domain with continuous support
|
51 |
+
|
52 |
+
Represented using a single symbol and interval.
|
53 |
+
"""
|
54 |
+
def compute_expectation(self, expr, variables=None, **kwargs):
|
55 |
+
if variables is None:
|
56 |
+
variables = self.symbols
|
57 |
+
if not variables:
|
58 |
+
return expr
|
59 |
+
if frozenset(variables) != frozenset(self.symbols):
|
60 |
+
raise ValueError("Values should be equal")
|
61 |
+
# assumes only intervals
|
62 |
+
return Integral(expr, (self.symbol, self.set), **kwargs)
|
63 |
+
|
64 |
+
def as_boolean(self):
|
65 |
+
return self.set.as_relational(self.symbol)
|
66 |
+
|
67 |
+
|
68 |
+
class ProductContinuousDomain(ProductDomain, ContinuousDomain):
|
69 |
+
"""
|
70 |
+
A collection of independent domains with continuous support
|
71 |
+
"""
|
72 |
+
|
73 |
+
def compute_expectation(self, expr, variables=None, **kwargs):
|
74 |
+
if variables is None:
|
75 |
+
variables = self.symbols
|
76 |
+
for domain in self.domains:
|
77 |
+
domain_vars = frozenset(variables) & frozenset(domain.symbols)
|
78 |
+
if domain_vars:
|
79 |
+
expr = domain.compute_expectation(expr, domain_vars, **kwargs)
|
80 |
+
return expr
|
81 |
+
|
82 |
+
def as_boolean(self):
|
83 |
+
return And(*[domain.as_boolean() for domain in self.domains])
|
84 |
+
|
85 |
+
|
86 |
+
class ConditionalContinuousDomain(ContinuousDomain, ConditionalDomain):
|
87 |
+
"""
|
88 |
+
A domain with continuous support that has been further restricted by a
|
89 |
+
condition such as $x > 3$.
|
90 |
+
"""
|
91 |
+
|
92 |
+
def compute_expectation(self, expr, variables=None, **kwargs):
|
93 |
+
if variables is None:
|
94 |
+
variables = self.symbols
|
95 |
+
if not variables:
|
96 |
+
return expr
|
97 |
+
# Extract the full integral
|
98 |
+
fullintgrl = self.fulldomain.compute_expectation(expr, variables)
|
99 |
+
# separate into integrand and limits
|
100 |
+
integrand, limits = fullintgrl.function, list(fullintgrl.limits)
|
101 |
+
|
102 |
+
conditions = [self.condition]
|
103 |
+
while conditions:
|
104 |
+
cond = conditions.pop()
|
105 |
+
if cond.is_Boolean:
|
106 |
+
if isinstance(cond, And):
|
107 |
+
conditions.extend(cond.args)
|
108 |
+
elif isinstance(cond, Or):
|
109 |
+
raise NotImplementedError("Or not implemented here")
|
110 |
+
elif cond.is_Relational:
|
111 |
+
if cond.is_Equality:
|
112 |
+
# Add the appropriate Delta to the integrand
|
113 |
+
integrand *= DiracDelta(cond.lhs - cond.rhs)
|
114 |
+
else:
|
115 |
+
symbols = cond.free_symbols & set(self.symbols)
|
116 |
+
if len(symbols) != 1: # Can't handle x > y
|
117 |
+
raise NotImplementedError(
|
118 |
+
"Multivariate Inequalities not yet implemented")
|
119 |
+
# Can handle x > 0
|
120 |
+
symbol = symbols.pop()
|
121 |
+
# Find the limit with x, such as (x, -oo, oo)
|
122 |
+
for i, limit in enumerate(limits):
|
123 |
+
if limit[0] == symbol:
|
124 |
+
# Make condition into an Interval like [0, oo]
|
125 |
+
cintvl = reduce_rational_inequalities_wrap(
|
126 |
+
cond, symbol)
|
127 |
+
# Make limit into an Interval like [-oo, oo]
|
128 |
+
lintvl = Interval(limit[1], limit[2])
|
129 |
+
# Intersect them to get [0, oo]
|
130 |
+
intvl = cintvl.intersect(lintvl)
|
131 |
+
# Put back into limits list
|
132 |
+
limits[i] = (symbol, intvl.left, intvl.right)
|
133 |
+
else:
|
134 |
+
raise TypeError(
|
135 |
+
"Condition %s is not a relational or Boolean" % cond)
|
136 |
+
|
137 |
+
return Integral(integrand, *limits, **kwargs)
|
138 |
+
|
139 |
+
def as_boolean(self):
|
140 |
+
return And(self.fulldomain.as_boolean(), self.condition)
|
141 |
+
|
142 |
+
@property
|
143 |
+
def set(self):
|
144 |
+
if len(self.symbols) == 1:
|
145 |
+
return (self.fulldomain.set & reduce_rational_inequalities_wrap(
|
146 |
+
self.condition, tuple(self.symbols)[0]))
|
147 |
+
else:
|
148 |
+
raise NotImplementedError(
|
149 |
+
"Set of Conditional Domain not Implemented")
|
150 |
+
|
151 |
+
|
152 |
+
class ContinuousDistribution(Distribution):
|
153 |
+
def __call__(self, *args):
|
154 |
+
return self.pdf(*args)
|
155 |
+
|
156 |
+
|
157 |
+
class SingleContinuousDistribution(ContinuousDistribution, NamedArgsMixin):
|
158 |
+
""" Continuous distribution of a single variable.
|
159 |
+
|
160 |
+
Explanation
|
161 |
+
===========
|
162 |
+
|
163 |
+
Serves as superclass for Normal/Exponential/UniformDistribution etc....
|
164 |
+
|
165 |
+
Represented by parameters for each of the specific classes. E.g
|
166 |
+
NormalDistribution is represented by a mean and standard deviation.
|
167 |
+
|
168 |
+
Provides methods for pdf, cdf, and sampling.
|
169 |
+
|
170 |
+
See Also
|
171 |
+
========
|
172 |
+
|
173 |
+
sympy.stats.crv_types.*
|
174 |
+
"""
|
175 |
+
|
176 |
+
set = Interval(-oo, oo)
|
177 |
+
|
178 |
+
def __new__(cls, *args):
|
179 |
+
args = list(map(sympify, args))
|
180 |
+
return Basic.__new__(cls, *args)
|
181 |
+
|
182 |
+
@staticmethod
|
183 |
+
def check(*args):
|
184 |
+
pass
|
185 |
+
|
186 |
+
@cacheit
|
187 |
+
def compute_cdf(self, **kwargs):
|
188 |
+
""" Compute the CDF from the PDF.
|
189 |
+
|
190 |
+
Returns a Lambda.
|
191 |
+
"""
|
192 |
+
x, z = symbols('x, z', real=True, cls=Dummy)
|
193 |
+
left_bound = self.set.start
|
194 |
+
|
195 |
+
# CDF is integral of PDF from left bound to z
|
196 |
+
pdf = self.pdf(x)
|
197 |
+
cdf = integrate(pdf.doit(), (x, left_bound, z), **kwargs)
|
198 |
+
# CDF Ensure that CDF left of left_bound is zero
|
199 |
+
cdf = Piecewise((cdf, z >= left_bound), (0, True))
|
200 |
+
return Lambda(z, cdf)
|
201 |
+
|
202 |
+
def _cdf(self, x):
|
203 |
+
return None
|
204 |
+
|
205 |
+
def cdf(self, x, **kwargs):
|
206 |
+
""" Cumulative density function """
|
207 |
+
if len(kwargs) == 0:
|
208 |
+
cdf = self._cdf(x)
|
209 |
+
if cdf is not None:
|
210 |
+
return cdf
|
211 |
+
return self.compute_cdf(**kwargs)(x)
|
212 |
+
|
213 |
+
@cacheit
|
214 |
+
def compute_characteristic_function(self, **kwargs):
|
215 |
+
""" Compute the characteristic function from the PDF.
|
216 |
+
|
217 |
+
Returns a Lambda.
|
218 |
+
"""
|
219 |
+
x, t = symbols('x, t', real=True, cls=Dummy)
|
220 |
+
pdf = self.pdf(x)
|
221 |
+
cf = integrate(exp(I*t*x)*pdf, (x, self.set))
|
222 |
+
return Lambda(t, cf)
|
223 |
+
|
224 |
+
def _characteristic_function(self, t):
|
225 |
+
return None
|
226 |
+
|
227 |
+
def characteristic_function(self, t, **kwargs):
|
228 |
+
""" Characteristic function """
|
229 |
+
if len(kwargs) == 0:
|
230 |
+
cf = self._characteristic_function(t)
|
231 |
+
if cf is not None:
|
232 |
+
return cf
|
233 |
+
return self.compute_characteristic_function(**kwargs)(t)
|
234 |
+
|
235 |
+
@cacheit
|
236 |
+
def compute_moment_generating_function(self, **kwargs):
|
237 |
+
""" Compute the moment generating function from the PDF.
|
238 |
+
|
239 |
+
Returns a Lambda.
|
240 |
+
"""
|
241 |
+
x, t = symbols('x, t', real=True, cls=Dummy)
|
242 |
+
pdf = self.pdf(x)
|
243 |
+
mgf = integrate(exp(t * x) * pdf, (x, self.set))
|
244 |
+
return Lambda(t, mgf)
|
245 |
+
|
246 |
+
def _moment_generating_function(self, t):
|
247 |
+
return None
|
248 |
+
|
249 |
+
def moment_generating_function(self, t, **kwargs):
|
250 |
+
""" Moment generating function """
|
251 |
+
if not kwargs:
|
252 |
+
mgf = self._moment_generating_function(t)
|
253 |
+
if mgf is not None:
|
254 |
+
return mgf
|
255 |
+
return self.compute_moment_generating_function(**kwargs)(t)
|
256 |
+
|
257 |
+
def expectation(self, expr, var, evaluate=True, **kwargs):
|
258 |
+
""" Expectation of expression over distribution """
|
259 |
+
if evaluate:
|
260 |
+
try:
|
261 |
+
p = poly(expr, var)
|
262 |
+
if p.is_zero:
|
263 |
+
return S.Zero
|
264 |
+
t = Dummy('t', real=True)
|
265 |
+
mgf = self._moment_generating_function(t)
|
266 |
+
if mgf is None:
|
267 |
+
return integrate(expr * self.pdf(var), (var, self.set), **kwargs)
|
268 |
+
deg = p.degree()
|
269 |
+
taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t)
|
270 |
+
result = 0
|
271 |
+
for k in range(deg+1):
|
272 |
+
result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k)
|
273 |
+
return result
|
274 |
+
except PolynomialError:
|
275 |
+
return integrate(expr * self.pdf(var), (var, self.set), **kwargs)
|
276 |
+
else:
|
277 |
+
return Integral(expr * self.pdf(var), (var, self.set), **kwargs)
|
278 |
+
|
279 |
+
@cacheit
|
280 |
+
def compute_quantile(self, **kwargs):
|
281 |
+
""" Compute the Quantile from the PDF.
|
282 |
+
|
283 |
+
Returns a Lambda.
|
284 |
+
"""
|
285 |
+
x, p = symbols('x, p', real=True, cls=Dummy)
|
286 |
+
left_bound = self.set.start
|
287 |
+
|
288 |
+
pdf = self.pdf(x)
|
289 |
+
cdf = integrate(pdf, (x, left_bound, x), **kwargs)
|
290 |
+
quantile = solveset(cdf - p, x, self.set)
|
291 |
+
return Lambda(p, Piecewise((quantile, (p >= 0) & (p <= 1) ), (nan, True)))
|
292 |
+
|
293 |
+
def _quantile(self, x):
|
294 |
+
return None
|
295 |
+
|
296 |
+
def quantile(self, x, **kwargs):
|
297 |
+
""" Cumulative density function """
|
298 |
+
if len(kwargs) == 0:
|
299 |
+
quantile = self._quantile(x)
|
300 |
+
if quantile is not None:
|
301 |
+
return quantile
|
302 |
+
return self.compute_quantile(**kwargs)(x)
|
303 |
+
|
304 |
+
|
305 |
+
class ContinuousPSpace(PSpace):
|
306 |
+
""" Continuous Probability Space
|
307 |
+
|
308 |
+
Represents the likelihood of an event space defined over a continuum.
|
309 |
+
|
310 |
+
Represented with a ContinuousDomain and a PDF (Lambda-Like)
|
311 |
+
"""
|
312 |
+
|
313 |
+
is_Continuous = True
|
314 |
+
is_real = True
|
315 |
+
|
316 |
+
@property
|
317 |
+
def pdf(self):
|
318 |
+
return self.density(*self.domain.symbols)
|
319 |
+
|
320 |
+
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
|
321 |
+
if rvs is None:
|
322 |
+
rvs = self.values
|
323 |
+
else:
|
324 |
+
rvs = frozenset(rvs)
|
325 |
+
|
326 |
+
expr = expr.xreplace({rv: rv.symbol for rv in rvs})
|
327 |
+
|
328 |
+
domain_symbols = frozenset(rv.symbol for rv in rvs)
|
329 |
+
|
330 |
+
return self.domain.compute_expectation(self.pdf * expr,
|
331 |
+
domain_symbols, **kwargs)
|
332 |
+
|
333 |
+
def compute_density(self, expr, **kwargs):
|
334 |
+
# Common case Density(X) where X in self.values
|
335 |
+
if expr in self.values:
|
336 |
+
# Marginalize all other random symbols out of the density
|
337 |
+
randomsymbols = tuple(set(self.values) - frozenset([expr]))
|
338 |
+
symbols = tuple(rs.symbol for rs in randomsymbols)
|
339 |
+
pdf = self.domain.compute_expectation(self.pdf, symbols, **kwargs)
|
340 |
+
return Lambda(expr.symbol, pdf)
|
341 |
+
|
342 |
+
z = Dummy('z', real=True)
|
343 |
+
return Lambda(z, self.compute_expectation(DiracDelta(expr - z), **kwargs))
|
344 |
+
|
345 |
+
@cacheit
|
346 |
+
def compute_cdf(self, expr, **kwargs):
|
347 |
+
if not self.domain.set.is_Interval:
|
348 |
+
raise ValueError(
|
349 |
+
"CDF not well defined on multivariate expressions")
|
350 |
+
|
351 |
+
d = self.compute_density(expr, **kwargs)
|
352 |
+
x, z = symbols('x, z', real=True, cls=Dummy)
|
353 |
+
left_bound = self.domain.set.start
|
354 |
+
|
355 |
+
# CDF is integral of PDF from left bound to z
|
356 |
+
cdf = integrate(d(x), (x, left_bound, z), **kwargs)
|
357 |
+
# CDF Ensure that CDF left of left_bound is zero
|
358 |
+
cdf = Piecewise((cdf, z >= left_bound), (0, True))
|
359 |
+
return Lambda(z, cdf)
|
360 |
+
|
361 |
+
@cacheit
|
362 |
+
def compute_characteristic_function(self, expr, **kwargs):
|
363 |
+
if not self.domain.set.is_Interval:
|
364 |
+
raise NotImplementedError("Characteristic function of multivariate expressions not implemented")
|
365 |
+
|
366 |
+
d = self.compute_density(expr, **kwargs)
|
367 |
+
x, t = symbols('x, t', real=True, cls=Dummy)
|
368 |
+
cf = integrate(exp(I*t*x)*d(x), (x, -oo, oo), **kwargs)
|
369 |
+
return Lambda(t, cf)
|
370 |
+
|
371 |
+
@cacheit
|
372 |
+
def compute_moment_generating_function(self, expr, **kwargs):
|
373 |
+
if not self.domain.set.is_Interval:
|
374 |
+
raise NotImplementedError("Moment generating function of multivariate expressions not implemented")
|
375 |
+
|
376 |
+
d = self.compute_density(expr, **kwargs)
|
377 |
+
x, t = symbols('x, t', real=True, cls=Dummy)
|
378 |
+
mgf = integrate(exp(t * x) * d(x), (x, -oo, oo), **kwargs)
|
379 |
+
return Lambda(t, mgf)
|
380 |
+
|
381 |
+
@cacheit
|
382 |
+
def compute_quantile(self, expr, **kwargs):
|
383 |
+
if not self.domain.set.is_Interval:
|
384 |
+
raise ValueError(
|
385 |
+
"Quantile not well defined on multivariate expressions")
|
386 |
+
|
387 |
+
d = self.compute_cdf(expr, **kwargs)
|
388 |
+
x = Dummy('x', real=True)
|
389 |
+
p = Dummy('p', positive=True)
|
390 |
+
|
391 |
+
quantile = solveset(d(x) - p, x, self.set)
|
392 |
+
|
393 |
+
return Lambda(p, quantile)
|
394 |
+
|
395 |
+
def probability(self, condition, **kwargs):
|
396 |
+
z = Dummy('z', real=True)
|
397 |
+
cond_inv = False
|
398 |
+
if isinstance(condition, Ne):
|
399 |
+
condition = Eq(condition.args[0], condition.args[1])
|
400 |
+
cond_inv = True
|
401 |
+
# Univariate case can be handled by where
|
402 |
+
try:
|
403 |
+
domain = self.where(condition)
|
404 |
+
rv = [rv for rv in self.values if rv.symbol == domain.symbol][0]
|
405 |
+
# Integrate out all other random variables
|
406 |
+
pdf = self.compute_density(rv, **kwargs)
|
407 |
+
# return S.Zero if `domain` is empty set
|
408 |
+
if domain.set is S.EmptySet or isinstance(domain.set, FiniteSet):
|
409 |
+
return S.Zero if not cond_inv else S.One
|
410 |
+
if isinstance(domain.set, Union):
|
411 |
+
return sum(
|
412 |
+
Integral(pdf(z), (z, subset), **kwargs) for subset in
|
413 |
+
domain.set.args if isinstance(subset, Interval))
|
414 |
+
# Integrate out the last variable over the special domain
|
415 |
+
return Integral(pdf(z), (z, domain.set), **kwargs)
|
416 |
+
|
417 |
+
# Other cases can be turned into univariate case
|
418 |
+
# by computing a density handled by density computation
|
419 |
+
except NotImplementedError:
|
420 |
+
from sympy.stats.rv import density
|
421 |
+
expr = condition.lhs - condition.rhs
|
422 |
+
if not is_random(expr):
|
423 |
+
dens = self.density
|
424 |
+
comp = condition.rhs
|
425 |
+
else:
|
426 |
+
dens = density(expr, **kwargs)
|
427 |
+
comp = 0
|
428 |
+
if not isinstance(dens, ContinuousDistribution):
|
429 |
+
from sympy.stats.crv_types import ContinuousDistributionHandmade
|
430 |
+
dens = ContinuousDistributionHandmade(dens, set=self.domain.set)
|
431 |
+
# Turn problem into univariate case
|
432 |
+
space = SingleContinuousPSpace(z, dens)
|
433 |
+
result = space.probability(condition.__class__(space.value, comp))
|
434 |
+
return result if not cond_inv else S.One - result
|
435 |
+
|
436 |
+
def where(self, condition):
|
437 |
+
rvs = frozenset(random_symbols(condition))
|
438 |
+
if not (len(rvs) == 1 and rvs.issubset(self.values)):
|
439 |
+
raise NotImplementedError(
|
440 |
+
"Multiple continuous random variables not supported")
|
441 |
+
rv = tuple(rvs)[0]
|
442 |
+
interval = reduce_rational_inequalities_wrap(condition, rv)
|
443 |
+
interval = interval.intersect(self.domain.set)
|
444 |
+
return SingleContinuousDomain(rv.symbol, interval)
|
445 |
+
|
446 |
+
def conditional_space(self, condition, normalize=True, **kwargs):
|
447 |
+
condition = condition.xreplace({rv: rv.symbol for rv in self.values})
|
448 |
+
domain = ConditionalContinuousDomain(self.domain, condition)
|
449 |
+
if normalize:
|
450 |
+
# create a clone of the variable to
|
451 |
+
# make sure that variables in nested integrals are different
|
452 |
+
# from the variables outside the integral
|
453 |
+
# this makes sure that they are evaluated separately
|
454 |
+
# and in the correct order
|
455 |
+
replacement = {rv: Dummy(str(rv)) for rv in self.symbols}
|
456 |
+
norm = domain.compute_expectation(self.pdf, **kwargs)
|
457 |
+
pdf = self.pdf / norm.xreplace(replacement)
|
458 |
+
# XXX: Converting set to tuple. The order matters to Lambda though
|
459 |
+
# so we shouldn't be starting with a set here...
|
460 |
+
density = Lambda(tuple(domain.symbols), pdf)
|
461 |
+
|
462 |
+
return ContinuousPSpace(domain, density)
|
463 |
+
|
464 |
+
|
465 |
+
class SingleContinuousPSpace(ContinuousPSpace, SinglePSpace):
|
466 |
+
"""
|
467 |
+
A continuous probability space over a single univariate variable.
|
468 |
+
|
469 |
+
These consist of a Symbol and a SingleContinuousDistribution
|
470 |
+
|
471 |
+
This class is normally accessed through the various random variable
|
472 |
+
functions, Normal, Exponential, Uniform, etc....
|
473 |
+
"""
|
474 |
+
|
475 |
+
@property
|
476 |
+
def set(self):
|
477 |
+
return self.distribution.set
|
478 |
+
|
479 |
+
@property
|
480 |
+
def domain(self):
|
481 |
+
return SingleContinuousDomain(sympify(self.symbol), self.set)
|
482 |
+
|
483 |
+
def sample(self, size=(), library='scipy', seed=None):
|
484 |
+
"""
|
485 |
+
Internal sample method.
|
486 |
+
|
487 |
+
Returns dictionary mapping RandomSymbol to realization value.
|
488 |
+
"""
|
489 |
+
return {self.value: self.distribution.sample(size, library=library, seed=seed)}
|
490 |
+
|
491 |
+
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
|
492 |
+
rvs = rvs or (self.value,)
|
493 |
+
if self.value not in rvs:
|
494 |
+
return expr
|
495 |
+
|
496 |
+
expr = _sympify(expr)
|
497 |
+
expr = expr.xreplace({rv: rv.symbol for rv in rvs})
|
498 |
+
|
499 |
+
x = self.value.symbol
|
500 |
+
try:
|
501 |
+
return self.distribution.expectation(expr, x, evaluate=evaluate, **kwargs)
|
502 |
+
except PoleError:
|
503 |
+
return Integral(expr * self.pdf, (x, self.set), **kwargs)
|
504 |
+
|
505 |
+
def compute_cdf(self, expr, **kwargs):
|
506 |
+
if expr == self.value:
|
507 |
+
z = Dummy("z", real=True)
|
508 |
+
return Lambda(z, self.distribution.cdf(z, **kwargs))
|
509 |
+
else:
|
510 |
+
return ContinuousPSpace.compute_cdf(self, expr, **kwargs)
|
511 |
+
|
512 |
+
def compute_characteristic_function(self, expr, **kwargs):
|
513 |
+
if expr == self.value:
|
514 |
+
t = Dummy("t", real=True)
|
515 |
+
return Lambda(t, self.distribution.characteristic_function(t, **kwargs))
|
516 |
+
else:
|
517 |
+
return ContinuousPSpace.compute_characteristic_function(self, expr, **kwargs)
|
518 |
+
|
519 |
+
def compute_moment_generating_function(self, expr, **kwargs):
|
520 |
+
if expr == self.value:
|
521 |
+
t = Dummy("t", real=True)
|
522 |
+
return Lambda(t, self.distribution.moment_generating_function(t, **kwargs))
|
523 |
+
else:
|
524 |
+
return ContinuousPSpace.compute_moment_generating_function(self, expr, **kwargs)
|
525 |
+
|
526 |
+
def compute_density(self, expr, **kwargs):
|
527 |
+
# https://en.wikipedia.org/wiki/Random_variable#Functions_of_random_variables
|
528 |
+
if expr == self.value:
|
529 |
+
return self.density
|
530 |
+
y = Dummy('y', real=True)
|
531 |
+
|
532 |
+
gs = solveset(expr - y, self.value, S.Reals)
|
533 |
+
|
534 |
+
if isinstance(gs, Intersection) and S.Reals in gs.args:
|
535 |
+
gs = list(gs.args[1])
|
536 |
+
|
537 |
+
if not gs:
|
538 |
+
raise ValueError("Can not solve %s for %s"%(expr, self.value))
|
539 |
+
fx = self.compute_density(self.value)
|
540 |
+
fy = sum(fx(g) * abs(g.diff(y)) for g in gs)
|
541 |
+
return Lambda(y, fy)
|
542 |
+
|
543 |
+
def compute_quantile(self, expr, **kwargs):
|
544 |
+
|
545 |
+
if expr == self.value:
|
546 |
+
p = Dummy("p", real=True)
|
547 |
+
return Lambda(p, self.distribution.quantile(p, **kwargs))
|
548 |
+
else:
|
549 |
+
return ContinuousPSpace.compute_quantile(self, expr, **kwargs)
|
550 |
+
|
551 |
+
def _reduce_inequalities(conditions, var, **kwargs):
|
552 |
+
try:
|
553 |
+
return reduce_rational_inequalities(conditions, var, **kwargs)
|
554 |
+
except PolynomialError:
|
555 |
+
raise ValueError("Reduction of condition failed %s\n" % conditions[0])
|
556 |
+
|
557 |
+
|
558 |
+
def reduce_rational_inequalities_wrap(condition, var):
|
559 |
+
if condition.is_Relational:
|
560 |
+
return _reduce_inequalities([[condition]], var, relational=False)
|
561 |
+
if isinstance(condition, Or):
|
562 |
+
return Union(*[_reduce_inequalities([[arg]], var, relational=False)
|
563 |
+
for arg in condition.args])
|
564 |
+
if isinstance(condition, And):
|
565 |
+
intervals = [_reduce_inequalities([[arg]], var, relational=False)
|
566 |
+
for arg in condition.args]
|
567 |
+
I = intervals[0]
|
568 |
+
for i in intervals:
|
569 |
+
I = I.intersect(i)
|
570 |
+
return I
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/crv_types.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/drv.py
ADDED
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.summations import (Sum, summation)
|
2 |
+
from sympy.core.basic import Basic
|
3 |
+
from sympy.core.cache import cacheit
|
4 |
+
from sympy.core.function import Lambda
|
5 |
+
from sympy.core.numbers import I
|
6 |
+
from sympy.core.relational import (Eq, Ne)
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.core.symbol import (Dummy, symbols)
|
9 |
+
from sympy.core.sympify import sympify
|
10 |
+
from sympy.functions.combinatorial.factorials import factorial
|
11 |
+
from sympy.functions.elementary.exponential import exp
|
12 |
+
from sympy.functions.elementary.integers import floor
|
13 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
14 |
+
from sympy.logic.boolalg import And
|
15 |
+
from sympy.polys.polytools import poly
|
16 |
+
from sympy.series.series import series
|
17 |
+
|
18 |
+
from sympy.polys.polyerrors import PolynomialError
|
19 |
+
from sympy.stats.crv import reduce_rational_inequalities_wrap
|
20 |
+
from sympy.stats.rv import (NamedArgsMixin, SinglePSpace, SingleDomain,
|
21 |
+
random_symbols, PSpace, ConditionalDomain, RandomDomain,
|
22 |
+
ProductDomain, Distribution)
|
23 |
+
from sympy.stats.symbolic_probability import Probability
|
24 |
+
from sympy.sets.fancysets import Range, FiniteSet
|
25 |
+
from sympy.sets.sets import Union
|
26 |
+
from sympy.sets.contains import Contains
|
27 |
+
from sympy.utilities import filldedent
|
28 |
+
from sympy.core.sympify import _sympify
|
29 |
+
|
30 |
+
|
31 |
+
class DiscreteDistribution(Distribution):
|
32 |
+
def __call__(self, *args):
|
33 |
+
return self.pdf(*args)
|
34 |
+
|
35 |
+
|
36 |
+
class SingleDiscreteDistribution(DiscreteDistribution, NamedArgsMixin):
|
37 |
+
""" Discrete distribution of a single variable.
|
38 |
+
|
39 |
+
Serves as superclass for PoissonDistribution etc....
|
40 |
+
|
41 |
+
Provides methods for pdf, cdf, and sampling
|
42 |
+
|
43 |
+
See Also:
|
44 |
+
sympy.stats.crv_types.*
|
45 |
+
"""
|
46 |
+
|
47 |
+
set = S.Integers
|
48 |
+
|
49 |
+
def __new__(cls, *args):
|
50 |
+
args = list(map(sympify, args))
|
51 |
+
return Basic.__new__(cls, *args)
|
52 |
+
|
53 |
+
@staticmethod
|
54 |
+
def check(*args):
|
55 |
+
pass
|
56 |
+
|
57 |
+
@cacheit
|
58 |
+
def compute_cdf(self, **kwargs):
|
59 |
+
""" Compute the CDF from the PDF.
|
60 |
+
|
61 |
+
Returns a Lambda.
|
62 |
+
"""
|
63 |
+
x = symbols('x', integer=True, cls=Dummy)
|
64 |
+
z = symbols('z', real=True, cls=Dummy)
|
65 |
+
left_bound = self.set.inf
|
66 |
+
|
67 |
+
# CDF is integral of PDF from left bound to z
|
68 |
+
pdf = self.pdf(x)
|
69 |
+
cdf = summation(pdf, (x, left_bound, floor(z)), **kwargs)
|
70 |
+
# CDF Ensure that CDF left of left_bound is zero
|
71 |
+
cdf = Piecewise((cdf, z >= left_bound), (0, True))
|
72 |
+
return Lambda(z, cdf)
|
73 |
+
|
74 |
+
def _cdf(self, x):
|
75 |
+
return None
|
76 |
+
|
77 |
+
def cdf(self, x, **kwargs):
|
78 |
+
""" Cumulative density function """
|
79 |
+
if not kwargs:
|
80 |
+
cdf = self._cdf(x)
|
81 |
+
if cdf is not None:
|
82 |
+
return cdf
|
83 |
+
return self.compute_cdf(**kwargs)(x)
|
84 |
+
|
85 |
+
@cacheit
|
86 |
+
def compute_characteristic_function(self, **kwargs):
|
87 |
+
""" Compute the characteristic function from the PDF.
|
88 |
+
|
89 |
+
Returns a Lambda.
|
90 |
+
"""
|
91 |
+
x, t = symbols('x, t', real=True, cls=Dummy)
|
92 |
+
pdf = self.pdf(x)
|
93 |
+
cf = summation(exp(I*t*x)*pdf, (x, self.set.inf, self.set.sup))
|
94 |
+
return Lambda(t, cf)
|
95 |
+
|
96 |
+
def _characteristic_function(self, t):
|
97 |
+
return None
|
98 |
+
|
99 |
+
def characteristic_function(self, t, **kwargs):
|
100 |
+
""" Characteristic function """
|
101 |
+
if not kwargs:
|
102 |
+
cf = self._characteristic_function(t)
|
103 |
+
if cf is not None:
|
104 |
+
return cf
|
105 |
+
return self.compute_characteristic_function(**kwargs)(t)
|
106 |
+
|
107 |
+
@cacheit
|
108 |
+
def compute_moment_generating_function(self, **kwargs):
|
109 |
+
t = Dummy('t', real=True)
|
110 |
+
x = Dummy('x', integer=True)
|
111 |
+
pdf = self.pdf(x)
|
112 |
+
mgf = summation(exp(t*x)*pdf, (x, self.set.inf, self.set.sup))
|
113 |
+
return Lambda(t, mgf)
|
114 |
+
|
115 |
+
def _moment_generating_function(self, t):
|
116 |
+
return None
|
117 |
+
|
118 |
+
def moment_generating_function(self, t, **kwargs):
|
119 |
+
if not kwargs:
|
120 |
+
mgf = self._moment_generating_function(t)
|
121 |
+
if mgf is not None:
|
122 |
+
return mgf
|
123 |
+
return self.compute_moment_generating_function(**kwargs)(t)
|
124 |
+
|
125 |
+
@cacheit
|
126 |
+
def compute_quantile(self, **kwargs):
|
127 |
+
""" Compute the Quantile from the PDF.
|
128 |
+
|
129 |
+
Returns a Lambda.
|
130 |
+
"""
|
131 |
+
x = Dummy('x', integer=True)
|
132 |
+
p = Dummy('p', real=True)
|
133 |
+
left_bound = self.set.inf
|
134 |
+
pdf = self.pdf(x)
|
135 |
+
cdf = summation(pdf, (x, left_bound, x), **kwargs)
|
136 |
+
set = ((x, p <= cdf), )
|
137 |
+
return Lambda(p, Piecewise(*set))
|
138 |
+
|
139 |
+
def _quantile(self, x):
|
140 |
+
return None
|
141 |
+
|
142 |
+
def quantile(self, x, **kwargs):
|
143 |
+
""" Cumulative density function """
|
144 |
+
if not kwargs:
|
145 |
+
quantile = self._quantile(x)
|
146 |
+
if quantile is not None:
|
147 |
+
return quantile
|
148 |
+
return self.compute_quantile(**kwargs)(x)
|
149 |
+
|
150 |
+
def expectation(self, expr, var, evaluate=True, **kwargs):
|
151 |
+
""" Expectation of expression over distribution """
|
152 |
+
# TODO: support discrete sets with non integer stepsizes
|
153 |
+
|
154 |
+
if evaluate:
|
155 |
+
try:
|
156 |
+
p = poly(expr, var)
|
157 |
+
|
158 |
+
t = Dummy('t', real=True)
|
159 |
+
|
160 |
+
mgf = self.moment_generating_function(t)
|
161 |
+
deg = p.degree()
|
162 |
+
taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t)
|
163 |
+
result = 0
|
164 |
+
for k in range(deg+1):
|
165 |
+
result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k)
|
166 |
+
|
167 |
+
return result
|
168 |
+
|
169 |
+
except PolynomialError:
|
170 |
+
return summation(expr * self.pdf(var),
|
171 |
+
(var, self.set.inf, self.set.sup), **kwargs)
|
172 |
+
|
173 |
+
else:
|
174 |
+
return Sum(expr * self.pdf(var),
|
175 |
+
(var, self.set.inf, self.set.sup), **kwargs)
|
176 |
+
|
177 |
+
def __call__(self, *args):
|
178 |
+
return self.pdf(*args)
|
179 |
+
|
180 |
+
|
181 |
+
class DiscreteDomain(RandomDomain):
|
182 |
+
"""
|
183 |
+
A domain with discrete support with step size one.
|
184 |
+
Represented using symbols and Range.
|
185 |
+
"""
|
186 |
+
is_Discrete = True
|
187 |
+
|
188 |
+
class SingleDiscreteDomain(DiscreteDomain, SingleDomain):
|
189 |
+
def as_boolean(self):
|
190 |
+
return Contains(self.symbol, self.set)
|
191 |
+
|
192 |
+
|
193 |
+
class ConditionalDiscreteDomain(DiscreteDomain, ConditionalDomain):
|
194 |
+
"""
|
195 |
+
Domain with discrete support of step size one, that is restricted by
|
196 |
+
some condition.
|
197 |
+
"""
|
198 |
+
@property
|
199 |
+
def set(self):
|
200 |
+
rv = self.symbols
|
201 |
+
if len(self.symbols) > 1:
|
202 |
+
raise NotImplementedError(filldedent('''
|
203 |
+
Multivariate conditional domains are not yet implemented.'''))
|
204 |
+
rv = list(rv)[0]
|
205 |
+
return reduce_rational_inequalities_wrap(self.condition,
|
206 |
+
rv).intersect(self.fulldomain.set)
|
207 |
+
|
208 |
+
|
209 |
+
class DiscretePSpace(PSpace):
|
210 |
+
is_real = True
|
211 |
+
is_Discrete = True
|
212 |
+
|
213 |
+
@property
|
214 |
+
def pdf(self):
|
215 |
+
return self.density(*self.symbols)
|
216 |
+
|
217 |
+
def where(self, condition):
|
218 |
+
rvs = random_symbols(condition)
|
219 |
+
assert all(r.symbol in self.symbols for r in rvs)
|
220 |
+
if len(rvs) > 1:
|
221 |
+
raise NotImplementedError(filldedent('''Multivariate discrete
|
222 |
+
random variables are not yet supported.'''))
|
223 |
+
conditional_domain = reduce_rational_inequalities_wrap(condition,
|
224 |
+
rvs[0])
|
225 |
+
conditional_domain = conditional_domain.intersect(self.domain.set)
|
226 |
+
return SingleDiscreteDomain(rvs[0].symbol, conditional_domain)
|
227 |
+
|
228 |
+
def probability(self, condition):
|
229 |
+
complement = isinstance(condition, Ne)
|
230 |
+
if complement:
|
231 |
+
condition = Eq(condition.args[0], condition.args[1])
|
232 |
+
try:
|
233 |
+
_domain = self.where(condition).set
|
234 |
+
if condition == False or _domain is S.EmptySet:
|
235 |
+
return S.Zero
|
236 |
+
if condition == True or _domain == self.domain.set:
|
237 |
+
return S.One
|
238 |
+
prob = self.eval_prob(_domain)
|
239 |
+
except NotImplementedError:
|
240 |
+
from sympy.stats.rv import density
|
241 |
+
expr = condition.lhs - condition.rhs
|
242 |
+
dens = density(expr)
|
243 |
+
if not isinstance(dens, DiscreteDistribution):
|
244 |
+
from sympy.stats.drv_types import DiscreteDistributionHandmade
|
245 |
+
dens = DiscreteDistributionHandmade(dens)
|
246 |
+
z = Dummy('z', real=True)
|
247 |
+
space = SingleDiscretePSpace(z, dens)
|
248 |
+
prob = space.probability(condition.__class__(space.value, 0))
|
249 |
+
if prob is None:
|
250 |
+
prob = Probability(condition)
|
251 |
+
return prob if not complement else S.One - prob
|
252 |
+
|
253 |
+
def eval_prob(self, _domain):
|
254 |
+
sym = list(self.symbols)[0]
|
255 |
+
if isinstance(_domain, Range):
|
256 |
+
n = symbols('n', integer=True)
|
257 |
+
inf, sup, step = (r for r in _domain.args)
|
258 |
+
summand = ((self.pdf).replace(
|
259 |
+
sym, n*step))
|
260 |
+
rv = summation(summand,
|
261 |
+
(n, inf/step, (sup)/step - 1)).doit()
|
262 |
+
return rv
|
263 |
+
elif isinstance(_domain, FiniteSet):
|
264 |
+
pdf = Lambda(sym, self.pdf)
|
265 |
+
rv = sum(pdf(x) for x in _domain)
|
266 |
+
return rv
|
267 |
+
elif isinstance(_domain, Union):
|
268 |
+
rv = sum(self.eval_prob(x) for x in _domain.args)
|
269 |
+
return rv
|
270 |
+
|
271 |
+
def conditional_space(self, condition):
|
272 |
+
# XXX: Converting from set to tuple. The order matters to Lambda
|
273 |
+
# though so we should be starting with a set...
|
274 |
+
density = Lambda(tuple(self.symbols), self.pdf/self.probability(condition))
|
275 |
+
condition = condition.xreplace({rv: rv.symbol for rv in self.values})
|
276 |
+
domain = ConditionalDiscreteDomain(self.domain, condition)
|
277 |
+
return DiscretePSpace(domain, density)
|
278 |
+
|
279 |
+
class ProductDiscreteDomain(ProductDomain, DiscreteDomain):
|
280 |
+
def as_boolean(self):
|
281 |
+
return And(*[domain.as_boolean for domain in self.domains])
|
282 |
+
|
283 |
+
class SingleDiscretePSpace(DiscretePSpace, SinglePSpace):
|
284 |
+
""" Discrete probability space over a single univariate variable """
|
285 |
+
is_real = True
|
286 |
+
|
287 |
+
@property
|
288 |
+
def set(self):
|
289 |
+
return self.distribution.set
|
290 |
+
|
291 |
+
@property
|
292 |
+
def domain(self):
|
293 |
+
return SingleDiscreteDomain(self.symbol, self.set)
|
294 |
+
|
295 |
+
def sample(self, size=(), library='scipy', seed=None):
|
296 |
+
"""
|
297 |
+
Internal sample method.
|
298 |
+
|
299 |
+
Returns dictionary mapping RandomSymbol to realization value.
|
300 |
+
"""
|
301 |
+
return {self.value: self.distribution.sample(size, library=library, seed=seed)}
|
302 |
+
|
303 |
+
def compute_expectation(self, expr, rvs=None, evaluate=True, **kwargs):
|
304 |
+
rvs = rvs or (self.value,)
|
305 |
+
if self.value not in rvs:
|
306 |
+
return expr
|
307 |
+
|
308 |
+
expr = _sympify(expr)
|
309 |
+
expr = expr.xreplace({rv: rv.symbol for rv in rvs})
|
310 |
+
|
311 |
+
x = self.value.symbol
|
312 |
+
try:
|
313 |
+
return self.distribution.expectation(expr, x, evaluate=evaluate,
|
314 |
+
**kwargs)
|
315 |
+
except NotImplementedError:
|
316 |
+
return Sum(expr * self.pdf, (x, self.set.inf, self.set.sup),
|
317 |
+
**kwargs)
|
318 |
+
|
319 |
+
def compute_cdf(self, expr, **kwargs):
|
320 |
+
if expr == self.value:
|
321 |
+
x = Dummy("x", real=True)
|
322 |
+
return Lambda(x, self.distribution.cdf(x, **kwargs))
|
323 |
+
else:
|
324 |
+
raise NotImplementedError()
|
325 |
+
|
326 |
+
def compute_density(self, expr, **kwargs):
|
327 |
+
if expr == self.value:
|
328 |
+
return self.distribution
|
329 |
+
raise NotImplementedError()
|
330 |
+
|
331 |
+
def compute_characteristic_function(self, expr, **kwargs):
|
332 |
+
if expr == self.value:
|
333 |
+
t = Dummy("t", real=True)
|
334 |
+
return Lambda(t, self.distribution.characteristic_function(t, **kwargs))
|
335 |
+
else:
|
336 |
+
raise NotImplementedError()
|
337 |
+
|
338 |
+
def compute_moment_generating_function(self, expr, **kwargs):
|
339 |
+
if expr == self.value:
|
340 |
+
t = Dummy("t", real=True)
|
341 |
+
return Lambda(t, self.distribution.moment_generating_function(t, **kwargs))
|
342 |
+
else:
|
343 |
+
raise NotImplementedError()
|
344 |
+
|
345 |
+
def compute_quantile(self, expr, **kwargs):
|
346 |
+
if expr == self.value:
|
347 |
+
p =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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
|
3 |
+
Contains
|
4 |
+
========
|
5 |
+
FlorySchulz
|
6 |
+
Geometric
|
7 |
+
Hermite
|
8 |
+
Logarithmic
|
9 |
+
NegativeBinomial
|
10 |
+
Poisson
|
11 |
+
Skellam
|
12 |
+
YuleSimon
|
13 |
+
Zeta
|
14 |
+
"""
|
15 |
+
|
16 |
+
|
17 |
+
|
18 |
+
from sympy.concrete.summations import Sum
|
19 |
+
from sympy.core.basic import Basic
|
20 |
+
from sympy.core.function import Lambda
|
21 |
+
from sympy.core.numbers import I
|
22 |
+
from sympy.core.relational import Eq
|
23 |
+
from sympy.core.singleton import S
|
24 |
+
from sympy.core.symbol import Dummy
|
25 |
+
from sympy.core.sympify import sympify
|
26 |
+
from sympy.functions.combinatorial.factorials import (binomial, factorial)
|
27 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
28 |
+
from sympy.functions.elementary.integers import floor
|
29 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
30 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
31 |
+
from sympy.functions.special.bessel import besseli
|
32 |
+
from sympy.functions.special.beta_functions import beta
|
33 |
+
from sympy.functions.special.hyper import hyper
|
34 |
+
from sympy.functions.special.zeta_functions import (polylog, zeta)
|
35 |
+
from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace
|
36 |
+
from sympy.stats.rv import _value_check, is_random
|
37 |
+
|
38 |
+
|
39 |
+
__all__ = ['FlorySchulz',
|
40 |
+
'Geometric',
|
41 |
+
'Hermite',
|
42 |
+
'Logarithmic',
|
43 |
+
'NegativeBinomial',
|
44 |
+
'Poisson',
|
45 |
+
'Skellam',
|
46 |
+
'YuleSimon',
|
47 |
+
'Zeta'
|
48 |
+
]
|
49 |
+
|
50 |
+
|
51 |
+
def rv(symbol, cls, *args, **kwargs):
|
52 |
+
args = list(map(sympify, args))
|
53 |
+
dist = cls(*args)
|
54 |
+
if kwargs.pop('check', True):
|
55 |
+
dist.check(*args)
|
56 |
+
pspace = SingleDiscretePSpace(symbol, dist)
|
57 |
+
if any(is_random(arg) for arg in args):
|
58 |
+
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
|
59 |
+
pspace = CompoundPSpace(symbol, CompoundDistribution(dist))
|
60 |
+
return pspace.value
|
61 |
+
|
62 |
+
|
63 |
+
class DiscreteDistributionHandmade(SingleDiscreteDistribution):
|
64 |
+
_argnames = ('pdf',)
|
65 |
+
|
66 |
+
def __new__(cls, pdf, set=S.Integers):
|
67 |
+
return Basic.__new__(cls, pdf, set)
|
68 |
+
|
69 |
+
@property
|
70 |
+
def set(self):
|
71 |
+
return self.args[1]
|
72 |
+
|
73 |
+
@staticmethod
|
74 |
+
def check(pdf, set):
|
75 |
+
x = Dummy('x')
|
76 |
+
val = Sum(pdf(x), (x, set._inf, set._sup)).doit()
|
77 |
+
_value_check(Eq(val, 1) != S.false, "The pdf is incorrect on the given set.")
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
def DiscreteRV(symbol, density, set=S.Integers, **kwargs):
|
82 |
+
"""
|
83 |
+
Create a Discrete Random Variable given the following:
|
84 |
+
|
85 |
+
Parameters
|
86 |
+
==========
|
87 |
+
|
88 |
+
symbol : Symbol
|
89 |
+
Represents name of the random variable.
|
90 |
+
density : Expression containing symbol
|
91 |
+
Represents probability density function.
|
92 |
+
set : set
|
93 |
+
Represents the region where the pdf is valid, by default is real line.
|
94 |
+
check : bool
|
95 |
+
If True, it will check whether the given density
|
96 |
+
integrates to 1 over the given set. If False, it
|
97 |
+
will not perform this check. Default is False.
|
98 |
+
|
99 |
+
Examples
|
100 |
+
========
|
101 |
+
|
102 |
+
>>> from sympy.stats import DiscreteRV, P, E
|
103 |
+
>>> from sympy import Rational, Symbol
|
104 |
+
>>> x = Symbol('x')
|
105 |
+
>>> n = 10
|
106 |
+
>>> density = Rational(1, 10)
|
107 |
+
>>> X = DiscreteRV(x, density, set=set(range(n)))
|
108 |
+
>>> E(X)
|
109 |
+
9/2
|
110 |
+
>>> P(X>3)
|
111 |
+
3/5
|
112 |
+
|
113 |
+
Returns
|
114 |
+
=======
|
115 |
+
|
116 |
+
RandomSymbol
|
117 |
+
|
118 |
+
"""
|
119 |
+
set = sympify(set)
|
120 |
+
pdf = Piecewise((density, set.as_relational(symbol)), (0, True))
|
121 |
+
pdf = Lambda(symbol, pdf)
|
122 |
+
# have a default of False while `rv` should have a default of True
|
123 |
+
kwargs['check'] = kwargs.pop('check', False)
|
124 |
+
return rv(symbol.name, DiscreteDistributionHandmade, pdf, set, **kwargs)
|
125 |
+
|
126 |
+
|
127 |
+
#-------------------------------------------------------------------------------
|
128 |
+
# Flory-Schulz distribution ------------------------------------------------------------
|
129 |
+
|
130 |
+
class FlorySchulzDistribution(SingleDiscreteDistribution):
|
131 |
+
_argnames = ('a',)
|
132 |
+
set = S.Naturals
|
133 |
+
|
134 |
+
@staticmethod
|
135 |
+
def check(a):
|
136 |
+
_value_check((0 < a, a < 1), "a must be between 0 and 1")
|
137 |
+
|
138 |
+
def pdf(self, k):
|
139 |
+
a = self.a
|
140 |
+
return (a**2 * k * (1 - a)**(k - 1))
|
141 |
+
|
142 |
+
def _characteristic_function(self, t):
|
143 |
+
a = self.a
|
144 |
+
return a**2*exp(I*t)/((1 + (a - 1)*exp(I*t))**2)
|
145 |
+
|
146 |
+
def _moment_generating_function(self, t):
|
147 |
+
a = self.a
|
148 |
+
return a**2*exp(t)/((1 + (a - 1)*exp(t))**2)
|
149 |
+
|
150 |
+
|
151 |
+
def FlorySchulz(name, a):
|
152 |
+
r"""
|
153 |
+
Create a discrete random variable with a FlorySchulz distribution.
|
154 |
+
|
155 |
+
The density of the FlorySchulz distribution is given by
|
156 |
+
|
157 |
+
.. math::
|
158 |
+
f(k) := (a^2) k (1 - a)^{k-1}
|
159 |
+
|
160 |
+
Parameters
|
161 |
+
==========
|
162 |
+
|
163 |
+
a : A real number between 0 and 1
|
164 |
+
|
165 |
+
Returns
|
166 |
+
=======
|
167 |
+
|
168 |
+
RandomSymbol
|
169 |
+
|
170 |
+
Examples
|
171 |
+
========
|
172 |
+
|
173 |
+
>>> from sympy.stats import density, E, variance, FlorySchulz
|
174 |
+
>>> from sympy import Symbol, S
|
175 |
+
|
176 |
+
>>> a = S.One / 5
|
177 |
+
>>> z = Symbol("z")
|
178 |
+
|
179 |
+
>>> X = FlorySchulz("x", a)
|
180 |
+
|
181 |
+
>>> density(X)(z)
|
182 |
+
(5/4)**(1 - z)*z/25
|
183 |
+
|
184 |
+
>>> E(X)
|
185 |
+
9
|
186 |
+
|
187 |
+
>>> variance(X)
|
188 |
+
40
|
189 |
+
|
190 |
+
References
|
191 |
+
==========
|
192 |
+
|
193 |
+
https://en.wikipedia.org/wiki/Flory%E2%80%93Schulz_distribution
|
194 |
+
"""
|
195 |
+
return rv(name, FlorySchulzDistribution, a)
|
196 |
+
|
197 |
+
|
198 |
+
#-------------------------------------------------------------------------------
|
199 |
+
# Geometric distribution ------------------------------------------------------------
|
200 |
+
|
201 |
+
class GeometricDistribution(SingleDiscreteDistribution):
|
202 |
+
_argnames = ('p',)
|
203 |
+
set = S.Naturals
|
204 |
+
|
205 |
+
@staticmethod
|
206 |
+
def check(p):
|
207 |
+
_value_check((0 < p, p <= 1), "p must be between 0 and 1")
|
208 |
+
|
209 |
+
def pdf(self, k):
|
210 |
+
return (1 - self.p)**(k - 1) * self.p
|
211 |
+
|
212 |
+
def _characteristic_function(self, t):
|
213 |
+
p = self.p
|
214 |
+
return p * exp(I*t) / (1 - (1 - p)*exp(I*t))
|
215 |
+
|
216 |
+
def _moment_generating_function(self, t):
|
217 |
+
p = self.p
|
218 |
+
return p * exp(t) / (1 - (1 - p) * exp(t))
|
219 |
+
|
220 |
+
|
221 |
+
def Geometric(name, p):
|
222 |
+
r"""
|
223 |
+
Create a discrete random variable with a Geometric distribution.
|
224 |
+
|
225 |
+
Explanation
|
226 |
+
===========
|
227 |
+
|
228 |
+
The density of the Geometric distribution is given by
|
229 |
+
|
230 |
+
.. math::
|
231 |
+
f(k) := p (1 - p)^{k - 1}
|
232 |
+
|
233 |
+
Parameters
|
234 |
+
==========
|
235 |
+
|
236 |
+
p : A probability between 0 and 1
|
237 |
+
|
238 |
+
Returns
|
239 |
+
=======
|
240 |
+
|
241 |
+
RandomSymbol
|
242 |
+
|
243 |
+
Examples
|
244 |
+
========
|
245 |
+
|
246 |
+
>>> from sympy.stats import Geometric, density, E, variance
|
247 |
+
>>> from sympy import Symbol, S
|
248 |
+
|
249 |
+
>>> p = S.One / 5
|
250 |
+
>>> z = Symbol("z")
|
251 |
+
|
252 |
+
>>> X = Geometric("x", p)
|
253 |
+
|
254 |
+
>>> density(X)(z)
|
255 |
+
(5/4)**(1 - z)/5
|
256 |
+
|
257 |
+
>>> E(X)
|
258 |
+
5
|
259 |
+
|
260 |
+
>>> variance(X)
|
261 |
+
20
|
262 |
+
|
263 |
+
References
|
264 |
+
==========
|
265 |
+
|
266 |
+
.. [1] https://en.wikipedia.org/wiki/Geometric_distribution
|
267 |
+
.. [2] https://mathworld.wolfram.com/GeometricDistribution.html
|
268 |
+
|
269 |
+
"""
|
270 |
+
return rv(name, GeometricDistribution, p)
|
271 |
+
|
272 |
+
|
273 |
+
#-------------------------------------------------------------------------------
|
274 |
+
# Hermite distribution ---------------------------------------------------------
|
275 |
+
|
276 |
+
|
277 |
+
class HermiteDistribution(SingleDiscreteDistribution):
|
278 |
+
_argnames = ('a1', 'a2')
|
279 |
+
set = S.Naturals0
|
280 |
+
|
281 |
+
@staticmethod
|
282 |
+
def check(a1, a2):
|
283 |
+
_value_check(a1.is_nonnegative, 'Parameter a1 must be >= 0.')
|
284 |
+
_value_check(a2.is_nonnegative, 'Parameter a2 must be >= 0.')
|
285 |
+
|
286 |
+
def pdf(self, k):
|
287 |
+
a1, a2 = self.a1, self.a2
|
288 |
+
term1 = exp(-(a1 + a2))
|
289 |
+
j = Dummy("j", integer=True)
|
290 |
+
num = a1**(k - 2*j) * a2**j
|
291 |
+
den = factorial(k - 2*j) * factorial(j)
|
292 |
+
return term1 * Sum(num/den, (j, 0, k//2)).doit()
|
293 |
+
|
294 |
+
def _moment_generating_function(self, t):
|
295 |
+
a1, a2 = self.a1, self.a2
|
296 |
+
term1 = a1 * (exp(t) - 1)
|
297 |
+
term2 = a2 * (exp(2*t) - 1)
|
298 |
+
return exp(term1 + term2)
|
299 |
+
|
300 |
+
def _characteristic_function(self, t):
|
301 |
+
a1, a2 = self.a1, self.a2
|
302 |
+
term1 = a1 * (exp(I*t) - 1)
|
303 |
+
term2 = a2 * (exp(2*I*t) - 1)
|
304 |
+
return exp(term1 + term2)
|
305 |
+
|
306 |
+
def Hermite(name, a1, a2):
|
307 |
+
r"""
|
308 |
+
Create a discrete random variable with a Hermite distribution.
|
309 |
+
|
310 |
+
Explanation
|
311 |
+
===========
|
312 |
+
|
313 |
+
The density of the Hermite distribution is given by
|
314 |
+
|
315 |
+
.. math::
|
316 |
+
f(x):= e^{-a_1 -a_2}\sum_{j=0}^{\left \lfloor x/2 \right \rfloor}
|
317 |
+
\frac{a_{1}^{x-2j}a_{2}^{j}}{(x-2j)!j!}
|
318 |
+
|
319 |
+
Parameters
|
320 |
+
==========
|
321 |
+
|
322 |
+
a1 : A Positive number greater than equal to 0.
|
323 |
+
a2 : A Positive number greater than equal to 0.
|
324 |
+
|
325 |
+
Returns
|
326 |
+
=======
|
327 |
+
|
328 |
+
RandomSymbol
|
329 |
+
|
330 |
+
Examples
|
331 |
+
========
|
332 |
+
|
333 |
+
>>> from sympy.stats import Hermite, density, E, variance
|
334 |
+
>>> from sympy import Symbol
|
335 |
+
|
336 |
+
>>> a1 = Symbol("a1", positive=True)
|
337 |
+
>>> a2 = Symbol("a2", positive=True)
|
338 |
+
>>> x = Symbol("x")
|
339 |
+
|
340 |
+
>>> H = Hermite("H", a1=5, a2=4)
|
341 |
+
|
342 |
+
>>> density(H)(2)
|
343 |
+
33*exp(-9)/2
|
344 |
+
|
345 |
+
>>> E(H)
|
346 |
+
13
|
347 |
+
|
348 |
+
>>> variance(H)
|
349 |
+
21
|
350 |
+
|
351 |
+
References
|
352 |
+
==========
|
353 |
+
|
354 |
+
.. [1] https://en.wikipedia.org/wiki/Hermite_distribution
|
355 |
+
|
356 |
+
"""
|
357 |
+
|
358 |
+
return rv(name, HermiteDistribution, a1, a2)
|
359 |
+
|
360 |
+
|
361 |
+
#-------------------------------------------------------------------------------
|
362 |
+
# Logarithmic distribution ------------------------------------------------------------
|
363 |
+
|
364 |
+
class LogarithmicDistribution(SingleDiscreteDistribution):
|
365 |
+
_argnames = ('p',)
|
366 |
+
|
367 |
+
set = S.Naturals
|
368 |
+
|
369 |
+
@staticmethod
|
370 |
+
def check(p):
|
371 |
+
_value_check((p > 0, p < 1), "p should be between 0 and 1")
|
372 |
+
|
373 |
+
def pdf(self, k):
|
374 |
+
p = self.p
|
375 |
+
return (-1) * p**k / (k * log(1 - p))
|
376 |
+
|
377 |
+
def _characteristic_function(self, t):
|
378 |
+
p = self.p
|
379 |
+
return log(1 - p * exp(I*t)) / log(1 - p)
|
380 |
+
|
381 |
+
def _moment_generating_function(self, t):
|
382 |
+
p = self.p
|
383 |
+
return log(1 - p * exp(t)) / log(1 - p)
|
384 |
+
|
385 |
+
|
386 |
+
def Logarithmic(name, p):
|
387 |
+
r"""
|
388 |
+
Create a discrete random variable with a Logarithmic distribution.
|
389 |
+
|
390 |
+
Explanation
|
391 |
+
===========
|
392 |
+
|
393 |
+
The density of the Logarithmic distribution is given by
|
394 |
+
|
395 |
+
.. math::
|
396 |
+
f(k) := \frac{-p^k}{k \ln{(1 - p)}}
|
397 |
+
|
398 |
+
Parameters
|
399 |
+
==========
|
400 |
+
|
401 |
+
p : A value between 0 and 1
|
402 |
+
|
403 |
+
Returns
|
404 |
+
=======
|
405 |
+
|
406 |
+
RandomSymbol
|
407 |
+
|
408 |
+
Examples
|
409 |
+
========
|
410 |
+
|
411 |
+
>>> from sympy.stats import Logarithmic, density, E, variance
|
412 |
+
>>> from sympy import Symbol, S
|
413 |
+
|
414 |
+
>>> p = S.One / 5
|
415 |
+
>>> z = Symbol("z")
|
416 |
+
|
417 |
+
>>> X = Logarithmic("x", p)
|
418 |
+
|
419 |
+
>>> density(X)(z)
|
420 |
+
-1/(5**z*z*log(4/5))
|
421 |
+
|
422 |
+
>>> E(X)
|
423 |
+
-1/(-4*log(5) + 8*log(2))
|
424 |
+
|
425 |
+
>>> variance(X)
|
426 |
+
-1/((-4*log(5) + 8*log(2))*(-2*log(5) + 4*log(2))) + 1/(-64*log(2)*log(5) + 64*log(2)**2 + 16*log(5)**2) - 10/(-32*log(5) + 64*log(2))
|
427 |
+
|
428 |
+
References
|
429 |
+
==========
|
430 |
+
|
431 |
+
.. [1] https://en.wikipedia.org/wiki/Logarithmic_distribution
|
432 |
+
.. [2] https://mathworld.wolfram.com/LogarithmicDistribution.html
|
433 |
+
|
434 |
+
"""
|
435 |
+
return rv(name, LogarithmicDistribution, p)
|
436 |
+
|
437 |
+
|
438 |
+
#-------------------------------------------------------------------------------
|
439 |
+
# Negative binomial distribution ------------------------------------------------------------
|
440 |
+
|
441 |
+
class NegativeBinomialDistribution(SingleDiscreteDistribution):
|
442 |
+
_argnames = ('r', 'p')
|
443 |
+
set = S.Naturals0
|
444 |
+
|
445 |
+
@staticmethod
|
446 |
+
def check(r, p):
|
447 |
+
_value_check(r > 0, 'r should be positive')
|
448 |
+
_value_check((p > 0, p < 1), 'p should be between 0 and 1')
|
449 |
+
|
450 |
+
def pdf(self, k):
|
451 |
+
r = self.r
|
452 |
+
p = self.p
|
453 |
+
|
454 |
+
return binomial(k + r - 1, k) * (1 - p)**r * p**k
|
455 |
+
|
456 |
+
def _characteristic_function(self, t):
|
457 |
+
r = self.r
|
458 |
+
p = self.p
|
459 |
+
|
460 |
+
return ((1 - p) / (1 - p * exp(I*t)))**r
|
461 |
+
|
462 |
+
def _moment_generating_function(self, t):
|
463 |
+
r = self.r
|
464 |
+
p = self.p
|
465 |
+
|
466 |
+
return ((1 - p) / (1 - p * exp(t)))**r
|
467 |
+
|
468 |
+
def NegativeBinomial(name, r, p):
|
469 |
+
r"""
|
470 |
+
Create a discrete random variable with a Negative Binomial distribution.
|
471 |
+
|
472 |
+
Explanation
|
473 |
+
===========
|
474 |
+
|
475 |
+
The density of the Negative Binomial distribution is given by
|
476 |
+
|
477 |
+
.. math::
|
478 |
+
f(k) := \binom{k + r - 1}{k} (1 - p)^r p^k
|
479 |
+
|
480 |
+
Parameters
|
481 |
+
==========
|
482 |
+
|
483 |
+
r : A positive value
|
484 |
+
p : A value between 0 and 1
|
485 |
+
|
486 |
+
Returns
|
487 |
+
=======
|
488 |
+
|
489 |
+
RandomSymbol
|
490 |
+
|
491 |
+
Examples
|
492 |
+
========
|
493 |
+
|
494 |
+
>>> from sympy.stats import NegativeBinomial, density, E, variance
|
495 |
+
>>> from sympy import Symbol, S
|
496 |
+
|
497 |
+
>>> r = 5
|
498 |
+
>>> p = S.One / 5
|
499 |
+
>>> z = Symbol("z")
|
500 |
+
|
501 |
+
>>> X = NegativeBinomial("x", r, p)
|
502 |
+
|
503 |
+
>>> density(X)(z)
|
504 |
+
1024*binomial(z + 4, z)/(3125*5**z)
|
505 |
+
|
506 |
+
>>> E(X)
|
507 |
+
5/4
|
508 |
+
|
509 |
+
>>> variance(X)
|
510 |
+
25/16
|
511 |
+
|
512 |
+
References
|
513 |
+
==========
|
514 |
+
|
515 |
+
.. [1] https://en.wikipedia.org/wiki/Negative_binomial_distribution
|
516 |
+
.. [2] https://mathworld.wolfram.com/NegativeBinomialDistribution.html
|
517 |
+
|
518 |
+
"""
|
519 |
+
return rv(name, NegativeBinomialDistribution, r, p)
|
520 |
+
|
521 |
+
|
522 |
+
#-------------------------------------------------------------------------------
|
523 |
+
# Poisson distribution ------------------------------------------------------------
|
524 |
+
|
525 |
+
class PoissonDistribution(SingleDiscreteDistribution):
|
526 |
+
_argnames = ('lamda',)
|
527 |
+
|
528 |
+
set = S.Naturals0
|
529 |
+
|
530 |
+
@staticmethod
|
531 |
+
def check(lamda):
|
532 |
+
_value_check(lamda > 0, "Lambda must be positive")
|
533 |
+
|
534 |
+
def pdf(self, k):
|
535 |
+
return self.lamda**k / factorial(k) * exp(-self.lamda)
|
536 |
+
|
537 |
+
def _characteristic_function(self, t):
|
538 |
+
return exp(self.lamda * (exp(I*t) - 1))
|
539 |
+
|
540 |
+
def _moment_generating_function(self, t):
|
541 |
+
return exp(self.lamda * (exp(t) - 1))
|
542 |
+
|
543 |
+
|
544 |
+
def Poisson(name, lamda):
|
545 |
+
r"""
|
546 |
+
Create a discrete random variable with a Poisson distribution.
|
547 |
+
|
548 |
+
Explanation
|
549 |
+
===========
|
550 |
+
|
551 |
+
The density of the Poisson distribution is given by
|
552 |
+
|
553 |
+
.. math::
|
554 |
+
f(k) := \frac{\lambda^{k} e^{- \lambda}}{k!}
|
555 |
+
|
556 |
+
Parameters
|
557 |
+
==========
|
558 |
+
|
559 |
+
lamda : Positive number, a rate
|
560 |
+
|
561 |
+
Returns
|
562 |
+
=======
|
563 |
+
|
564 |
+
RandomSymbol
|
565 |
+
|
566 |
+
Examples
|
567 |
+
========
|
568 |
+
|
569 |
+
>>> from sympy.stats import Poisson, density, E, variance
|
570 |
+
>>> from sympy import Symbol, simplify
|
571 |
+
|
572 |
+
>>> rate = Symbol("lambda", positive=True)
|
573 |
+
>>> z = Symbol("z")
|
574 |
+
|
575 |
+
>>> X = Poisson("x", rate)
|
576 |
+
|
577 |
+
>>> density(X)(z)
|
578 |
+
lambda**z*exp(-lambda)/factorial(z)
|
579 |
+
|
580 |
+
>>> E(X)
|
581 |
+
lambda
|
582 |
+
|
583 |
+
>>> simplify(variance(X))
|
584 |
+
lambda
|
585 |
+
|
586 |
+
References
|
587 |
+
==========
|
588 |
+
|
589 |
+
.. [1] https://en.wikipedia.org/wiki/Poisson_distribution
|
590 |
+
.. [2] https://mathworld.wolfram.com/PoissonDistribution.html
|
591 |
+
|
592 |
+
"""
|
593 |
+
return rv(name, PoissonDistribution, lamda)
|
594 |
+
|
595 |
+
|
596 |
+
# -----------------------------------------------------------------------------
|
597 |
+
# Skellam distribution --------------------------------------------------------
|
598 |
+
|
599 |
+
|
600 |
+
class SkellamDistribution(SingleDiscreteDistribution):
|
601 |
+
_argnames = ('mu1', 'mu2')
|
602 |
+
set = S.Integers
|
603 |
+
|
604 |
+
@staticmethod
|
605 |
+
def check(mu1, mu2):
|
606 |
+
_value_check(mu1 >= 0, 'Parameter mu1 must be >= 0')
|
607 |
+
_value_check(mu2 >= 0, 'Parameter mu2 must be >= 0')
|
608 |
+
|
609 |
+
def pdf(self, k):
|
610 |
+
(mu1, mu2) = (self.mu1, self.mu2)
|
611 |
+
term1 = exp(-(mu1 + mu2)) * (mu1 / mu2) ** (k / 2)
|
612 |
+
term2 = besseli(k, 2 * sqrt(mu1 * mu2))
|
613 |
+
return term1 * term2
|
614 |
+
|
615 |
+
def _cdf(self, x):
|
616 |
+
raise NotImplementedError(
|
617 |
+
"Skellam doesn't have closed form for the CDF.")
|
618 |
+
|
619 |
+
def _characteristic_function(self, t):
|
620 |
+
(mu1, mu2) = (self.mu1, self.mu2)
|
621 |
+
return exp(-(mu1 + mu2) + mu1 * exp(I * t) + mu2 * exp(-I * t))
|
622 |
+
|
623 |
+
def _moment_generating_function(self, t):
|
624 |
+
(mu1, mu2) = (self.mu1, self.mu2)
|
625 |
+
return exp(-(mu1 + mu2) + mu1 * exp(t) + mu2 * exp(-t))
|
626 |
+
|
627 |
+
|
628 |
+
def Skellam(name, mu1, mu2):
|
629 |
+
r"""
|
630 |
+
Create a discrete random variable with a Skellam distribution.
|
631 |
+
|
632 |
+
Explanation
|
633 |
+
===========
|
634 |
+
|
635 |
+
The Skellam is the distribution of the difference N1 - N2
|
636 |
+
of two statistically independent random variables N1 and N2
|
637 |
+
each Poisson-distributed with respective expected values mu1 and mu2.
|
638 |
+
|
639 |
+
The density of the Skellam distribution is given by
|
640 |
+
|
641 |
+
.. math::
|
642 |
+
f(k) := e^{-(\mu_1+\mu_2)}(\frac{\mu_1}{\mu_2})^{k/2}I_k(2\sqrt{\mu_1\mu_2})
|
643 |
+
|
644 |
+
Parameters
|
645 |
+
==========
|
646 |
+
|
647 |
+
mu1 : A non-negative value
|
648 |
+
mu2 : A non-negative value
|
649 |
+
|
650 |
+
Returns
|
651 |
+
=======
|
652 |
+
|
653 |
+
RandomSymbol
|
654 |
+
|
655 |
+
Examples
|
656 |
+
========
|
657 |
+
|
658 |
+
>>> from sympy.stats import Skellam, density, E, variance
|
659 |
+
>>> from sympy import Symbol, pprint
|
660 |
+
|
661 |
+
>>> z = Symbol("z", integer=True)
|
662 |
+
>>> mu1 = Symbol("mu1", positive=True)
|
663 |
+
>>> mu2 = Symbol("mu2", positive=True)
|
664 |
+
>>> X = Skellam("x", mu1, mu2)
|
665 |
+
|
666 |
+
>>> pprint(density(X)(z), use_unicode=False)
|
667 |
+
z
|
668 |
+
-
|
669 |
+
2
|
670 |
+
/mu1\ -mu1 - mu2 / _____ _____\
|
671 |
+
|---| *e *besseli\z, 2*\/ mu1 *\/ mu2 /
|
672 |
+
\mu2/
|
673 |
+
>>> E(X)
|
674 |
+
mu1 - mu2
|
675 |
+
>>> variance(X).expand()
|
676 |
+
mu1 + mu2
|
677 |
+
|
678 |
+
References
|
679 |
+
==========
|
680 |
+
|
681 |
+
.. [1] https://en.wikipedia.org/wiki/Skellam_distribution
|
682 |
+
|
683 |
+
"""
|
684 |
+
return rv(name, SkellamDistribution, mu1, mu2)
|
685 |
+
|
686 |
+
|
687 |
+
#-------------------------------------------------------------------------------
|
688 |
+
# Yule-Simon distribution ------------------------------------------------------------
|
689 |
+
|
690 |
+
class YuleSimonDistribution(SingleDiscreteDistribution):
|
691 |
+
_argnames = ('rho',)
|
692 |
+
set = S.Naturals
|
693 |
+
|
694 |
+
@staticmethod
|
695 |
+
def check(rho):
|
696 |
+
_value_check(rho > 0, 'rho should be positive')
|
697 |
+
|
698 |
+
def pdf(self, k):
|
699 |
+
rho = self.rho
|
700 |
+
return rho * beta(k, rho + 1)
|
701 |
+
|
702 |
+
def _cdf(self, x):
|
703 |
+
return Piecewise((1 - floor(x) * beta(floor(x), self.rho + 1), x >= 1), (0, True))
|
704 |
+
|
705 |
+
def _characteristic_function(self, t):
|
706 |
+
rho = self.rho
|
707 |
+
return rho * hyper((1, 1), (rho + 2,), exp(I*t)) * exp(I*t) / (rho + 1)
|
708 |
+
|
709 |
+
def _moment_generating_function(self, t):
|
710 |
+
rho = self.rho
|
711 |
+
return rho * hyper((1, 1), (rho + 2,), exp(t)) * exp(t) / (rho + 1)
|
712 |
+
|
713 |
+
|
714 |
+
def YuleSimon(name, rho):
|
715 |
+
r"""
|
716 |
+
Create a discrete random variable with a Yule-Simon distribution.
|
717 |
+
|
718 |
+
Explanation
|
719 |
+
===========
|
720 |
+
|
721 |
+
The density of the Yule-Simon distribution is given by
|
722 |
+
|
723 |
+
.. math::
|
724 |
+
f(k) := \rho B(k, \rho + 1)
|
725 |
+
|
726 |
+
Parameters
|
727 |
+
==========
|
728 |
+
|
729 |
+
rho : A positive value
|
730 |
+
|
731 |
+
Returns
|
732 |
+
=======
|
733 |
+
|
734 |
+
RandomSymbol
|
735 |
+
|
736 |
+
Examples
|
737 |
+
========
|
738 |
+
|
739 |
+
>>> from sympy.stats import YuleSimon, density, E, variance
|
740 |
+
>>> from sympy import Symbol, simplify
|
741 |
+
|
742 |
+
>>> p = 5
|
743 |
+
>>> z = Symbol("z")
|
744 |
+
|
745 |
+
>>> X = YuleSimon("x", p)
|
746 |
+
|
747 |
+
>>> density(X)(z)
|
748 |
+
5*beta(z, 6)
|
749 |
+
|
750 |
+
>>> simplify(E(X))
|
751 |
+
5/4
|
752 |
+
|
753 |
+
>>> simplify(variance(X))
|
754 |
+
25/48
|
755 |
+
|
756 |
+
References
|
757 |
+
==========
|
758 |
+
|
759 |
+
.. [1] https://en.wikipedia.org/wiki/Yule%E2%80%93Simon_distribution
|
760 |
+
|
761 |
+
"""
|
762 |
+
return rv(name, YuleSimonDistribution, rho)
|
763 |
+
|
764 |
+
|
765 |
+
#-------------------------------------------------------------------------------
|
766 |
+
# Zeta distribution ------------------------------------------------------------
|
767 |
+
|
768 |
+
class ZetaDistribution(SingleDiscreteDistribution):
|
769 |
+
_argnames = ('s',)
|
770 |
+
set = S.Naturals
|
771 |
+
|
772 |
+
@staticmethod
|
773 |
+
def check(s):
|
774 |
+
_value_check(s > 1, 's should be greater than 1')
|
775 |
+
|
776 |
+
def pdf(self, k):
|
777 |
+
s = self.s
|
778 |
+
return 1 / (k**s * zeta(s))
|
779 |
+
|
780 |
+
def _characteristic_function(self, t):
|
781 |
+
return polylog(self.s, exp(I*t)) / zeta(self.s)
|
782 |
+
|
783 |
+
def _moment_generating_function(self, t):
|
784 |
+
return polylog(self.s, exp(t)) / zeta(self.s)
|
785 |
+
|
786 |
+
|
787 |
+
def Zeta(name, s):
|
788 |
+
r"""
|
789 |
+
Create a discrete random variable with a Zeta distribution.
|
790 |
+
|
791 |
+
Explanation
|
792 |
+
===========
|
793 |
+
|
794 |
+
The density of the Zeta distribution is given by
|
795 |
+
|
796 |
+
.. math::
|
797 |
+
f(k) := \frac{1}{k^s \zeta{(s)}}
|
798 |
+
|
799 |
+
Parameters
|
800 |
+
==========
|
801 |
+
|
802 |
+
s : A value greater than 1
|
803 |
+
|
804 |
+
Returns
|
805 |
+
=======
|
806 |
+
|
807 |
+
RandomSymbol
|
808 |
+
|
809 |
+
Examples
|
810 |
+
========
|
811 |
+
|
812 |
+
>>> from sympy.stats import Zeta, density, E, variance
|
813 |
+
>>> from sympy import Symbol
|
814 |
+
|
815 |
+
>>> s = 5
|
816 |
+
>>> z = Symbol("z")
|
817 |
+
|
818 |
+
>>> X = Zeta("x", s)
|
819 |
+
|
820 |
+
>>> density(X)(z)
|
821 |
+
1/(z**5*zeta(5))
|
822 |
+
|
823 |
+
>>> E(X)
|
824 |
+
pi**4/(90*zeta(5))
|
825 |
+
|
826 |
+
>>> variance(X)
|
827 |
+
-pi**8/(8100*zeta(5)**2) + zeta(3)/zeta(5)
|
828 |
+
|
829 |
+
References
|
830 |
+
==========
|
831 |
+
|
832 |
+
.. [1] https://en.wikipedia.org/wiki/Zeta_distribution
|
833 |
+
|
834 |
+
"""
|
835 |
+
return rv(name, ZetaDistribution, s)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/error_prop.py
ADDED
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tools for arithmetic error propagation."""
|
2 |
+
|
3 |
+
from itertools import repeat, combinations
|
4 |
+
|
5 |
+
from sympy.core.add import Add
|
6 |
+
from sympy.core.mul import Mul
|
7 |
+
from sympy.core.power import Pow
|
8 |
+
from sympy.core.singleton import S
|
9 |
+
from sympy.core.symbol import Symbol
|
10 |
+
from sympy.functions.elementary.exponential import exp
|
11 |
+
from sympy.simplify.simplify import simplify
|
12 |
+
from sympy.stats.symbolic_probability import RandomSymbol, Variance, Covariance
|
13 |
+
from sympy.stats.rv import is_random
|
14 |
+
|
15 |
+
_arg0_or_var = lambda var: var.args[0] if len(var.args) > 0 else var
|
16 |
+
|
17 |
+
|
18 |
+
def variance_prop(expr, consts=(), include_covar=False):
|
19 |
+
r"""Symbolically propagates variance (`\sigma^2`) for expressions.
|
20 |
+
This is computed as as seen in [1]_.
|
21 |
+
|
22 |
+
Parameters
|
23 |
+
==========
|
24 |
+
|
25 |
+
expr : Expr
|
26 |
+
A SymPy expression to compute the variance for.
|
27 |
+
consts : sequence of Symbols, optional
|
28 |
+
Represents symbols that are known constants in the expr,
|
29 |
+
and thus have zero variance. All symbols not in consts are
|
30 |
+
assumed to be variant.
|
31 |
+
include_covar : bool, optional
|
32 |
+
Flag for whether or not to include covariances, default=False.
|
33 |
+
|
34 |
+
Returns
|
35 |
+
=======
|
36 |
+
|
37 |
+
var_expr : Expr
|
38 |
+
An expression for the total variance of the expr.
|
39 |
+
The variance for the original symbols (e.g. x) are represented
|
40 |
+
via instance of the Variance symbol (e.g. Variance(x)).
|
41 |
+
|
42 |
+
Examples
|
43 |
+
========
|
44 |
+
|
45 |
+
>>> from sympy import symbols, exp
|
46 |
+
>>> from sympy.stats.error_prop import variance_prop
|
47 |
+
>>> x, y = symbols('x y')
|
48 |
+
|
49 |
+
>>> variance_prop(x + y)
|
50 |
+
Variance(x) + Variance(y)
|
51 |
+
|
52 |
+
>>> variance_prop(x * y)
|
53 |
+
x**2*Variance(y) + y**2*Variance(x)
|
54 |
+
|
55 |
+
>>> variance_prop(exp(2*x))
|
56 |
+
4*exp(4*x)*Variance(x)
|
57 |
+
|
58 |
+
References
|
59 |
+
==========
|
60 |
+
|
61 |
+
.. [1] https://en.wikipedia.org/wiki/Propagation_of_uncertainty
|
62 |
+
|
63 |
+
"""
|
64 |
+
args = expr.args
|
65 |
+
if len(args) == 0:
|
66 |
+
if expr in consts:
|
67 |
+
return S.Zero
|
68 |
+
elif is_random(expr):
|
69 |
+
return Variance(expr).doit()
|
70 |
+
elif isinstance(expr, Symbol):
|
71 |
+
return Variance(RandomSymbol(expr)).doit()
|
72 |
+
else:
|
73 |
+
return S.Zero
|
74 |
+
nargs = len(args)
|
75 |
+
var_args = list(map(variance_prop, args, repeat(consts, nargs),
|
76 |
+
repeat(include_covar, nargs)))
|
77 |
+
if isinstance(expr, Add):
|
78 |
+
var_expr = Add(*var_args)
|
79 |
+
if include_covar:
|
80 |
+
terms = [2 * Covariance(_arg0_or_var(x), _arg0_or_var(y)).expand() \
|
81 |
+
for x, y in combinations(var_args, 2)]
|
82 |
+
var_expr += Add(*terms)
|
83 |
+
elif isinstance(expr, Mul):
|
84 |
+
terms = [v/a**2 for a, v in zip(args, var_args)]
|
85 |
+
var_expr = simplify(expr**2 * Add(*terms))
|
86 |
+
if include_covar:
|
87 |
+
terms = [2*Covariance(_arg0_or_var(x), _arg0_or_var(y)).expand()/(a*b) \
|
88 |
+
for (a, b), (x, y) in zip(combinations(args, 2),
|
89 |
+
combinations(var_args, 2))]
|
90 |
+
var_expr += Add(*terms)
|
91 |
+
elif isinstance(expr, Pow):
|
92 |
+
b = args[1]
|
93 |
+
v = var_args[0] * (expr * b / args[0])**2
|
94 |
+
var_expr = simplify(v)
|
95 |
+
elif isinstance(expr, exp):
|
96 |
+
var_expr = simplify(var_args[0] * expr**2)
|
97 |
+
else:
|
98 |
+
# unknown how to proceed, return variance of whole expr.
|
99 |
+
var_expr = Variance(expr)
|
100 |
+
return var_expr
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/frv.py
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
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Finite Discrete Random Variables Module
|
3 |
+
|
4 |
+
See Also
|
5 |
+
========
|
6 |
+
sympy.stats.frv_types
|
7 |
+
sympy.stats.rv
|
8 |
+
sympy.stats.crv
|
9 |
+
"""
|
10 |
+
from itertools import product
|
11 |
+
|
12 |
+
from sympy.concrete.summations import Sum
|
13 |
+
from sympy.core.basic import Basic
|
14 |
+
from sympy.core.cache import cacheit
|
15 |
+
from sympy.core.function import Lambda
|
16 |
+
from sympy.core.mul import Mul
|
17 |
+
from sympy.core.numbers import (I, nan)
|
18 |
+
from sympy.core.relational import Eq
|
19 |
+
from sympy.core.singleton import S
|
20 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
21 |
+
from sympy.core.sympify import sympify
|
22 |
+
from sympy.functions.elementary.exponential import exp
|
23 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
24 |
+
from sympy.logic.boolalg import (And, Or)
|
25 |
+
from sympy.sets.sets import Intersection
|
26 |
+
from sympy.core.containers import Dict
|
27 |
+
from sympy.core.logic import Logic
|
28 |
+
from sympy.core.relational import Relational
|
29 |
+
from sympy.core.sympify import _sympify
|
30 |
+
from sympy.sets.sets import FiniteSet
|
31 |
+
from sympy.stats.rv import (RandomDomain, ProductDomain, ConditionalDomain,
|
32 |
+
PSpace, IndependentProductPSpace, SinglePSpace, random_symbols,
|
33 |
+
sumsets, rv_subs, NamedArgsMixin, Density, Distribution)
|
34 |
+
|
35 |
+
|
36 |
+
class FiniteDensity(dict):
|
37 |
+
"""
|
38 |
+
A domain with Finite Density.
|
39 |
+
"""
|
40 |
+
def __call__(self, item):
|
41 |
+
"""
|
42 |
+
Make instance of a class callable.
|
43 |
+
|
44 |
+
If item belongs to current instance of a class, return it.
|
45 |
+
|
46 |
+
Otherwise, return 0.
|
47 |
+
"""
|
48 |
+
item = sympify(item)
|
49 |
+
if item in self:
|
50 |
+
return self[item]
|
51 |
+
else:
|
52 |
+
return 0
|
53 |
+
|
54 |
+
@property
|
55 |
+
def dict(self):
|
56 |
+
"""
|
57 |
+
Return item as dictionary.
|
58 |
+
"""
|
59 |
+
return dict(self)
|
60 |
+
|
61 |
+
class FiniteDomain(RandomDomain):
|
62 |
+
"""
|
63 |
+
A domain with discrete finite support
|
64 |
+
|
65 |
+
Represented using a FiniteSet.
|
66 |
+
"""
|
67 |
+
is_Finite = True
|
68 |
+
|
69 |
+
@property
|
70 |
+
def symbols(self):
|
71 |
+
return FiniteSet(sym for sym, val in self.elements)
|
72 |
+
|
73 |
+
@property
|
74 |
+
def elements(self):
|
75 |
+
return self.args[0]
|
76 |
+
|
77 |
+
@property
|
78 |
+
def dict(self):
|
79 |
+
return FiniteSet(*[Dict(dict(el)) for el in self.elements])
|
80 |
+
|
81 |
+
def __contains__(self, other):
|
82 |
+
return other in self.elements
|
83 |
+
|
84 |
+
def __iter__(self):
|
85 |
+
return self.elements.__iter__()
|
86 |
+
|
87 |
+
def as_boolean(self):
|
88 |
+
return Or(*[And(*[Eq(sym, val) for sym, val in item]) for item in self])
|
89 |
+
|
90 |
+
|
91 |
+
class SingleFiniteDomain(FiniteDomain):
|
92 |
+
"""
|
93 |
+
A FiniteDomain over a single symbol/set
|
94 |
+
|
95 |
+
Example: The possibilities of a *single* die roll.
|
96 |
+
"""
|
97 |
+
|
98 |
+
def __new__(cls, symbol, set):
|
99 |
+
if not isinstance(set, FiniteSet) and \
|
100 |
+
not isinstance(set, Intersection):
|
101 |
+
set = FiniteSet(*set)
|
102 |
+
return Basic.__new__(cls, symbol, set)
|
103 |
+
|
104 |
+
@property
|
105 |
+
def symbol(self):
|
106 |
+
return self.args[0]
|
107 |
+
|
108 |
+
@property
|
109 |
+
def symbols(self):
|
110 |
+
return FiniteSet(self.symbol)
|
111 |
+
|
112 |
+
@property
|
113 |
+
def set(self):
|
114 |
+
return self.args[1]
|
115 |
+
|
116 |
+
@property
|
117 |
+
def elements(self):
|
118 |
+
return FiniteSet(*[frozenset(((self.symbol, elem), )) for elem in self.set])
|
119 |
+
|
120 |
+
def __iter__(self):
|
121 |
+
return (frozenset(((self.symbol, elem),)) for elem in self.set)
|
122 |
+
|
123 |
+
def __contains__(self, other):
|
124 |
+
sym, val = tuple(other)[0]
|
125 |
+
return sym == self.symbol and val in self.set
|
126 |
+
|
127 |
+
|
128 |
+
class ProductFiniteDomain(ProductDomain, FiniteDomain):
|
129 |
+
"""
|
130 |
+
A Finite domain consisting of several other FiniteDomains
|
131 |
+
|
132 |
+
Example: The possibilities of the rolls of three independent dice
|
133 |
+
"""
|
134 |
+
|
135 |
+
def __iter__(self):
|
136 |
+
proditer = product(*self.domains)
|
137 |
+
return (sumsets(items) for items in proditer)
|
138 |
+
|
139 |
+
@property
|
140 |
+
def elements(self):
|
141 |
+
return FiniteSet(*self)
|
142 |
+
|
143 |
+
|
144 |
+
class ConditionalFiniteDomain(ConditionalDomain, ProductFiniteDomain):
|
145 |
+
"""
|
146 |
+
A FiniteDomain that has been restricted by a condition
|
147 |
+
|
148 |
+
Example: The possibilities of a die roll under the condition that the
|
149 |
+
roll is even.
|
150 |
+
"""
|
151 |
+
|
152 |
+
def __new__(cls, domain, condition):
|
153 |
+
"""
|
154 |
+
Create a new instance of ConditionalFiniteDomain class
|
155 |
+
"""
|
156 |
+
if condition is True:
|
157 |
+
return domain
|
158 |
+
cond = rv_subs(condition)
|
159 |
+
return Basic.__new__(cls, domain, cond)
|
160 |
+
|
161 |
+
def _test(self, elem):
|
162 |
+
"""
|
163 |
+
Test the value. If value is boolean, return it. If value is equality
|
164 |
+
relational (two objects are equal), return it with left-hand side
|
165 |
+
being equal to right-hand side. Otherwise, raise ValueError exception.
|
166 |
+
"""
|
167 |
+
val = self.condition.xreplace(dict(elem))
|
168 |
+
if val in [True, False]:
|
169 |
+
return val
|
170 |
+
elif val.is_Equality:
|
171 |
+
return val.lhs == val.rhs
|
172 |
+
raise ValueError("Undecidable if %s" % str(val))
|
173 |
+
|
174 |
+
def __contains__(self, other):
|
175 |
+
return other in self.fulldomain and self._test(other)
|
176 |
+
|
177 |
+
def __iter__(self):
|
178 |
+
return (elem for elem in self.fulldomain if self._test(elem))
|
179 |
+
|
180 |
+
@property
|
181 |
+
def set(self):
|
182 |
+
if isinstance(self.fulldomain, SingleFiniteDomain):
|
183 |
+
return FiniteSet(*[elem for elem in self.fulldomain.set
|
184 |
+
if frozenset(((self.fulldomain.symbol, elem),)) in self])
|
185 |
+
else:
|
186 |
+
raise NotImplementedError(
|
187 |
+
"Not implemented on multi-dimensional conditional domain")
|
188 |
+
|
189 |
+
def as_boolean(self):
|
190 |
+
return FiniteDomain.as_boolean(self)
|
191 |
+
|
192 |
+
|
193 |
+
class SingleFiniteDistribution(Distribution, NamedArgsMixin):
|
194 |
+
def __new__(cls, *args):
|
195 |
+
args = list(map(sympify, args))
|
196 |
+
return Basic.__new__(cls, *args)
|
197 |
+
|
198 |
+
@staticmethod
|
199 |
+
def check(*args):
|
200 |
+
pass
|
201 |
+
|
202 |
+
@property # type: ignore
|
203 |
+
@cacheit
|
204 |
+
def dict(self):
|
205 |
+
if self.is_symbolic:
|
206 |
+
return Density(self)
|
207 |
+
return {k: self.pmf(k) for k in self.set}
|
208 |
+
|
209 |
+
def pmf(self, *args): # to be overridden by specific distribution
|
210 |
+
raise NotImplementedError()
|
211 |
+
|
212 |
+
@property
|
213 |
+
def set(self): # to be overridden by specific distribution
|
214 |
+
raise NotImplementedError()
|
215 |
+
|
216 |
+
values = property(lambda self: self.dict.values)
|
217 |
+
items = property(lambda self: self.dict.items)
|
218 |
+
is_symbolic = property(lambda self: False)
|
219 |
+
__iter__ = property(lambda self: self.dict.__iter__)
|
220 |
+
__getitem__ = property(lambda self: self.dict.__getitem__)
|
221 |
+
|
222 |
+
def __call__(self, *args):
|
223 |
+
return self.pmf(*args)
|
224 |
+
|
225 |
+
def __contains__(self, other):
|
226 |
+
return other in self.set
|
227 |
+
|
228 |
+
|
229 |
+
#=============================================
|
230 |
+
#========= Probability Space ===============
|
231 |
+
#=============================================
|
232 |
+
|
233 |
+
|
234 |
+
class FinitePSpace(PSpace):
|
235 |
+
"""
|
236 |
+
A Finite Probability Space
|
237 |
+
|
238 |
+
Represents the probabilities of a finite number of events.
|
239 |
+
"""
|
240 |
+
is_Finite = True
|
241 |
+
|
242 |
+
def __new__(cls, domain, density):
|
243 |
+
density = {sympify(key): sympify(val)
|
244 |
+
for key, val in density.items()}
|
245 |
+
public_density = Dict(density)
|
246 |
+
|
247 |
+
obj = PSpace.__new__(cls, domain, public_density)
|
248 |
+
obj._density = density
|
249 |
+
return obj
|
250 |
+
|
251 |
+
def prob_of(self, elem):
|
252 |
+
elem = sympify(elem)
|
253 |
+
density = self._density
|
254 |
+
if isinstance(list(density.keys())[0], FiniteSet):
|
255 |
+
return density.get(elem, S.Zero)
|
256 |
+
return density.get(tuple(elem)[0][1], S.Zero)
|
257 |
+
|
258 |
+
def where(self, condition):
|
259 |
+
assert all(r.symbol in self.symbols for r in random_symbols(condition))
|
260 |
+
return ConditionalFiniteDomain(self.domain, condition)
|
261 |
+
|
262 |
+
def compute_density(self, expr):
|
263 |
+
expr = rv_subs(expr, self.values)
|
264 |
+
d = FiniteDensity()
|
265 |
+
for elem in self.domain:
|
266 |
+
val = expr.xreplace(dict(elem))
|
267 |
+
prob = self.prob_of(elem)
|
268 |
+
d[val] = d.get(val, S.Zero) + prob
|
269 |
+
return d
|
270 |
+
|
271 |
+
@cacheit
|
272 |
+
def compute_cdf(self, expr):
|
273 |
+
d = self.compute_density(expr)
|
274 |
+
cum_prob = S.Zero
|
275 |
+
cdf = []
|
276 |
+
for key in sorted(d):
|
277 |
+
prob = d[key]
|
278 |
+
cum_prob += prob
|
279 |
+
cdf.append((key, cum_prob))
|
280 |
+
|
281 |
+
return dict(cdf)
|
282 |
+
|
283 |
+
@cacheit
|
284 |
+
def sorted_cdf(self, expr, python_float=False):
|
285 |
+
cdf = self.compute_cdf(expr)
|
286 |
+
items = list(cdf.items())
|
287 |
+
sorted_items = sorted(items, key=lambda val_cumprob: val_cumprob[1])
|
288 |
+
if python_float:
|
289 |
+
sorted_items = [(v, float(cum_prob))
|
290 |
+
for v, cum_prob in sorted_items]
|
291 |
+
return sorted_items
|
292 |
+
|
293 |
+
@cacheit
|
294 |
+
def compute_characteristic_function(self, expr):
|
295 |
+
d = self.compute_density(expr)
|
296 |
+
t = Dummy('t', real=True)
|
297 |
+
|
298 |
+
return Lambda(t, sum(exp(I*k*t)*v for k,v in d.items()))
|
299 |
+
|
300 |
+
@cacheit
|
301 |
+
def compute_moment_generating_function(self, expr):
|
302 |
+
d = self.compute_density(expr)
|
303 |
+
t = Dummy('t', real=True)
|
304 |
+
|
305 |
+
return Lambda(t, sum(exp(k*t)*v for k,v in d.items()))
|
306 |
+
|
307 |
+
def compute_expectation(self, expr, rvs=None, **kwargs):
|
308 |
+
rvs = rvs or self.values
|
309 |
+
expr = rv_subs(expr, rvs)
|
310 |
+
probs = [self.prob_of(elem) for elem in self.domain]
|
311 |
+
if isinstance(expr, (Logic, Relational)):
|
312 |
+
parse_domain = [tuple(elem)[0][1] for elem in self.domain]
|
313 |
+
bools = [expr.xreplace(dict(elem)) for elem in self.domain]
|
314 |
+
else:
|
315 |
+
parse_domain = [expr.xreplace(dict(elem)) for elem in self.domain]
|
316 |
+
bools = [True for elem in self.domain]
|
317 |
+
return sum([Piecewise((prob * elem, blv), (S.Zero, True))
|
318 |
+
for prob, elem, blv in zip(probs, parse_domain, bools)])
|
319 |
+
|
320 |
+
def compute_quantile(self, expr):
|
321 |
+
cdf = self.compute_cdf(expr)
|
322 |
+
p = Dummy('p', real=True)
|
323 |
+
set = ((nan, (p < 0) | (p > 1)),)
|
324 |
+
for key, value in cdf.items():
|
325 |
+
set = set + ((key, p <= value), )
|
326 |
+
return Lambda(p, Piecewise(*set))
|
327 |
+
|
328 |
+
def probability(self, condition):
|
329 |
+
cond_symbols = frozenset(rs.symbol for rs in random_symbols(condition))
|
330 |
+
cond = rv_subs(condition)
|
331 |
+
if not cond_symbols.issubset(self.symbols):
|
332 |
+
raise ValueError("Cannot compare foreign random symbols, %s"
|
333 |
+
%(str(cond_symbols - self.symbols)))
|
334 |
+
if isinstance(condition, Relational) and \
|
335 |
+
(not cond.free_symbols.issubset(self.domain.free_symbols)):
|
336 |
+
rv = condition.lhs if isinstance(condition.rhs, Symbol) else condition.rhs
|
337 |
+
return sum(Piecewise(
|
338 |
+
(self.prob_of(elem), condition.subs(rv, list(elem)[0][1])),
|
339 |
+
(S.Zero, True)) for elem in self.domain)
|
340 |
+
return sympify(sum(self.prob_of(elem) for elem in self.where(condition)))
|
341 |
+
|
342 |
+
def conditional_space(self, condition):
|
343 |
+
domain = self.where(condition)
|
344 |
+
prob = self.probability(condition)
|
345 |
+
density = {key: val / prob
|
346 |
+
for key, val in self._density.items() if domain._test(key)}
|
347 |
+
return FinitePSpace(domain, density)
|
348 |
+
|
349 |
+
def sample(self, size=(), library='scipy', seed=None):
|
350 |
+
"""
|
351 |
+
Internal sample method
|
352 |
+
|
353 |
+
Returns dictionary mapping RandomSymbol to realization value.
|
354 |
+
"""
|
355 |
+
return {self.value: self.distribution.sample(size, library, seed)}
|
356 |
+
|
357 |
+
|
358 |
+
class SingleFinitePSpace(SinglePSpace, FinitePSpace):
|
359 |
+
"""
|
360 |
+
A single finite probability space
|
361 |
+
|
362 |
+
Represents the probabilities of a set of random events that can be
|
363 |
+
attributed to a single variable/symbol.
|
364 |
+
|
365 |
+
This class is implemented by many of the standard FiniteRV types such as
|
366 |
+
Die, Bernoulli, Coin, etc....
|
367 |
+
"""
|
368 |
+
@property
|
369 |
+
def domain(self):
|
370 |
+
return SingleFiniteDomain(self.symbol, self.distribution.set)
|
371 |
+
|
372 |
+
@property
|
373 |
+
def _is_symbolic(self):
|
374 |
+
"""
|
375 |
+
Helper property to check if the distribution
|
376 |
+
of the random variable is having symbolic
|
377 |
+
dimension.
|
378 |
+
"""
|
379 |
+
return self.distribution.is_symbolic
|
380 |
+
|
381 |
+
@property
|
382 |
+
def distribution(self):
|
383 |
+
return self.args[1]
|
384 |
+
|
385 |
+
def pmf(self, expr):
|
386 |
+
return self.distribution.pmf(expr)
|
387 |
+
|
388 |
+
@property # type: ignore
|
389 |
+
@cacheit
|
390 |
+
def _density(self):
|
391 |
+
return {FiniteSet((self.symbol, val)): prob
|
392 |
+
for val, prob in self.distribution.dict.items()}
|
393 |
+
|
394 |
+
@cacheit
|
395 |
+
def compute_characteristic_function(self, expr):
|
396 |
+
if self._is_symbolic:
|
397 |
+
d = self.compute_density(expr)
|
398 |
+
t = Dummy('t', real=True)
|
399 |
+
ki = Dummy('ki')
|
400 |
+
return Lambda(t, Sum(d(ki)*exp(I*ki*t), (ki, self.args[1].low, self.args[1].high)))
|
401 |
+
expr = rv_subs(expr, self.values)
|
402 |
+
return FinitePSpace(self.domain, self.distribution).compute_characteristic_function(expr)
|
403 |
+
|
404 |
+
@cacheit
|
405 |
+
def compute_moment_generating_function(self, expr):
|
406 |
+
if self._is_symbolic:
|
407 |
+
d = self.compute_density(expr)
|
408 |
+
t = Dummy('t', real=True)
|
409 |
+
ki = Dummy('ki')
|
410 |
+
return Lambda(t, Sum(d(ki)*exp(ki*t), (ki, self.args[1].low, self.args[1].high)))
|
411 |
+
expr = rv_subs(expr, self.values)
|
412 |
+
return FinitePSpace(self.domain, self.distribution).compute_moment_generating_function(expr)
|
413 |
+
|
414 |
+
def compute_quantile(self, expr):
|
415 |
+
if self._is_symbolic:
|
416 |
+
raise NotImplementedError("Computing quantile for random variables "
|
417 |
+
"with symbolic dimension because the bounds of searching the required "
|
418 |
+
"value is undetermined.")
|
419 |
+
expr = rv_subs(expr, self.values)
|
420 |
+
return FinitePSpace(self.domain, self.distribution).compute_quantile(expr)
|
421 |
+
|
422 |
+
def compute_density(self, expr):
|
423 |
+
if self._is_symbolic:
|
424 |
+
rv = list(random_symbols(expr))[0]
|
425 |
+
k = Dummy('k', integer=True)
|
426 |
+
cond = True if not isinstance(expr, (Relational, Logic)) \
|
427 |
+
else expr.subs(rv, k)
|
428 |
+
return Lambda(k,
|
429 |
+
Piecewise((self.pmf(k), And(k >= self.args[1].low,
|
430 |
+
k <= self.args[1].high, cond)), (S.Zero, True)))
|
431 |
+
expr = rv_subs(expr, self.values)
|
432 |
+
return FinitePSpace(self.domain, self.distribution).compute_density(expr)
|
433 |
+
|
434 |
+
def compute_cdf(self, expr):
|
435 |
+
if self._is_symbolic:
|
436 |
+
d = self.compute_density(expr)
|
437 |
+
k = Dummy('k')
|
438 |
+
ki = Dummy('ki')
|
439 |
+
return Lambda(k, Sum(d(ki), (ki, self.args[1].low, k)))
|
440 |
+
expr = rv_subs(expr, self.values)
|
441 |
+
return FinitePSpace(self.domain, self.distribution).compute_cdf(expr)
|
442 |
+
|
443 |
+
def compute_expectation(self, expr, rvs=None, **kwargs):
|
444 |
+
if self._is_symbolic:
|
445 |
+
rv = random_symbols(expr)[0]
|
446 |
+
k = Dummy('k', integer=True)
|
447 |
+
expr = expr.subs(rv, k)
|
448 |
+
cond = True if not isinstance(expr, (Relational, Logic)) \
|
449 |
+
else expr
|
450 |
+
func = self.pmf(k) * k if cond != True else self.pmf(k) * expr
|
451 |
+
return Sum(Piecewise((func, cond), (S.Zero, True)),
|
452 |
+
(k, self.distribution.low, self.distribution.high)).doit()
|
453 |
+
|
454 |
+
expr = _sympify(expr)
|
455 |
+
expr = rv_subs(expr, rvs)
|
456 |
+
return FinitePSpace(self.domain, self.distribution).compute_expectation(expr, rvs, **kwargs)
|
457 |
+
|
458 |
+
def probability(self, condition):
|
459 |
+
if self._is_symbolic:
|
460 |
+
#TODO: Implement the mechanism for handling queries for symbolic sized distributions.
|
461 |
+
raise NotImplementedError("Currently, probability queries are not "
|
462 |
+
"supported for random variables with symbolic sized distributions.")
|
463 |
+
condition = rv_subs(condition)
|
464 |
+
return FinitePSpace(self.domain, self.distribution).probability(condition)
|
465 |
+
|
466 |
+
def conditional_space(self, condition):
|
467 |
+
"""
|
468 |
+
This method is used for transferring the
|
469 |
+
computation to probability method because
|
470 |
+
conditional space of random variables with
|
471 |
+
symbolic dimensions is currently not possible.
|
472 |
+
"""
|
473 |
+
if self._is_symbolic:
|
474 |
+
self
|
475 |
+
domain = self.where(condition)
|
476 |
+
prob = self.probability(condition)
|
477 |
+
density = {key: val / prob
|
478 |
+
for key, val in self._density.items() if domain._test(key)}
|
479 |
+
return FinitePSpace(domain, density)
|
480 |
+
|
481 |
+
|
482 |
+
class ProductFinitePSpace(IndependentProductPSpace, FinitePSpace):
|
483 |
+
"""
|
484 |
+
A collection of several independent finite probability spaces
|
485 |
+
"""
|
486 |
+
@property
|
487 |
+
def domain(self):
|
488 |
+
return ProductFiniteDomain(*[space.domain for space in self.spaces])
|
489 |
+
|
490 |
+
@property # type: ignore
|
491 |
+
@cacheit
|
492 |
+
def _density(self):
|
493 |
+
proditer = product(*[iter(space._density.items())
|
494 |
+
for space in self.spaces])
|
495 |
+
d = {}
|
496 |
+
for items in proditer:
|
497 |
+
elems, probs = list(zip(*items))
|
498 |
+
elem = sumsets(elems)
|
499 |
+
prob = Mul(*probs)
|
500 |
+
d[elem] = d.get(elem, S.Zero) + prob
|
501 |
+
return Dict(d)
|
502 |
+
|
503 |
+
@property # type: ignore
|
504 |
+
@cacheit
|
505 |
+
def density(self):
|
506 |
+
return Dict(self._density)
|
507 |
+
|
508 |
+
def probability(self, condition):
|
509 |
+
return FinitePSpace.probability(self, condition)
|
510 |
+
|
511 |
+
def compute_density(self, expr):
|
512 |
+
return FinitePSpace.compute_density(self, expr)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/frv_types.py
ADDED
@@ -0,0 +1,870 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Finite Discrete Random Variables - Prebuilt variable types
|
3 |
+
|
4 |
+
Contains
|
5 |
+
========
|
6 |
+
FiniteRV
|
7 |
+
DiscreteUniform
|
8 |
+
Die
|
9 |
+
Bernoulli
|
10 |
+
Coin
|
11 |
+
Binomial
|
12 |
+
BetaBinomial
|
13 |
+
Hypergeometric
|
14 |
+
Rademacher
|
15 |
+
IdealSoliton
|
16 |
+
RobustSoliton
|
17 |
+
"""
|
18 |
+
|
19 |
+
|
20 |
+
from sympy.core.cache import cacheit
|
21 |
+
from sympy.core.function import Lambda
|
22 |
+
from sympy.core.numbers import (Integer, Rational)
|
23 |
+
from sympy.core.relational import (Eq, Ge, Gt, Le, Lt)
|
24 |
+
from sympy.core.singleton import S
|
25 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
26 |
+
from sympy.core.sympify import sympify
|
27 |
+
from sympy.functions.combinatorial.factorials import binomial
|
28 |
+
from sympy.functions.elementary.exponential import log
|
29 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
30 |
+
from sympy.logic.boolalg import Or
|
31 |
+
from sympy.sets.contains import Contains
|
32 |
+
from sympy.sets.fancysets import Range
|
33 |
+
from sympy.sets.sets import (Intersection, Interval)
|
34 |
+
from sympy.functions.special.beta_functions import beta as beta_fn
|
35 |
+
from sympy.stats.frv import (SingleFiniteDistribution,
|
36 |
+
SingleFinitePSpace)
|
37 |
+
from sympy.stats.rv import _value_check, Density, is_random
|
38 |
+
from sympy.utilities.iterables import multiset
|
39 |
+
from sympy.utilities.misc import filldedent
|
40 |
+
|
41 |
+
|
42 |
+
__all__ = ['FiniteRV',
|
43 |
+
'DiscreteUniform',
|
44 |
+
'Die',
|
45 |
+
'Bernoulli',
|
46 |
+
'Coin',
|
47 |
+
'Binomial',
|
48 |
+
'BetaBinomial',
|
49 |
+
'Hypergeometric',
|
50 |
+
'Rademacher',
|
51 |
+
'IdealSoliton',
|
52 |
+
'RobustSoliton',
|
53 |
+
]
|
54 |
+
|
55 |
+
def rv(name, cls, *args, **kwargs):
|
56 |
+
args = list(map(sympify, args))
|
57 |
+
dist = cls(*args)
|
58 |
+
if kwargs.pop('check', True):
|
59 |
+
dist.check(*args)
|
60 |
+
pspace = SingleFinitePSpace(name, dist)
|
61 |
+
if any(is_random(arg) for arg in args):
|
62 |
+
from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
|
63 |
+
pspace = CompoundPSpace(name, CompoundDistribution(dist))
|
64 |
+
return pspace.value
|
65 |
+
|
66 |
+
class FiniteDistributionHandmade(SingleFiniteDistribution):
|
67 |
+
|
68 |
+
@property
|
69 |
+
def dict(self):
|
70 |
+
return self.args[0]
|
71 |
+
|
72 |
+
def pmf(self, x):
|
73 |
+
x = Symbol('x')
|
74 |
+
return Lambda(x, Piecewise(*(
|
75 |
+
[(v, Eq(k, x)) for k, v in self.dict.items()] + [(S.Zero, True)])))
|
76 |
+
|
77 |
+
@property
|
78 |
+
def set(self):
|
79 |
+
return set(self.dict.keys())
|
80 |
+
|
81 |
+
@staticmethod
|
82 |
+
def check(density):
|
83 |
+
for p in density.values():
|
84 |
+
_value_check((p >= 0, p <= 1),
|
85 |
+
"Probability at a point must be between 0 and 1.")
|
86 |
+
val = sum(density.values())
|
87 |
+
_value_check(Eq(val, 1) != S.false, "Total Probability must be 1.")
|
88 |
+
|
89 |
+
def FiniteRV(name, density, **kwargs):
|
90 |
+
r"""
|
91 |
+
Create a Finite Random Variable given a dict representing the density.
|
92 |
+
|
93 |
+
Parameters
|
94 |
+
==========
|
95 |
+
|
96 |
+
name : Symbol
|
97 |
+
Represents name of the random variable.
|
98 |
+
density : dict
|
99 |
+
Dictionary containing the pdf of finite distribution
|
100 |
+
check : bool
|
101 |
+
If True, it will check whether the given density
|
102 |
+
integrates to 1 over the given set. If False, it
|
103 |
+
will not perform this check. Default is False.
|
104 |
+
|
105 |
+
Examples
|
106 |
+
========
|
107 |
+
|
108 |
+
>>> from sympy.stats import FiniteRV, P, E
|
109 |
+
|
110 |
+
>>> density = {0: .1, 1: .2, 2: .3, 3: .4}
|
111 |
+
>>> X = FiniteRV('X', density)
|
112 |
+
|
113 |
+
>>> E(X)
|
114 |
+
2.00000000000000
|
115 |
+
>>> P(X >= 2)
|
116 |
+
0.700000000000000
|
117 |
+
|
118 |
+
Returns
|
119 |
+
=======
|
120 |
+
|
121 |
+
RandomSymbol
|
122 |
+
|
123 |
+
"""
|
124 |
+
# have a default of False while `rv` should have a default of True
|
125 |
+
kwargs['check'] = kwargs.pop('check', False)
|
126 |
+
return rv(name, FiniteDistributionHandmade, density, **kwargs)
|
127 |
+
|
128 |
+
class DiscreteUniformDistribution(SingleFiniteDistribution):
|
129 |
+
|
130 |
+
@staticmethod
|
131 |
+
def check(*args):
|
132 |
+
# not using _value_check since there is a
|
133 |
+
# suggestion for the user
|
134 |
+
if len(set(args)) != len(args):
|
135 |
+
weights = multiset(args)
|
136 |
+
n = Integer(len(args))
|
137 |
+
for k in weights:
|
138 |
+
weights[k] /= n
|
139 |
+
raise ValueError(filldedent("""
|
140 |
+
Repeated args detected but set expected. For a
|
141 |
+
distribution having different weights for each
|
142 |
+
item use the following:""") + (
|
143 |
+
'\nS("FiniteRV(%s, %s)")' % ("'X'", weights)))
|
144 |
+
|
145 |
+
@property
|
146 |
+
def p(self):
|
147 |
+
return Rational(1, len(self.args))
|
148 |
+
|
149 |
+
@property # type: ignore
|
150 |
+
@cacheit
|
151 |
+
def dict(self):
|
152 |
+
return {k: self.p for k in self.set}
|
153 |
+
|
154 |
+
@property
|
155 |
+
def set(self):
|
156 |
+
return set(self.args)
|
157 |
+
|
158 |
+
def pmf(self, x):
|
159 |
+
if x in self.args:
|
160 |
+
return self.p
|
161 |
+
else:
|
162 |
+
return S.Zero
|
163 |
+
|
164 |
+
|
165 |
+
def DiscreteUniform(name, items):
|
166 |
+
r"""
|
167 |
+
Create a Finite Random Variable representing a uniform distribution over
|
168 |
+
the input set.
|
169 |
+
|
170 |
+
Parameters
|
171 |
+
==========
|
172 |
+
|
173 |
+
items : list/tuple
|
174 |
+
Items over which Uniform distribution is to be made
|
175 |
+
|
176 |
+
Examples
|
177 |
+
========
|
178 |
+
|
179 |
+
>>> from sympy.stats import DiscreteUniform, density
|
180 |
+
>>> from sympy import symbols
|
181 |
+
|
182 |
+
>>> X = DiscreteUniform('X', symbols('a b c')) # equally likely over a, b, c
|
183 |
+
>>> density(X).dict
|
184 |
+
{a: 1/3, b: 1/3, c: 1/3}
|
185 |
+
|
186 |
+
>>> Y = DiscreteUniform('Y', list(range(5))) # distribution over a range
|
187 |
+
>>> density(Y).dict
|
188 |
+
{0: 1/5, 1: 1/5, 2: 1/5, 3: 1/5, 4: 1/5}
|
189 |
+
|
190 |
+
Returns
|
191 |
+
=======
|
192 |
+
|
193 |
+
RandomSymbol
|
194 |
+
|
195 |
+
References
|
196 |
+
==========
|
197 |
+
|
198 |
+
.. [1] https://en.wikipedia.org/wiki/Discrete_uniform_distribution
|
199 |
+
.. [2] https://mathworld.wolfram.com/DiscreteUniformDistribution.html
|
200 |
+
|
201 |
+
"""
|
202 |
+
return rv(name, DiscreteUniformDistribution, *items)
|
203 |
+
|
204 |
+
|
205 |
+
class DieDistribution(SingleFiniteDistribution):
|
206 |
+
_argnames = ('sides',)
|
207 |
+
|
208 |
+
@staticmethod
|
209 |
+
def check(sides):
|
210 |
+
_value_check((sides.is_positive, sides.is_integer),
|
211 |
+
"number of sides must be a positive integer.")
|
212 |
+
|
213 |
+
@property
|
214 |
+
def is_symbolic(self):
|
215 |
+
return not self.sides.is_number
|
216 |
+
|
217 |
+
@property
|
218 |
+
def high(self):
|
219 |
+
return self.sides
|
220 |
+
|
221 |
+
@property
|
222 |
+
def low(self):
|
223 |
+
return S.One
|
224 |
+
|
225 |
+
@property
|
226 |
+
def set(self):
|
227 |
+
if self.is_symbolic:
|
228 |
+
return Intersection(S.Naturals0, Interval(0, self.sides))
|
229 |
+
return set(map(Integer, range(1, self.sides + 1)))
|
230 |
+
|
231 |
+
def pmf(self, x):
|
232 |
+
x = sympify(x)
|
233 |
+
if not (x.is_number or x.is_Symbol or is_random(x)):
|
234 |
+
raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or "
|
235 |
+
"'RandomSymbol' not %s" % (type(x)))
|
236 |
+
cond = Ge(x, 1) & Le(x, self.sides) & Contains(x, S.Integers)
|
237 |
+
return Piecewise((S.One/self.sides, cond), (S.Zero, True))
|
238 |
+
|
239 |
+
def Die(name, sides=6):
|
240 |
+
r"""
|
241 |
+
Create a Finite Random Variable representing a fair die.
|
242 |
+
|
243 |
+
Parameters
|
244 |
+
==========
|
245 |
+
|
246 |
+
sides : Integer
|
247 |
+
Represents the number of sides of the Die, by default is 6
|
248 |
+
|
249 |
+
Examples
|
250 |
+
========
|
251 |
+
|
252 |
+
>>> from sympy.stats import Die, density
|
253 |
+
>>> from sympy import Symbol
|
254 |
+
|
255 |
+
>>> D6 = Die('D6', 6) # Six sided Die
|
256 |
+
>>> density(D6).dict
|
257 |
+
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
|
258 |
+
|
259 |
+
>>> D4 = Die('D4', 4) # Four sided Die
|
260 |
+
>>> density(D4).dict
|
261 |
+
{1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4}
|
262 |
+
|
263 |
+
>>> n = Symbol('n', positive=True, integer=True)
|
264 |
+
>>> Dn = Die('Dn', n) # n sided Die
|
265 |
+
>>> density(Dn).dict
|
266 |
+
Density(DieDistribution(n))
|
267 |
+
>>> density(Dn).dict.subs(n, 4).doit()
|
268 |
+
{1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4}
|
269 |
+
|
270 |
+
Returns
|
271 |
+
=======
|
272 |
+
|
273 |
+
RandomSymbol
|
274 |
+
"""
|
275 |
+
|
276 |
+
return rv(name, DieDistribution, sides)
|
277 |
+
|
278 |
+
|
279 |
+
class BernoulliDistribution(SingleFiniteDistribution):
|
280 |
+
_argnames = ('p', 'succ', 'fail')
|
281 |
+
|
282 |
+
@staticmethod
|
283 |
+
def check(p, succ, fail):
|
284 |
+
_value_check((p >= 0, p <= 1),
|
285 |
+
"p should be in range [0, 1].")
|
286 |
+
|
287 |
+
@property
|
288 |
+
def set(self):
|
289 |
+
return {self.succ, self.fail}
|
290 |
+
|
291 |
+
def pmf(self, x):
|
292 |
+
if isinstance(self.succ, Symbol) and isinstance(self.fail, Symbol):
|
293 |
+
return Piecewise((self.p, x == self.succ),
|
294 |
+
(1 - self.p, x == self.fail),
|
295 |
+
(S.Zero, True))
|
296 |
+
return Piecewise((self.p, Eq(x, self.succ)),
|
297 |
+
(1 - self.p, Eq(x, self.fail)),
|
298 |
+
(S.Zero, True))
|
299 |
+
|
300 |
+
|
301 |
+
def Bernoulli(name, p, succ=1, fail=0):
|
302 |
+
r"""
|
303 |
+
Create a Finite Random Variable representing a Bernoulli process.
|
304 |
+
|
305 |
+
Parameters
|
306 |
+
==========
|
307 |
+
|
308 |
+
p : Rational number between 0 and 1
|
309 |
+
Represents probability of success
|
310 |
+
succ : Integer/symbol/string
|
311 |
+
Represents event of success
|
312 |
+
fail : Integer/symbol/string
|
313 |
+
Represents event of failure
|
314 |
+
|
315 |
+
Examples
|
316 |
+
========
|
317 |
+
|
318 |
+
>>> from sympy.stats import Bernoulli, density
|
319 |
+
>>> from sympy import S
|
320 |
+
|
321 |
+
>>> X = Bernoulli('X', S(3)/4) # 1-0 Bernoulli variable, probability = 3/4
|
322 |
+
>>> density(X).dict
|
323 |
+
{0: 1/4, 1: 3/4}
|
324 |
+
|
325 |
+
>>> X = Bernoulli('X', S.Half, 'Heads', 'Tails') # A fair coin toss
|
326 |
+
>>> density(X).dict
|
327 |
+
{Heads: 1/2, Tails: 1/2}
|
328 |
+
|
329 |
+
Returns
|
330 |
+
=======
|
331 |
+
|
332 |
+
RandomSymbol
|
333 |
+
|
334 |
+
References
|
335 |
+
==========
|
336 |
+
|
337 |
+
.. [1] https://en.wikipedia.org/wiki/Bernoulli_distribution
|
338 |
+
.. [2] https://mathworld.wolfram.com/BernoulliDistribution.html
|
339 |
+
|
340 |
+
"""
|
341 |
+
|
342 |
+
return rv(name, BernoulliDistribution, p, succ, fail)
|
343 |
+
|
344 |
+
|
345 |
+
def Coin(name, p=S.Half):
|
346 |
+
r"""
|
347 |
+
Create a Finite Random Variable representing a Coin toss.
|
348 |
+
|
349 |
+
Parameters
|
350 |
+
==========
|
351 |
+
|
352 |
+
p : Rational Number between 0 and 1
|
353 |
+
Represents probability of getting "Heads", by default is Half
|
354 |
+
|
355 |
+
Examples
|
356 |
+
========
|
357 |
+
|
358 |
+
>>> from sympy.stats import Coin, density
|
359 |
+
>>> from sympy import Rational
|
360 |
+
|
361 |
+
>>> C = Coin('C') # A fair coin toss
|
362 |
+
>>> density(C).dict
|
363 |
+
{H: 1/2, T: 1/2}
|
364 |
+
|
365 |
+
>>> C2 = Coin('C2', Rational(3, 5)) # An unfair coin
|
366 |
+
>>> density(C2).dict
|
367 |
+
{H: 3/5, T: 2/5}
|
368 |
+
|
369 |
+
Returns
|
370 |
+
=======
|
371 |
+
|
372 |
+
RandomSymbol
|
373 |
+
|
374 |
+
See Also
|
375 |
+
========
|
376 |
+
|
377 |
+
sympy.stats.Binomial
|
378 |
+
|
379 |
+
References
|
380 |
+
==========
|
381 |
+
|
382 |
+
.. [1] https://en.wikipedia.org/wiki/Coin_flipping
|
383 |
+
|
384 |
+
"""
|
385 |
+
return rv(name, BernoulliDistribution, p, 'H', 'T')
|
386 |
+
|
387 |
+
|
388 |
+
class BinomialDistribution(SingleFiniteDistribution):
|
389 |
+
_argnames = ('n', 'p', 'succ', 'fail')
|
390 |
+
|
391 |
+
@staticmethod
|
392 |
+
def check(n, p, succ, fail):
|
393 |
+
_value_check((n.is_integer, n.is_nonnegative),
|
394 |
+
"'n' must be nonnegative integer.")
|
395 |
+
_value_check((p <= 1, p >= 0),
|
396 |
+
"p should be in range [0, 1].")
|
397 |
+
|
398 |
+
@property
|
399 |
+
def high(self):
|
400 |
+
return self.n
|
401 |
+
|
402 |
+
@property
|
403 |
+
def low(self):
|
404 |
+
return S.Zero
|
405 |
+
|
406 |
+
@property
|
407 |
+
def is_symbolic(self):
|
408 |
+
return not self.n.is_number
|
409 |
+
|
410 |
+
@property
|
411 |
+
def set(self):
|
412 |
+
if self.is_symbolic:
|
413 |
+
return Intersection(S.Naturals0, Interval(0, self.n))
|
414 |
+
return set(self.dict.keys())
|
415 |
+
|
416 |
+
def pmf(self, x):
|
417 |
+
n, p = self.n, self.p
|
418 |
+
x = sympify(x)
|
419 |
+
if not (x.is_number or x.is_Symbol or is_random(x)):
|
420 |
+
raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or "
|
421 |
+
"'RandomSymbol' not %s" % (type(x)))
|
422 |
+
cond = Ge(x, 0) & Le(x, n) & Contains(x, S.Integers)
|
423 |
+
return Piecewise((binomial(n, x) * p**x * (1 - p)**(n - x), cond), (S.Zero, True))
|
424 |
+
|
425 |
+
@property # type: ignore
|
426 |
+
@cacheit
|
427 |
+
def dict(self):
|
428 |
+
if self.is_symbolic:
|
429 |
+
return Density(self)
|
430 |
+
return {k*self.succ + (self.n-k)*self.fail: self.pmf(k)
|
431 |
+
for k in range(0, self.n + 1)}
|
432 |
+
|
433 |
+
|
434 |
+
def Binomial(name, n, p, succ=1, fail=0):
|
435 |
+
r"""
|
436 |
+
Create a Finite Random Variable representing a binomial distribution.
|
437 |
+
|
438 |
+
Parameters
|
439 |
+
==========
|
440 |
+
|
441 |
+
n : Positive Integer
|
442 |
+
Represents number of trials
|
443 |
+
p : Rational Number between 0 and 1
|
444 |
+
Represents probability of success
|
445 |
+
succ : Integer/symbol/string
|
446 |
+
Represents event of success, by default is 1
|
447 |
+
fail : Integer/symbol/string
|
448 |
+
Represents event of failure, by default is 0
|
449 |
+
|
450 |
+
Examples
|
451 |
+
========
|
452 |
+
|
453 |
+
>>> from sympy.stats import Binomial, density
|
454 |
+
>>> from sympy import S, Symbol
|
455 |
+
|
456 |
+
>>> X = Binomial('X', 4, S.Half) # Four "coin flips"
|
457 |
+
>>> density(X).dict
|
458 |
+
{0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16}
|
459 |
+
|
460 |
+
>>> n = Symbol('n', positive=True, integer=True)
|
461 |
+
>>> p = Symbol('p', positive=True)
|
462 |
+
>>> X = Binomial('X', n, S.Half) # n "coin flips"
|
463 |
+
>>> density(X).dict
|
464 |
+
Density(BinomialDistribution(n, 1/2, 1, 0))
|
465 |
+
>>> density(X).dict.subs(n, 4).doit()
|
466 |
+
{0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16}
|
467 |
+
|
468 |
+
Returns
|
469 |
+
=======
|
470 |
+
|
471 |
+
RandomSymbol
|
472 |
+
|
473 |
+
References
|
474 |
+
==========
|
475 |
+
|
476 |
+
.. [1] https://en.wikipedia.org/wiki/Binomial_distribution
|
477 |
+
.. [2] https://mathworld.wolfram.com/BinomialDistribution.html
|
478 |
+
|
479 |
+
"""
|
480 |
+
|
481 |
+
return rv(name, BinomialDistribution, n, p, succ, fail)
|
482 |
+
|
483 |
+
#-------------------------------------------------------------------------------
|
484 |
+
# Beta-binomial distribution ----------------------------------------------------------
|
485 |
+
|
486 |
+
class BetaBinomialDistribution(SingleFiniteDistribution):
|
487 |
+
_argnames = ('n', 'alpha', 'beta')
|
488 |
+
|
489 |
+
@staticmethod
|
490 |
+
def check(n, alpha, beta):
|
491 |
+
_value_check((n.is_integer, n.is_nonnegative),
|
492 |
+
"'n' must be nonnegative integer. n = %s." % str(n))
|
493 |
+
_value_check((alpha > 0),
|
494 |
+
"'alpha' must be: alpha > 0 . alpha = %s" % str(alpha))
|
495 |
+
_value_check((beta > 0),
|
496 |
+
"'beta' must be: beta > 0 . beta = %s" % str(beta))
|
497 |
+
|
498 |
+
@property
|
499 |
+
def high(self):
|
500 |
+
return self.n
|
501 |
+
|
502 |
+
@property
|
503 |
+
def low(self):
|
504 |
+
return S.Zero
|
505 |
+
|
506 |
+
@property
|
507 |
+
def is_symbolic(self):
|
508 |
+
return not self.n.is_number
|
509 |
+
|
510 |
+
@property
|
511 |
+
def set(self):
|
512 |
+
if self.is_symbolic:
|
513 |
+
return Intersection(S.Naturals0, Interval(0, self.n))
|
514 |
+
return set(map(Integer, range(self.n + 1)))
|
515 |
+
|
516 |
+
def pmf(self, k):
|
517 |
+
n, a, b = self.n, self.alpha, self.beta
|
518 |
+
return binomial(n, k) * beta_fn(k + a, n - k + b) / beta_fn(a, b)
|
519 |
+
|
520 |
+
|
521 |
+
def BetaBinomial(name, n, alpha, beta):
|
522 |
+
r"""
|
523 |
+
Create a Finite Random Variable representing a Beta-binomial distribution.
|
524 |
+
|
525 |
+
Parameters
|
526 |
+
==========
|
527 |
+
|
528 |
+
n : Positive Integer
|
529 |
+
Represents number of trials
|
530 |
+
alpha : Real positive number
|
531 |
+
beta : Real positive number
|
532 |
+
|
533 |
+
Examples
|
534 |
+
========
|
535 |
+
|
536 |
+
>>> from sympy.stats import BetaBinomial, density
|
537 |
+
|
538 |
+
>>> X = BetaBinomial('X', 2, 1, 1)
|
539 |
+
>>> density(X).dict
|
540 |
+
{0: 1/3, 1: 2*beta(2, 2), 2: 1/3}
|
541 |
+
|
542 |
+
Returns
|
543 |
+
=======
|
544 |
+
|
545 |
+
RandomSymbol
|
546 |
+
|
547 |
+
References
|
548 |
+
==========
|
549 |
+
|
550 |
+
.. [1] https://en.wikipedia.org/wiki/Beta-binomial_distribution
|
551 |
+
.. [2] https://mathworld.wolfram.com/BetaBinomialDistribution.html
|
552 |
+
|
553 |
+
"""
|
554 |
+
|
555 |
+
return rv(name, BetaBinomialDistribution, n, alpha, beta)
|
556 |
+
|
557 |
+
|
558 |
+
class HypergeometricDistribution(SingleFiniteDistribution):
|
559 |
+
_argnames = ('N', 'm', 'n')
|
560 |
+
|
561 |
+
@staticmethod
|
562 |
+
def check(n, N, m):
|
563 |
+
_value_check((N.is_integer, N.is_nonnegative),
|
564 |
+
"'N' must be nonnegative integer. N = %s." % str(n))
|
565 |
+
_value_check((n.is_integer, n.is_nonnegative),
|
566 |
+
"'n' must be nonnegative integer. n = %s." % str(n))
|
567 |
+
_value_check((m.is_integer, m.is_nonnegative),
|
568 |
+
"'m' must be nonnegative integer. m = %s." % str(n))
|
569 |
+
|
570 |
+
@property
|
571 |
+
def is_symbolic(self):
|
572 |
+
return not all(x.is_number for x in (self.N, self.m, self.n))
|
573 |
+
|
574 |
+
@property
|
575 |
+
def high(self):
|
576 |
+
return Piecewise((self.n, Lt(self.n, self.m) != False), (self.m, True))
|
577 |
+
|
578 |
+
@property
|
579 |
+
def low(self):
|
580 |
+
return Piecewise((0, Gt(0, self.n + self.m - self.N) != False), (self.n + self.m - self.N, True))
|
581 |
+
|
582 |
+
@property
|
583 |
+
def set(self):
|
584 |
+
N, m, n = self.N, self.m, self.n
|
585 |
+
if self.is_symbolic:
|
586 |
+
return Intersection(S.Naturals0, Interval(self.low, self.high))
|
587 |
+
return set(range(max(0, n + m - N), min(n, m) + 1))
|
588 |
+
|
589 |
+
def pmf(self, k):
|
590 |
+
N, m, n = self.N, self.m, self.n
|
591 |
+
return S(binomial(m, k) * binomial(N - m, n - k))/binomial(N, n)
|
592 |
+
|
593 |
+
|
594 |
+
def Hypergeometric(name, N, m, n):
|
595 |
+
r"""
|
596 |
+
Create a Finite Random Variable representing a hypergeometric distribution.
|
597 |
+
|
598 |
+
Parameters
|
599 |
+
==========
|
600 |
+
|
601 |
+
N : Positive Integer
|
602 |
+
Represents finite population of size N.
|
603 |
+
m : Positive Integer
|
604 |
+
Represents number of trials with required feature.
|
605 |
+
n : Positive Integer
|
606 |
+
Represents numbers of draws.
|
607 |
+
|
608 |
+
|
609 |
+
Examples
|
610 |
+
========
|
611 |
+
|
612 |
+
>>> from sympy.stats import Hypergeometric, density
|
613 |
+
|
614 |
+
>>> X = Hypergeometric('X', 10, 5, 3) # 10 marbles, 5 white (success), 3 draws
|
615 |
+
>>> density(X).dict
|
616 |
+
{0: 1/12, 1: 5/12, 2: 5/12, 3: 1/12}
|
617 |
+
|
618 |
+
Returns
|
619 |
+
=======
|
620 |
+
|
621 |
+
RandomSymbol
|
622 |
+
|
623 |
+
References
|
624 |
+
==========
|
625 |
+
|
626 |
+
.. [1] https://en.wikipedia.org/wiki/Hypergeometric_distribution
|
627 |
+
.. [2] https://mathworld.wolfram.com/HypergeometricDistribution.html
|
628 |
+
|
629 |
+
"""
|
630 |
+
return rv(name, HypergeometricDistribution, N, m, n)
|
631 |
+
|
632 |
+
|
633 |
+
class RademacherDistribution(SingleFiniteDistribution):
|
634 |
+
|
635 |
+
@property
|
636 |
+
def set(self):
|
637 |
+
return {-1, 1}
|
638 |
+
|
639 |
+
@property
|
640 |
+
def pmf(self):
|
641 |
+
k = Dummy('k')
|
642 |
+
return Lambda(k, Piecewise((S.Half, Or(Eq(k, -1), Eq(k, 1))), (S.Zero, True)))
|
643 |
+
|
644 |
+
def Rademacher(name):
|
645 |
+
r"""
|
646 |
+
Create a Finite Random Variable representing a Rademacher distribution.
|
647 |
+
|
648 |
+
Examples
|
649 |
+
========
|
650 |
+
|
651 |
+
>>> from sympy.stats import Rademacher, density
|
652 |
+
|
653 |
+
>>> X = Rademacher('X')
|
654 |
+
>>> density(X).dict
|
655 |
+
{-1: 1/2, 1: 1/2}
|
656 |
+
|
657 |
+
Returns
|
658 |
+
=======
|
659 |
+
|
660 |
+
RandomSymbol
|
661 |
+
|
662 |
+
See Also
|
663 |
+
========
|
664 |
+
|
665 |
+
sympy.stats.Bernoulli
|
666 |
+
|
667 |
+
References
|
668 |
+
==========
|
669 |
+
|
670 |
+
.. [1] https://en.wikipedia.org/wiki/Rademacher_distribution
|
671 |
+
|
672 |
+
"""
|
673 |
+
return rv(name, RademacherDistribution)
|
674 |
+
|
675 |
+
class IdealSolitonDistribution(SingleFiniteDistribution):
|
676 |
+
_argnames = ('k',)
|
677 |
+
|
678 |
+
@staticmethod
|
679 |
+
def check(k):
|
680 |
+
_value_check(k.is_integer and k.is_positive,
|
681 |
+
"'k' must be a positive integer.")
|
682 |
+
|
683 |
+
@property
|
684 |
+
def low(self):
|
685 |
+
return S.One
|
686 |
+
|
687 |
+
@property
|
688 |
+
def high(self):
|
689 |
+
return self.k
|
690 |
+
|
691 |
+
@property
|
692 |
+
def set(self):
|
693 |
+
return set(map(Integer, range(1, self.k + 1)))
|
694 |
+
|
695 |
+
@property # type: ignore
|
696 |
+
@cacheit
|
697 |
+
def dict(self):
|
698 |
+
if self.k.is_Symbol:
|
699 |
+
return Density(self)
|
700 |
+
d = {1: Rational(1, self.k)}
|
701 |
+
d.update({i: Rational(1, i*(i - 1)) for i in range(2, self.k + 1)})
|
702 |
+
return d
|
703 |
+
|
704 |
+
def pmf(self, x):
|
705 |
+
x = sympify(x)
|
706 |
+
if not (x.is_number or x.is_Symbol or is_random(x)):
|
707 |
+
raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or "
|
708 |
+
"'RandomSymbol' not %s" % (type(x)))
|
709 |
+
cond1 = Eq(x, 1) & x.is_integer
|
710 |
+
cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer
|
711 |
+
return Piecewise((1/self.k, cond1), (1/(x*(x - 1)), cond2), (S.Zero, True))
|
712 |
+
|
713 |
+
def IdealSoliton(name, k):
|
714 |
+
r"""
|
715 |
+
Create a Finite Random Variable of Ideal Soliton Distribution
|
716 |
+
|
717 |
+
Parameters
|
718 |
+
==========
|
719 |
+
|
720 |
+
k : Positive Integer
|
721 |
+
Represents the number of input symbols in an LT (Luby Transform) code.
|
722 |
+
|
723 |
+
Examples
|
724 |
+
========
|
725 |
+
|
726 |
+
>>> from sympy.stats import IdealSoliton, density, P, E
|
727 |
+
>>> sol = IdealSoliton('sol', 5)
|
728 |
+
>>> density(sol).dict
|
729 |
+
{1: 1/5, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20}
|
730 |
+
>>> density(sol).set
|
731 |
+
{1, 2, 3, 4, 5}
|
732 |
+
|
733 |
+
>>> from sympy import Symbol
|
734 |
+
>>> k = Symbol('k', positive=True, integer=True)
|
735 |
+
>>> sol = IdealSoliton('sol', k)
|
736 |
+
>>> density(sol).dict
|
737 |
+
Density(IdealSolitonDistribution(k))
|
738 |
+
>>> density(sol).dict.subs(k, 10).doit()
|
739 |
+
{1: 1/10, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20, 6: 1/30, 7: 1/42, 8: 1/56, 9: 1/72, 10: 1/90}
|
740 |
+
|
741 |
+
>>> E(sol.subs(k, 10))
|
742 |
+
7381/2520
|
743 |
+
|
744 |
+
>>> P(sol.subs(k, 4) > 2)
|
745 |
+
1/4
|
746 |
+
|
747 |
+
Returns
|
748 |
+
=======
|
749 |
+
|
750 |
+
RandomSymbol
|
751 |
+
|
752 |
+
References
|
753 |
+
==========
|
754 |
+
|
755 |
+
.. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Ideal_distribution
|
756 |
+
.. [2] https://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf
|
757 |
+
|
758 |
+
"""
|
759 |
+
return rv(name, IdealSolitonDistribution, k)
|
760 |
+
|
761 |
+
class RobustSolitonDistribution(SingleFiniteDistribution):
|
762 |
+
_argnames= ('k', 'delta', 'c')
|
763 |
+
|
764 |
+
@staticmethod
|
765 |
+
def check(k, delta, c):
|
766 |
+
_value_check(k.is_integer and k.is_positive,
|
767 |
+
"'k' must be a positive integer")
|
768 |
+
_value_check(Gt(delta, 0) and Le(delta, 1),
|
769 |
+
"'delta' must be a real number in the interval (0,1)")
|
770 |
+
_value_check(c.is_positive,
|
771 |
+
"'c' must be a positive real number.")
|
772 |
+
|
773 |
+
@property
|
774 |
+
def R(self):
|
775 |
+
return self.c * log(self.k/self.delta) * self.k**0.5
|
776 |
+
|
777 |
+
@property
|
778 |
+
def Z(self):
|
779 |
+
z = 0
|
780 |
+
for i in Range(1, round(self.k/self.R)):
|
781 |
+
z += (1/i)
|
782 |
+
z += log(self.R/self.delta)
|
783 |
+
return 1 + z * self.R/self.k
|
784 |
+
|
785 |
+
@property
|
786 |
+
def low(self):
|
787 |
+
return S.One
|
788 |
+
|
789 |
+
@property
|
790 |
+
def high(self):
|
791 |
+
return self.k
|
792 |
+
|
793 |
+
@property
|
794 |
+
def set(self):
|
795 |
+
return set(map(Integer, range(1, self.k + 1)))
|
796 |
+
|
797 |
+
@property
|
798 |
+
def is_symbolic(self):
|
799 |
+
return not (self.k.is_number and self.c.is_number and self.delta.is_number)
|
800 |
+
|
801 |
+
def pmf(self, x):
|
802 |
+
x = sympify(x)
|
803 |
+
if not (x.is_number or x.is_Symbol or is_random(x)):
|
804 |
+
raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or "
|
805 |
+
"'RandomSymbol' not %s" % (type(x)))
|
806 |
+
|
807 |
+
cond1 = Eq(x, 1) & x.is_integer
|
808 |
+
cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer
|
809 |
+
rho = Piecewise((Rational(1, self.k), cond1), (Rational(1, x*(x-1)), cond2), (S.Zero, True))
|
810 |
+
|
811 |
+
cond1 = Ge(x, 1) & Le(x, round(self.k/self.R)-1)
|
812 |
+
cond2 = Eq(x, round(self.k/self.R))
|
813 |
+
tau = Piecewise((self.R/(self.k * x), cond1), (self.R * log(self.R/self.delta)/self.k, cond2), (S.Zero, True))
|
814 |
+
|
815 |
+
return (rho + tau)/self.Z
|
816 |
+
|
817 |
+
def RobustSoliton(name, k, delta, c):
|
818 |
+
r'''
|
819 |
+
Create a Finite Random Variable of Robust Soliton Distribution
|
820 |
+
|
821 |
+
Parameters
|
822 |
+
==========
|
823 |
+
|
824 |
+
k : Positive Integer
|
825 |
+
Represents the number of input symbols in an LT (Luby Transform) code.
|
826 |
+
delta : Positive Rational Number
|
827 |
+
Represents the failure probability. Must be in the interval (0,1).
|
828 |
+
c : Positive Rational Number
|
829 |
+
Constant of proportionality. Values close to 1 are recommended
|
830 |
+
|
831 |
+
Examples
|
832 |
+
========
|
833 |
+
|
834 |
+
>>> from sympy.stats import RobustSoliton, density, P, E
|
835 |
+
>>> robSol = RobustSoliton('robSol', 5, 0.5, 0.01)
|
836 |
+
>>> density(robSol).dict
|
837 |
+
{1: 0.204253668152708, 2: 0.490631107897393, 3: 0.165210624506162, 4: 0.0834387731899302, 5: 0.0505633404760675}
|
838 |
+
>>> density(robSol).set
|
839 |
+
{1, 2, 3, 4, 5}
|
840 |
+
|
841 |
+
>>> from sympy import Symbol
|
842 |
+
>>> k = Symbol('k', positive=True, integer=True)
|
843 |
+
>>> c = Symbol('c', positive=True)
|
844 |
+
>>> robSol = RobustSoliton('robSol', k, 0.5, c)
|
845 |
+
>>> density(robSol).dict
|
846 |
+
Density(RobustSolitonDistribution(k, 0.5, c))
|
847 |
+
>>> density(robSol).dict.subs(k, 10).subs(c, 0.03).doit()
|
848 |
+
{1: 0.116641095387194, 2: 0.467045731687165, 3: 0.159984123349381, 4: 0.0821431680681869, 5: 0.0505765646770100,
|
849 |
+
6: 0.0345781523420719, 7: 0.0253132820710503, 8: 0.0194459129233227, 9: 0.0154831166726115, 10: 0.0126733075238887}
|
850 |
+
|
851 |
+
>>> E(robSol.subs(k, 10).subs(c, 0.05))
|
852 |
+
2.91358846104106
|
853 |
+
|
854 |
+
>>> P(robSol.subs(k, 4).subs(c, 0.1) > 2)
|
855 |
+
0.243650614389834
|
856 |
+
|
857 |
+
Returns
|
858 |
+
=======
|
859 |
+
|
860 |
+
RandomSymbol
|
861 |
+
|
862 |
+
References
|
863 |
+
==========
|
864 |
+
|
865 |
+
.. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Robust_distribution
|
866 |
+
.. [2] https://www.inference.org.uk/mackay/itprnn/ps/588.596.pdf
|
867 |
+
.. [3] https://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf
|
868 |
+
|
869 |
+
'''
|
870 |
+
return rv(name, RobustSolitonDistribution, k, delta, c)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/joint_rv.py
ADDED
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
from math import prod
|
12 |
+
|
13 |
+
from sympy.core.basic import Basic
|
14 |
+
from sympy.core.function import Lambda
|
15 |
+
from sympy.core.singleton import S
|
16 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
17 |
+
from sympy.core.sympify import sympify
|
18 |
+
from sympy.sets.sets import ProductSet
|
19 |
+
from sympy.tensor.indexed import Indexed
|
20 |
+
from sympy.concrete.products import Product
|
21 |
+
from sympy.concrete.summations import Sum, summation
|
22 |
+
from sympy.core.containers import Tuple
|
23 |
+
from sympy.integrals.integrals import Integral, integrate
|
24 |
+
from sympy.matrices import ImmutableMatrix, matrix2numpy, list2numpy
|
25 |
+
from sympy.stats.crv import SingleContinuousDistribution, SingleContinuousPSpace
|
26 |
+
from sympy.stats.drv import SingleDiscreteDistribution, SingleDiscretePSpace
|
27 |
+
from sympy.stats.rv import (ProductPSpace, NamedArgsMixin, Distribution,
|
28 |
+
ProductDomain, RandomSymbol, random_symbols,
|
29 |
+
SingleDomain, _symbol_converter)
|
30 |
+
from sympy.utilities.iterables import iterable
|
31 |
+
from sympy.utilities.misc import filldedent
|
32 |
+
from sympy.external import import_module
|
33 |
+
|
34 |
+
# __all__ = ['marginal_distribution']
|
35 |
+
|
36 |
+
class JointPSpace(ProductPSpace):
|
37 |
+
"""
|
38 |
+
Represents a joint probability space. Represented using symbols for
|
39 |
+
each component and a distribution.
|
40 |
+
"""
|
41 |
+
def __new__(cls, sym, dist):
|
42 |
+
if isinstance(dist, SingleContinuousDistribution):
|
43 |
+
return SingleContinuousPSpace(sym, dist)
|
44 |
+
if isinstance(dist, SingleDiscreteDistribution):
|
45 |
+
return SingleDiscretePSpace(sym, dist)
|
46 |
+
sym = _symbol_converter(sym)
|
47 |
+
return Basic.__new__(cls, sym, dist)
|
48 |
+
|
49 |
+
@property
|
50 |
+
def set(self):
|
51 |
+
return self.domain.set
|
52 |
+
|
53 |
+
@property
|
54 |
+
def symbol(self):
|
55 |
+
return self.args[0]
|
56 |
+
|
57 |
+
@property
|
58 |
+
def distribution(self):
|
59 |
+
return self.args[1]
|
60 |
+
|
61 |
+
@property
|
62 |
+
def value(self):
|
63 |
+
return JointRandomSymbol(self.symbol, self)
|
64 |
+
|
65 |
+
@property
|
66 |
+
def component_count(self):
|
67 |
+
_set = self.distribution.set
|
68 |
+
if isinstance(_set, ProductSet):
|
69 |
+
return S(len(_set.args))
|
70 |
+
elif isinstance(_set, Product):
|
71 |
+
return _set.limits[0][-1]
|
72 |
+
return S.One
|
73 |
+
|
74 |
+
@property
|
75 |
+
def pdf(self):
|
76 |
+
sym = [Indexed(self.symbol, i) for i in range(self.component_count)]
|
77 |
+
return self.distribution(*sym)
|
78 |
+
|
79 |
+
@property
|
80 |
+
def domain(self):
|
81 |
+
rvs = random_symbols(self.distribution)
|
82 |
+
if not rvs:
|
83 |
+
return SingleDomain(self.symbol, self.distribution.set)
|
84 |
+
return ProductDomain(*[rv.pspace.domain for rv in rvs])
|
85 |
+
|
86 |
+
def component_domain(self, index):
|
87 |
+
return self.set.args[index]
|
88 |
+
|
89 |
+
def marginal_distribution(self, *indices):
|
90 |
+
count = self.component_count
|
91 |
+
if count.atoms(Symbol):
|
92 |
+
raise ValueError("Marginal distributions cannot be computed "
|
93 |
+
"for symbolic dimensions. It is a work under progress.")
|
94 |
+
orig = [Indexed(self.symbol, i) for i in range(count)]
|
95 |
+
all_syms = [Symbol(str(i)) for i in orig]
|
96 |
+
replace_dict = dict(zip(all_syms, orig))
|
97 |
+
sym = tuple(Symbol(str(Indexed(self.symbol, i))) for i in indices)
|
98 |
+
limits = [[i,] for i in all_syms if i not in sym]
|
99 |
+
index = 0
|
100 |
+
for i in range(count):
|
101 |
+
if i not in indices:
|
102 |
+
limits[index].append(self.distribution.set.args[i])
|
103 |
+
limits[index] = tuple(limits[index])
|
104 |
+
index += 1
|
105 |
+
if self.distribution.is_Continuous:
|
106 |
+
f = Lambda(sym, integrate(self.distribution(*all_syms), *limits))
|
107 |
+
elif self.distribution.is_Discrete:
|
108 |
+
f = Lambda(sym, summation(self.distribution(*all_syms), *limits))
|
109 |
+
return f.xreplace(replace_dict)
|
110 |
+
|
111 |
+
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
|
112 |
+
syms = tuple(self.value[i] for i in range(self.component_count))
|
113 |
+
rvs = rvs or syms
|
114 |
+
if not any(i in rvs for i in syms):
|
115 |
+
return expr
|
116 |
+
expr = expr*self.pdf
|
117 |
+
for rv in rvs:
|
118 |
+
if isinstance(rv, Indexed):
|
119 |
+
expr = expr.xreplace({rv: Indexed(str(rv.base), rv.args[1])})
|
120 |
+
elif isinstance(rv, RandomSymbol):
|
121 |
+
expr = expr.xreplace({rv: rv.symbol})
|
122 |
+
if self.value in random_symbols(expr):
|
123 |
+
raise NotImplementedError(filldedent('''
|
124 |
+
Expectations of expression with unindexed joint random symbols
|
125 |
+
cannot be calculated yet.'''))
|
126 |
+
limits = tuple((Indexed(str(rv.base),rv.args[1]),
|
127 |
+
self.distribution.set.args[rv.args[1]]) for rv in syms)
|
128 |
+
return Integral(expr, *limits)
|
129 |
+
|
130 |
+
def where(self, condition):
|
131 |
+
raise NotImplementedError()
|
132 |
+
|
133 |
+
def compute_density(self, expr):
|
134 |
+
raise NotImplementedError()
|
135 |
+
|
136 |
+
def sample(self, size=(), library='scipy', seed=None):
|
137 |
+
"""
|
138 |
+
Internal sample method
|
139 |
+
|
140 |
+
Returns dictionary mapping RandomSymbol to realization value.
|
141 |
+
"""
|
142 |
+
return {RandomSymbol(self.symbol, self): self.distribution.sample(size,
|
143 |
+
library=library, seed=seed)}
|
144 |
+
|
145 |
+
def probability(self, condition):
|
146 |
+
raise NotImplementedError()
|
147 |
+
|
148 |
+
|
149 |
+
class SampleJointScipy:
|
150 |
+
"""Returns the sample from scipy of the given distribution"""
|
151 |
+
def __new__(cls, dist, size, seed=None):
|
152 |
+
return cls._sample_scipy(dist, size, seed)
|
153 |
+
|
154 |
+
@classmethod
|
155 |
+
def _sample_scipy(cls, dist, size, seed):
|
156 |
+
"""Sample from SciPy."""
|
157 |
+
|
158 |
+
import numpy
|
159 |
+
if seed is None or isinstance(seed, int):
|
160 |
+
rand_state = numpy.random.default_rng(seed=seed)
|
161 |
+
else:
|
162 |
+
rand_state = seed
|
163 |
+
from scipy import stats as scipy_stats
|
164 |
+
scipy_rv_map = {
|
165 |
+
'MultivariateNormalDistribution': lambda dist, size: scipy_stats.multivariate_normal.rvs(
|
166 |
+
mean=matrix2numpy(dist.mu).flatten(),
|
167 |
+
cov=matrix2numpy(dist.sigma), size=size, random_state=rand_state),
|
168 |
+
'MultivariateBetaDistribution': lambda dist, size: scipy_stats.dirichlet.rvs(
|
169 |
+
alpha=list2numpy(dist.alpha, float).flatten(), size=size, random_state=rand_state),
|
170 |
+
'MultinomialDistribution': lambda dist, size: scipy_stats.multinomial.rvs(
|
171 |
+
n=int(dist.n), p=list2numpy(dist.p, float).flatten(), size=size, random_state=rand_state)
|
172 |
+
}
|
173 |
+
|
174 |
+
sample_shape = {
|
175 |
+
'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape,
|
176 |
+
'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape,
|
177 |
+
'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape
|
178 |
+
}
|
179 |
+
|
180 |
+
dist_list = scipy_rv_map.keys()
|
181 |
+
|
182 |
+
if dist.__class__.__name__ not in dist_list:
|
183 |
+
return None
|
184 |
+
|
185 |
+
samples = scipy_rv_map[dist.__class__.__name__](dist, size)
|
186 |
+
return samples.reshape(size + sample_shape[dist.__class__.__name__](dist))
|
187 |
+
|
188 |
+
class SampleJointNumpy:
|
189 |
+
"""Returns the sample from numpy of the given distribution"""
|
190 |
+
|
191 |
+
def __new__(cls, dist, size, seed=None):
|
192 |
+
return cls._sample_numpy(dist, size, seed)
|
193 |
+
|
194 |
+
@classmethod
|
195 |
+
def _sample_numpy(cls, dist, size, seed):
|
196 |
+
"""Sample from NumPy."""
|
197 |
+
|
198 |
+
import numpy
|
199 |
+
if seed is None or isinstance(seed, int):
|
200 |
+
rand_state = numpy.random.default_rng(seed=seed)
|
201 |
+
else:
|
202 |
+
rand_state = seed
|
203 |
+
numpy_rv_map = {
|
204 |
+
'MultivariateNormalDistribution': lambda dist, size: rand_state.multivariate_normal(
|
205 |
+
mean=matrix2numpy(dist.mu, float).flatten(),
|
206 |
+
cov=matrix2numpy(dist.sigma, float), size=size),
|
207 |
+
'MultivariateBetaDistribution': lambda dist, size: rand_state.dirichlet(
|
208 |
+
alpha=list2numpy(dist.alpha, float).flatten(), size=size),
|
209 |
+
'MultinomialDistribution': lambda dist, size: rand_state.multinomial(
|
210 |
+
n=int(dist.n), pvals=list2numpy(dist.p, float).flatten(), size=size)
|
211 |
+
}
|
212 |
+
|
213 |
+
sample_shape = {
|
214 |
+
'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape,
|
215 |
+
'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape,
|
216 |
+
'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape
|
217 |
+
}
|
218 |
+
|
219 |
+
dist_list = numpy_rv_map.keys()
|
220 |
+
|
221 |
+
if dist.__class__.__name__ not in dist_list:
|
222 |
+
return None
|
223 |
+
|
224 |
+
samples = numpy_rv_map[dist.__class__.__name__](dist, prod(size))
|
225 |
+
return samples.reshape(size + sample_shape[dist.__class__.__name__](dist))
|
226 |
+
|
227 |
+
class SampleJointPymc:
|
228 |
+
"""Returns the sample from pymc of the given distribution"""
|
229 |
+
|
230 |
+
def __new__(cls, dist, size, seed=None):
|
231 |
+
return cls._sample_pymc(dist, size, seed)
|
232 |
+
|
233 |
+
@classmethod
|
234 |
+
def _sample_pymc(cls, dist, size, seed):
|
235 |
+
"""Sample from PyMC."""
|
236 |
+
|
237 |
+
try:
|
238 |
+
import pymc
|
239 |
+
except ImportError:
|
240 |
+
import pymc3 as pymc
|
241 |
+
pymc_rv_map = {
|
242 |
+
'MultivariateNormalDistribution': lambda dist:
|
243 |
+
pymc.MvNormal('X', mu=matrix2numpy(dist.mu, float).flatten(),
|
244 |
+
cov=matrix2numpy(dist.sigma, float), shape=(1, dist.mu.shape[0])),
|
245 |
+
'MultivariateBetaDistribution': lambda dist:
|
246 |
+
pymc.Dirichlet('X', a=list2numpy(dist.alpha, float).flatten()),
|
247 |
+
'MultinomialDistribution': lambda dist:
|
248 |
+
pymc.Multinomial('X', n=int(dist.n),
|
249 |
+
p=list2numpy(dist.p, float).flatten(), shape=(1, len(dist.p)))
|
250 |
+
}
|
251 |
+
|
252 |
+
sample_shape = {
|
253 |
+
'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape,
|
254 |
+
'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape,
|
255 |
+
'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape
|
256 |
+
}
|
257 |
+
|
258 |
+
dist_list = pymc_rv_map.keys()
|
259 |
+
|
260 |
+
if dist.__class__.__name__ not in dist_list:
|
261 |
+
return None
|
262 |
+
|
263 |
+
import logging
|
264 |
+
logging.getLogger("pymc3").setLevel(logging.ERROR)
|
265 |
+
with pymc.Model():
|
266 |
+
pymc_rv_map[dist.__class__.__name__](dist)
|
267 |
+
samples = pymc.sample(draws=prod(size), chains=1, progressbar=False, random_seed=seed, return_inferencedata=False, compute_convergence_checks=False)[:]['X']
|
268 |
+
return samples.reshape(size + sample_shape[dist.__class__.__name__](dist))
|
269 |
+
|
270 |
+
|
271 |
+
_get_sample_class_jrv = {
|
272 |
+
'scipy': SampleJointScipy,
|
273 |
+
'pymc3': SampleJointPymc,
|
274 |
+
'pymc': SampleJointPymc,
|
275 |
+
'numpy': SampleJointNumpy
|
276 |
+
}
|
277 |
+
|
278 |
+
class JointDistribution(Distribution, NamedArgsMixin):
|
279 |
+
"""
|
280 |
+
Represented by the random variables part of the joint distribution.
|
281 |
+
Contains methods for PDF, CDF, sampling, marginal densities, etc.
|
282 |
+
"""
|
283 |
+
|
284 |
+
_argnames = ('pdf', )
|
285 |
+
|
286 |
+
def __new__(cls, *args):
|
287 |
+
args = list(map(sympify, args))
|
288 |
+
for i in range(len(args)):
|
289 |
+
if isinstance(args[i], list):
|
290 |
+
args[i] = ImmutableMatrix(args[i])
|
291 |
+
return Basic.__new__(cls, *args)
|
292 |
+
|
293 |
+
@property
|
294 |
+
def domain(self):
|
295 |
+
return ProductDomain(self.symbols)
|
296 |
+
|
297 |
+
@property
|
298 |
+
def pdf(self):
|
299 |
+
return self.density.args[1]
|
300 |
+
|
301 |
+
def cdf(self, other):
|
302 |
+
if not isinstance(other, dict):
|
303 |
+
raise ValueError("%s should be of type dict, got %s"%(other, type(other)))
|
304 |
+
rvs = other.keys()
|
305 |
+
_set = self.domain.set.sets
|
306 |
+
expr = self.pdf(tuple(i.args[0] for i in self.symbols))
|
307 |
+
for i in range(len(other)):
|
308 |
+
if rvs[i].is_Continuous:
|
309 |
+
density = Integral(expr, (rvs[i], _set[i].inf,
|
310 |
+
other[rvs[i]]))
|
311 |
+
elif rvs[i].is_Discrete:
|
312 |
+
density = Sum(expr, (rvs[i], _set[i].inf,
|
313 |
+
other[rvs[i]]))
|
314 |
+
return density
|
315 |
+
|
316 |
+
def sample(self, size=(), library='scipy', seed=None):
|
317 |
+
""" A random realization from the distribution """
|
318 |
+
|
319 |
+
libraries = ('scipy', 'numpy', 'pymc3', 'pymc')
|
320 |
+
if library not in libraries:
|
321 |
+
raise NotImplementedError("Sampling from %s is not supported yet."
|
322 |
+
% str(library))
|
323 |
+
if not import_module(library):
|
324 |
+
raise ValueError("Failed to import %s" % library)
|
325 |
+
|
326 |
+
samps = _get_sample_class_jrv[library](self, size, seed=seed)
|
327 |
+
|
328 |
+
if samps is not None:
|
329 |
+
return samps
|
330 |
+
raise NotImplementedError(
|
331 |
+
"Sampling for %s is not currently implemented from %s"
|
332 |
+
% (self.__class__.__name__, library)
|
333 |
+
)
|
334 |
+
|
335 |
+
def __call__(self, *args):
|
336 |
+
return self.pdf(*args)
|
337 |
+
|
338 |
+
class JointRandomSymbol(RandomSymbol):
|
339 |
+
"""
|
340 |
+
Representation of random symbols with joint probability distributions
|
341 |
+
to allow indexing."
|
342 |
+
"""
|
343 |
+
def __getitem__(self, key):
|
344 |
+
if isinstance(self.pspace, JointPSpace):
|
345 |
+
if (self.pspace.component_count <= key) == True:
|
346 |
+
raise ValueError("Index keys for %s can only up to %s." %
|
347 |
+
(self.name, self.pspace.component_count - 1))
|
348 |
+
return Indexed(self, key)
|
349 |
+
|
350 |
+
|
351 |
+
|
352 |
+
class MarginalDistribution(Distribution):
|
353 |
+
"""
|
354 |
+
Represents the marginal distribution of a joint probability space.
|
355 |
+
|
356 |
+
Initialised using a probability distribution and random variables(or
|
357 |
+
their indexed components) which should be a part of the resultant
|
358 |
+
distribution.
|
359 |
+
"""
|
360 |
+
|
361 |
+
def __new__(cls, dist, *rvs):
|
362 |
+
if len(rvs) == 1 and iterable(rvs[0]):
|
363 |
+
rvs = tuple(rvs[0])
|
364 |
+
if not all(isinstance(rv, (Indexed, RandomSymbol)) for rv in rvs):
|
365 |
+
raise ValueError(filldedent('''Marginal distribution can be
|
366 |
+
intitialised only in terms of random variables or indexed random
|
367 |
+
variables'''))
|
368 |
+
rvs = Tuple.fromiter(rv for rv in rvs)
|
369 |
+
if not isinstance(dist, JointDistribution) and len(random_symbols(dist)) == 0:
|
370 |
+
return dist
|
371 |
+
return Basic.__new__(cls, dist, rvs)
|
372 |
+
|
373 |
+
def check(self):
|
374 |
+
pass
|
375 |
+
|
376 |
+
@property
|
377 |
+
def set(self):
|
378 |
+
rvs = [i for i in self.args[1] if isinstance(i, RandomSymbol)]
|
379 |
+
return ProductSet(*[rv.pspace.set for rv in rvs])
|
380 |
+
|
381 |
+
@property
|
382 |
+
def symbols(self):
|
383 |
+
rvs = self.args[1]
|
384 |
+
return {rv.pspace.symbol for rv in rvs}
|
385 |
+
|
386 |
+
def pdf(self, *x):
|
387 |
+
expr, rvs = self.args[0], self.args[1]
|
388 |
+
marginalise_out = [i for i in random_symbols(expr) if i not in rvs]
|
389 |
+
if isinstance(expr, JointDistribution):
|
390 |
+
count = len(expr.domain.args)
|
391 |
+
x = Dummy('x', real=True)
|
392 |
+
syms = tuple(Indexed(x, i) for i in count)
|
393 |
+
expr = expr.pdf(syms)
|
394 |
+
else:
|
395 |
+
syms = tuple(rv.pspace.symbol if isinstance(rv, RandomSymbol) else rv.args[0] for rv in rvs)
|
396 |
+
return Lambda(syms, self.compute_pdf(expr, marginalise_out))(*x)
|
397 |
+
|
398 |
+
def compute_pdf(self, expr, rvs):
|
399 |
+
for rv in rvs:
|
400 |
+
lpdf = 1
|
401 |
+
if isinstance(rv, RandomSymbol):
|
402 |
+
lpdf = rv.pspace.pdf
|
403 |
+
expr = self.marginalise_out(expr*lpdf, rv)
|
404 |
+
return expr
|
405 |
+
|
406 |
+
def marginalise_out(self, expr, rv):
|
407 |
+
from sympy.concrete.summations import Sum
|
408 |
+
if isinstance(rv, RandomSymbol):
|
409 |
+
dom = rv.pspace.set
|
410 |
+
elif isinstance(rv, Indexed):
|
411 |
+
dom = rv.base.component_domain(
|
412 |
+
rv.pspace.component_domain(rv.args[1]))
|
413 |
+
expr = expr.xreplace({rv: rv.pspace.symbol})
|
414 |
+
if rv.pspace.is_Continuous:
|
415 |
+
#TODO: Modify to support integration
|
416 |
+
#for all kinds of sets.
|
417 |
+
expr = Integral(expr, (rv.pspace.symbol, dom))
|
418 |
+
elif rv.pspace.is_Discrete:
|
419 |
+
#incorporate this into `Sum`/`summation`
|
420 |
+
if dom in (S.Integers, S.Naturals, S.Naturals0):
|
421 |
+
dom = (dom.inf, dom.sup)
|
422 |
+
expr = Sum(expr, (rv.pspace.symbol, dom))
|
423 |
+
return expr
|
424 |
+
|
425 |
+
def __call__(self, *args):
|
426 |
+
return self.pdf(*args)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/joint_rv_types.py
ADDED
@@ -0,0 +1,946 @@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.products import Product
|
2 |
+
from sympy.concrete.summations import Sum
|
3 |
+
from sympy.core.add import Add
|
4 |
+
from sympy.core.function import Lambda
|
5 |
+
from sympy.core.mul import Mul
|
6 |
+
from sympy.core.numbers import (Integer, Rational, pi)
|
7 |
+
from sympy.core.power import Pow
|
8 |
+
from sympy.core.relational import Eq
|
9 |
+
from sympy.core.singleton import S
|
10 |
+
from sympy.core.symbol import (Symbol, symbols)
|
11 |
+
from sympy.core.sympify import sympify
|
12 |
+
from sympy.functions.combinatorial.factorials import (rf, factorial)
|
13 |
+
from sympy.functions.elementary.exponential import exp
|
14 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
15 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
16 |
+
from sympy.functions.special.bessel import besselk
|
17 |
+
from sympy.functions.special.gamma_functions import gamma
|
18 |
+
from sympy.matrices.dense import (Matrix, ones)
|
19 |
+
from sympy.sets.fancysets import Range
|
20 |
+
from sympy.sets.sets import (Intersection, Interval)
|
21 |
+
from sympy.tensor.indexed import (Indexed, IndexedBase)
|
22 |
+
from sympy.matrices import ImmutableMatrix, MatrixSymbol
|
23 |
+
from sympy.matrices.expressions.determinant import det
|
24 |
+
from sympy.matrices.expressions.matexpr import MatrixElement
|
25 |
+
from sympy.stats.joint_rv import JointDistribution, JointPSpace, MarginalDistribution
|
26 |
+
from sympy.stats.rv import _value_check, random_symbols
|
27 |
+
|
28 |
+
__all__ = ['JointRV',
|
29 |
+
'MultivariateNormal',
|
30 |
+
'MultivariateLaplace',
|
31 |
+
'Dirichlet',
|
32 |
+
'GeneralizedMultivariateLogGamma',
|
33 |
+
'GeneralizedMultivariateLogGammaOmega',
|
34 |
+
'Multinomial',
|
35 |
+
'MultivariateBeta',
|
36 |
+
'MultivariateEwens',
|
37 |
+
'MultivariateT',
|
38 |
+
'NegativeMultinomial',
|
39 |
+
'NormalGamma'
|
40 |
+
]
|
41 |
+
|
42 |
+
def multivariate_rv(cls, sym, *args):
|
43 |
+
args = list(map(sympify, args))
|
44 |
+
dist = cls(*args)
|
45 |
+
args = dist.args
|
46 |
+
dist.check(*args)
|
47 |
+
return JointPSpace(sym, dist).value
|
48 |
+
|
49 |
+
|
50 |
+
def marginal_distribution(rv, *indices):
|
51 |
+
"""
|
52 |
+
Marginal distribution function of a joint random variable.
|
53 |
+
|
54 |
+
Parameters
|
55 |
+
==========
|
56 |
+
|
57 |
+
rv : A random variable with a joint probability distribution.
|
58 |
+
indices : Component indices or the indexed random symbol
|
59 |
+
for which the joint distribution is to be calculated
|
60 |
+
|
61 |
+
Returns
|
62 |
+
=======
|
63 |
+
|
64 |
+
A Lambda expression in `sym`.
|
65 |
+
|
66 |
+
Examples
|
67 |
+
========
|
68 |
+
|
69 |
+
>>> from sympy.stats import MultivariateNormal, marginal_distribution
|
70 |
+
>>> m = MultivariateNormal('X', [1, 2], [[2, 1], [1, 2]])
|
71 |
+
>>> marginal_distribution(m, m[0])(1)
|
72 |
+
1/(2*sqrt(pi))
|
73 |
+
|
74 |
+
"""
|
75 |
+
indices = list(indices)
|
76 |
+
for i in range(len(indices)):
|
77 |
+
if isinstance(indices[i], Indexed):
|
78 |
+
indices[i] = indices[i].args[1]
|
79 |
+
prob_space = rv.pspace
|
80 |
+
if not indices:
|
81 |
+
raise ValueError(
|
82 |
+
"At least one component for marginal density is needed.")
|
83 |
+
if hasattr(prob_space.distribution, '_marginal_distribution'):
|
84 |
+
return prob_space.distribution._marginal_distribution(indices, rv.symbol)
|
85 |
+
return prob_space.marginal_distribution(*indices)
|
86 |
+
|
87 |
+
|
88 |
+
class JointDistributionHandmade(JointDistribution):
|
89 |
+
|
90 |
+
_argnames = ('pdf',)
|
91 |
+
is_Continuous = True
|
92 |
+
|
93 |
+
@property
|
94 |
+
def set(self):
|
95 |
+
return self.args[1]
|
96 |
+
|
97 |
+
|
98 |
+
def JointRV(symbol, pdf, _set=None):
|
99 |
+
"""
|
100 |
+
Create a Joint Random Variable where each of its component is continuous,
|
101 |
+
given the following:
|
102 |
+
|
103 |
+
Parameters
|
104 |
+
==========
|
105 |
+
|
106 |
+
symbol : Symbol
|
107 |
+
Represents name of the random variable.
|
108 |
+
pdf : A PDF in terms of indexed symbols of the symbol given
|
109 |
+
as the first argument
|
110 |
+
|
111 |
+
NOTE
|
112 |
+
====
|
113 |
+
|
114 |
+
As of now, the set for each component for a ``JointRV`` is
|
115 |
+
equal to the set of all integers, which cannot be changed.
|
116 |
+
|
117 |
+
Examples
|
118 |
+
========
|
119 |
+
|
120 |
+
>>> from sympy import exp, pi, Indexed, S
|
121 |
+
>>> from sympy.stats import density, JointRV
|
122 |
+
>>> x1, x2 = (Indexed('x', i) for i in (1, 2))
|
123 |
+
>>> pdf = exp(-x1**2/2 + x1 - x2**2/2 - S(1)/2)/(2*pi)
|
124 |
+
>>> N1 = JointRV('x', pdf) #Multivariate Normal distribution
|
125 |
+
>>> density(N1)(1, 2)
|
126 |
+
exp(-2)/(2*pi)
|
127 |
+
|
128 |
+
Returns
|
129 |
+
=======
|
130 |
+
|
131 |
+
RandomSymbol
|
132 |
+
|
133 |
+
"""
|
134 |
+
#TODO: Add support for sets provided by the user
|
135 |
+
symbol = sympify(symbol)
|
136 |
+
syms = [i for i in pdf.free_symbols if isinstance(i, Indexed)
|
137 |
+
and i.base == IndexedBase(symbol)]
|
138 |
+
syms = tuple(sorted(syms, key = lambda index: index.args[1]))
|
139 |
+
_set = S.Reals**len(syms)
|
140 |
+
pdf = Lambda(syms, pdf)
|
141 |
+
dist = JointDistributionHandmade(pdf, _set)
|
142 |
+
jrv = JointPSpace(symbol, dist).value
|
143 |
+
rvs = random_symbols(pdf)
|
144 |
+
if len(rvs) != 0:
|
145 |
+
dist = MarginalDistribution(dist, (jrv,))
|
146 |
+
return JointPSpace(symbol, dist).value
|
147 |
+
return jrv
|
148 |
+
|
149 |
+
#-------------------------------------------------------------------------------
|
150 |
+
# Multivariate Normal distribution ---------------------------------------------
|
151 |
+
|
152 |
+
class MultivariateNormalDistribution(JointDistribution):
|
153 |
+
_argnames = ('mu', 'sigma')
|
154 |
+
|
155 |
+
is_Continuous=True
|
156 |
+
|
157 |
+
@property
|
158 |
+
def set(self):
|
159 |
+
k = self.mu.shape[0]
|
160 |
+
return S.Reals**k
|
161 |
+
|
162 |
+
@staticmethod
|
163 |
+
def check(mu, sigma):
|
164 |
+
_value_check(mu.shape[0] == sigma.shape[0],
|
165 |
+
"Size of the mean vector and covariance matrix are incorrect.")
|
166 |
+
#check if covariance matrix is positive semi definite or not.
|
167 |
+
if not isinstance(sigma, MatrixSymbol):
|
168 |
+
_value_check(sigma.is_positive_semidefinite,
|
169 |
+
"The covariance matrix must be positive semi definite. ")
|
170 |
+
|
171 |
+
def pdf(self, *args):
|
172 |
+
mu, sigma = self.mu, self.sigma
|
173 |
+
k = mu.shape[0]
|
174 |
+
if len(args) == 1 and args[0].is_Matrix:
|
175 |
+
args = args[0]
|
176 |
+
else:
|
177 |
+
args = ImmutableMatrix(args)
|
178 |
+
x = args - mu
|
179 |
+
density = S.One/sqrt((2*pi)**(k)*det(sigma))*exp(
|
180 |
+
Rational(-1, 2)*x.transpose()*(sigma.inv()*x))
|
181 |
+
return MatrixElement(density, 0, 0)
|
182 |
+
|
183 |
+
def _marginal_distribution(self, indices, sym):
|
184 |
+
sym = ImmutableMatrix([Indexed(sym, i) for i in indices])
|
185 |
+
_mu, _sigma = self.mu, self.sigma
|
186 |
+
k = self.mu.shape[0]
|
187 |
+
for i in range(k):
|
188 |
+
if i not in indices:
|
189 |
+
_mu = _mu.row_del(i)
|
190 |
+
_sigma = _sigma.col_del(i)
|
191 |
+
_sigma = _sigma.row_del(i)
|
192 |
+
return Lambda(tuple(sym), S.One/sqrt((2*pi)**(len(_mu))*det(_sigma))*exp(
|
193 |
+
Rational(-1, 2)*(_mu - sym).transpose()*(_sigma.inv()*\
|
194 |
+
(_mu - sym)))[0])
|
195 |
+
|
196 |
+
def MultivariateNormal(name, mu, sigma):
|
197 |
+
r"""
|
198 |
+
Creates a continuous random variable with Multivariate Normal
|
199 |
+
Distribution.
|
200 |
+
|
201 |
+
The density of the multivariate normal distribution can be found at [1].
|
202 |
+
|
203 |
+
Parameters
|
204 |
+
==========
|
205 |
+
|
206 |
+
mu : List representing the mean or the mean vector
|
207 |
+
sigma : Positive semidefinite square matrix
|
208 |
+
Represents covariance Matrix.
|
209 |
+
If `\sigma` is noninvertible then only sampling is supported currently
|
210 |
+
|
211 |
+
Returns
|
212 |
+
=======
|
213 |
+
|
214 |
+
RandomSymbol
|
215 |
+
|
216 |
+
Examples
|
217 |
+
========
|
218 |
+
|
219 |
+
>>> from sympy.stats import MultivariateNormal, density, marginal_distribution
|
220 |
+
>>> from sympy import symbols, MatrixSymbol
|
221 |
+
>>> X = MultivariateNormal('X', [3, 4], [[2, 1], [1, 2]])
|
222 |
+
>>> y, z = symbols('y z')
|
223 |
+
>>> density(X)(y, z)
|
224 |
+
sqrt(3)*exp(-y**2/3 + y*z/3 + 2*y/3 - z**2/3 + 5*z/3 - 13/3)/(6*pi)
|
225 |
+
>>> density(X)(1, 2)
|
226 |
+
sqrt(3)*exp(-4/3)/(6*pi)
|
227 |
+
>>> marginal_distribution(X, X[1])(y)
|
228 |
+
exp(-(y - 4)**2/4)/(2*sqrt(pi))
|
229 |
+
>>> marginal_distribution(X, X[0])(y)
|
230 |
+
exp(-(y - 3)**2/4)/(2*sqrt(pi))
|
231 |
+
|
232 |
+
The example below shows that it is also possible to use
|
233 |
+
symbolic parameters to define the MultivariateNormal class.
|
234 |
+
|
235 |
+
>>> n = symbols('n', integer=True, positive=True)
|
236 |
+
>>> Sg = MatrixSymbol('Sg', n, n)
|
237 |
+
>>> mu = MatrixSymbol('mu', n, 1)
|
238 |
+
>>> obs = MatrixSymbol('obs', n, 1)
|
239 |
+
>>> X = MultivariateNormal('X', mu, Sg)
|
240 |
+
|
241 |
+
The density of a multivariate normal can be
|
242 |
+
calculated using a matrix argument, as shown below.
|
243 |
+
|
244 |
+
>>> density(X)(obs)
|
245 |
+
(exp(((1/2)*mu.T - (1/2)*obs.T)*Sg**(-1)*(-mu + obs))/sqrt((2*pi)**n*Determinant(Sg)))[0, 0]
|
246 |
+
|
247 |
+
References
|
248 |
+
==========
|
249 |
+
|
250 |
+
.. [1] https://en.wikipedia.org/wiki/Multivariate_normal_distribution
|
251 |
+
|
252 |
+
"""
|
253 |
+
return multivariate_rv(MultivariateNormalDistribution, name, mu, sigma)
|
254 |
+
|
255 |
+
#-------------------------------------------------------------------------------
|
256 |
+
# Multivariate Laplace distribution --------------------------------------------
|
257 |
+
|
258 |
+
class MultivariateLaplaceDistribution(JointDistribution):
|
259 |
+
_argnames = ('mu', 'sigma')
|
260 |
+
is_Continuous=True
|
261 |
+
|
262 |
+
@property
|
263 |
+
def set(self):
|
264 |
+
k = self.mu.shape[0]
|
265 |
+
return S.Reals**k
|
266 |
+
|
267 |
+
@staticmethod
|
268 |
+
def check(mu, sigma):
|
269 |
+
_value_check(mu.shape[0] == sigma.shape[0],
|
270 |
+
"Size of the mean vector and covariance matrix are incorrect.")
|
271 |
+
# check if covariance matrix is positive definite or not.
|
272 |
+
if not isinstance(sigma, MatrixSymbol):
|
273 |
+
_value_check(sigma.is_positive_definite,
|
274 |
+
"The covariance matrix must be positive definite. ")
|
275 |
+
|
276 |
+
def pdf(self, *args):
|
277 |
+
mu, sigma = self.mu, self.sigma
|
278 |
+
mu_T = mu.transpose()
|
279 |
+
k = S(mu.shape[0])
|
280 |
+
sigma_inv = sigma.inv()
|
281 |
+
args = ImmutableMatrix(args)
|
282 |
+
args_T = args.transpose()
|
283 |
+
x = (mu_T*sigma_inv*mu)[0]
|
284 |
+
y = (args_T*sigma_inv*args)[0]
|
285 |
+
v = 1 - k/2
|
286 |
+
return (2 * (y/(2 + x))**(v/2) * besselk(v, sqrt((2 + x)*y)) *
|
287 |
+
exp((args_T * sigma_inv * mu)[0]) /
|
288 |
+
((2 * pi)**(k/2) * sqrt(det(sigma))))
|
289 |
+
|
290 |
+
|
291 |
+
def MultivariateLaplace(name, mu, sigma):
|
292 |
+
"""
|
293 |
+
Creates a continuous random variable with Multivariate Laplace
|
294 |
+
Distribution.
|
295 |
+
|
296 |
+
The density of the multivariate Laplace distribution can be found at [1].
|
297 |
+
|
298 |
+
Parameters
|
299 |
+
==========
|
300 |
+
|
301 |
+
mu : List representing the mean or the mean vector
|
302 |
+
sigma : Positive definite square matrix
|
303 |
+
Represents covariance Matrix
|
304 |
+
|
305 |
+
Returns
|
306 |
+
=======
|
307 |
+
|
308 |
+
RandomSymbol
|
309 |
+
|
310 |
+
Examples
|
311 |
+
========
|
312 |
+
|
313 |
+
>>> from sympy.stats import MultivariateLaplace, density
|
314 |
+
>>> from sympy import symbols
|
315 |
+
>>> y, z = symbols('y z')
|
316 |
+
>>> X = MultivariateLaplace('X', [2, 4], [[3, 1], [1, 3]])
|
317 |
+
>>> density(X)(y, z)
|
318 |
+
sqrt(2)*exp(y/4 + 5*z/4)*besselk(0, sqrt(15*y*(3*y/8 - z/8)/2 + 15*z*(-y/8 + 3*z/8)/2))/(4*pi)
|
319 |
+
>>> density(X)(1, 2)
|
320 |
+
sqrt(2)*exp(11/4)*besselk(0, sqrt(165)/4)/(4*pi)
|
321 |
+
|
322 |
+
References
|
323 |
+
==========
|
324 |
+
|
325 |
+
.. [1] https://en.wikipedia.org/wiki/Multivariate_Laplace_distribution
|
326 |
+
|
327 |
+
"""
|
328 |
+
return multivariate_rv(MultivariateLaplaceDistribution, name, mu, sigma)
|
329 |
+
|
330 |
+
#-------------------------------------------------------------------------------
|
331 |
+
# Multivariate StudentT distribution -------------------------------------------
|
332 |
+
|
333 |
+
class MultivariateTDistribution(JointDistribution):
|
334 |
+
_argnames = ('mu', 'shape_mat', 'dof')
|
335 |
+
is_Continuous=True
|
336 |
+
|
337 |
+
@property
|
338 |
+
def set(self):
|
339 |
+
k = self.mu.shape[0]
|
340 |
+
return S.Reals**k
|
341 |
+
|
342 |
+
@staticmethod
|
343 |
+
def check(mu, sigma, v):
|
344 |
+
_value_check(mu.shape[0] == sigma.shape[0],
|
345 |
+
"Size of the location vector and shape matrix are incorrect.")
|
346 |
+
# check if covariance matrix is positive definite or not.
|
347 |
+
if not isinstance(sigma, MatrixSymbol):
|
348 |
+
_value_check(sigma.is_positive_definite,
|
349 |
+
"The shape matrix must be positive definite. ")
|
350 |
+
|
351 |
+
def pdf(self, *args):
|
352 |
+
mu, sigma = self.mu, self.shape_mat
|
353 |
+
v = S(self.dof)
|
354 |
+
k = S(mu.shape[0])
|
355 |
+
sigma_inv = sigma.inv()
|
356 |
+
args = ImmutableMatrix(args)
|
357 |
+
x = args - mu
|
358 |
+
return gamma((k + v)/2)/(gamma(v/2)*(v*pi)**(k/2)*sqrt(det(sigma)))\
|
359 |
+
*(1 + 1/v*(x.transpose()*sigma_inv*x)[0])**((-v - k)/2)
|
360 |
+
|
361 |
+
def MultivariateT(syms, mu, sigma, v):
|
362 |
+
"""
|
363 |
+
Creates a joint random variable with multivariate T-distribution.
|
364 |
+
|
365 |
+
Parameters
|
366 |
+
==========
|
367 |
+
|
368 |
+
syms : A symbol/str
|
369 |
+
For identifying the random variable.
|
370 |
+
mu : A list/matrix
|
371 |
+
Representing the location vector
|
372 |
+
sigma : The shape matrix for the distribution
|
373 |
+
|
374 |
+
Examples
|
375 |
+
========
|
376 |
+
|
377 |
+
>>> from sympy.stats import density, MultivariateT
|
378 |
+
>>> from sympy import Symbol
|
379 |
+
|
380 |
+
>>> x = Symbol("x")
|
381 |
+
>>> X = MultivariateT("x", [1, 1], [[1, 0], [0, 1]], 2)
|
382 |
+
|
383 |
+
>>> density(X)(1, 2)
|
384 |
+
2/(9*pi)
|
385 |
+
|
386 |
+
Returns
|
387 |
+
=======
|
388 |
+
|
389 |
+
RandomSymbol
|
390 |
+
|
391 |
+
"""
|
392 |
+
return multivariate_rv(MultivariateTDistribution, syms, mu, sigma, v)
|
393 |
+
|
394 |
+
|
395 |
+
#-------------------------------------------------------------------------------
|
396 |
+
# Multivariate Normal Gamma distribution ---------------------------------------
|
397 |
+
|
398 |
+
class NormalGammaDistribution(JointDistribution):
|
399 |
+
|
400 |
+
_argnames = ('mu', 'lamda', 'alpha', 'beta')
|
401 |
+
is_Continuous=True
|
402 |
+
|
403 |
+
@staticmethod
|
404 |
+
def check(mu, lamda, alpha, beta):
|
405 |
+
_value_check(mu.is_real, "Location must be real.")
|
406 |
+
_value_check(lamda > 0, "Lambda must be positive")
|
407 |
+
_value_check(alpha > 0, "alpha must be positive")
|
408 |
+
_value_check(beta > 0, "beta must be positive")
|
409 |
+
|
410 |
+
@property
|
411 |
+
def set(self):
|
412 |
+
return S.Reals*Interval(0, S.Infinity)
|
413 |
+
|
414 |
+
def pdf(self, x, tau):
|
415 |
+
beta, alpha, lamda = self.beta, self.alpha, self.lamda
|
416 |
+
mu = self.mu
|
417 |
+
|
418 |
+
return beta**alpha*sqrt(lamda)/(gamma(alpha)*sqrt(2*pi))*\
|
419 |
+
tau**(alpha - S.Half)*exp(-1*beta*tau)*\
|
420 |
+
exp(-1*(lamda*tau*(x - mu)**2)/S(2))
|
421 |
+
|
422 |
+
def _marginal_distribution(self, indices, *sym):
|
423 |
+
if len(indices) == 2:
|
424 |
+
return self.pdf(*sym)
|
425 |
+
if indices[0] == 0:
|
426 |
+
#For marginal over `x`, return non-standardized Student-T's
|
427 |
+
#distribution
|
428 |
+
x = sym[0]
|
429 |
+
v, mu, sigma = self.alpha - S.Half, self.mu, \
|
430 |
+
S(self.beta)/(self.lamda * self.alpha)
|
431 |
+
return Lambda(sym, gamma((v + 1)/2)/(gamma(v/2)*sqrt(pi*v)*sigma)*\
|
432 |
+
(1 + 1/v*((x - mu)/sigma)**2)**((-v -1)/2))
|
433 |
+
#For marginal over `tau`, return Gamma distribution as per construction
|
434 |
+
from sympy.stats.crv_types import GammaDistribution
|
435 |
+
return Lambda(sym, GammaDistribution(self.alpha, self.beta)(sym[0]))
|
436 |
+
|
437 |
+
def NormalGamma(sym, mu, lamda, alpha, beta):
|
438 |
+
"""
|
439 |
+
Creates a bivariate joint random variable with multivariate Normal gamma
|
440 |
+
distribution.
|
441 |
+
|
442 |
+
Parameters
|
443 |
+
==========
|
444 |
+
|
445 |
+
sym : A symbol/str
|
446 |
+
For identifying the random variable.
|
447 |
+
mu : A real number
|
448 |
+
The mean of the normal distribution
|
449 |
+
lamda : A positive integer
|
450 |
+
Parameter of joint distribution
|
451 |
+
alpha : A positive integer
|
452 |
+
Parameter of joint distribution
|
453 |
+
beta : A positive integer
|
454 |
+
Parameter of joint distribution
|
455 |
+
|
456 |
+
Returns
|
457 |
+
=======
|
458 |
+
|
459 |
+
RandomSymbol
|
460 |
+
|
461 |
+
Examples
|
462 |
+
========
|
463 |
+
|
464 |
+
>>> from sympy.stats import density, NormalGamma
|
465 |
+
>>> from sympy import symbols
|
466 |
+
|
467 |
+
>>> X = NormalGamma('x', 0, 1, 2, 3)
|
468 |
+
>>> y, z = symbols('y z')
|
469 |
+
|
470 |
+
>>> density(X)(y, z)
|
471 |
+
9*sqrt(2)*z**(3/2)*exp(-3*z)*exp(-y**2*z/2)/(2*sqrt(pi))
|
472 |
+
|
473 |
+
References
|
474 |
+
==========
|
475 |
+
|
476 |
+
.. [1] https://en.wikipedia.org/wiki/Normal-gamma_distribution
|
477 |
+
|
478 |
+
"""
|
479 |
+
return multivariate_rv(NormalGammaDistribution, sym, mu, lamda, alpha, beta)
|
480 |
+
|
481 |
+
#-------------------------------------------------------------------------------
|
482 |
+
# Multivariate Beta/Dirichlet distribution -------------------------------------
|
483 |
+
|
484 |
+
class MultivariateBetaDistribution(JointDistribution):
|
485 |
+
|
486 |
+
_argnames = ('alpha',)
|
487 |
+
is_Continuous = True
|
488 |
+
|
489 |
+
@staticmethod
|
490 |
+
def check(alpha):
|
491 |
+
_value_check(len(alpha) >= 2, "At least two categories should be passed.")
|
492 |
+
for a_k in alpha:
|
493 |
+
_value_check((a_k > 0) != False, "Each concentration parameter"
|
494 |
+
" should be positive.")
|
495 |
+
|
496 |
+
@property
|
497 |
+
def set(self):
|
498 |
+
k = len(self.alpha)
|
499 |
+
return Interval(0, 1)**k
|
500 |
+
|
501 |
+
def pdf(self, *syms):
|
502 |
+
alpha = self.alpha
|
503 |
+
B = Mul.fromiter(map(gamma, alpha))/gamma(Add(*alpha))
|
504 |
+
return Mul.fromiter(sym**(a_k - 1) for a_k, sym in zip(alpha, syms))/B
|
505 |
+
|
506 |
+
def MultivariateBeta(syms, *alpha):
|
507 |
+
"""
|
508 |
+
Creates a continuous random variable with Dirichlet/Multivariate Beta
|
509 |
+
Distribution.
|
510 |
+
|
511 |
+
The density of the Dirichlet distribution can be found at [1].
|
512 |
+
|
513 |
+
Parameters
|
514 |
+
==========
|
515 |
+
|
516 |
+
alpha : Positive real numbers
|
517 |
+
Signifies concentration numbers.
|
518 |
+
|
519 |
+
Returns
|
520 |
+
=======
|
521 |
+
|
522 |
+
RandomSymbol
|
523 |
+
|
524 |
+
Examples
|
525 |
+
========
|
526 |
+
|
527 |
+
>>> from sympy.stats import density, MultivariateBeta, marginal_distribution
|
528 |
+
>>> from sympy import Symbol
|
529 |
+
>>> a1 = Symbol('a1', positive=True)
|
530 |
+
>>> a2 = Symbol('a2', positive=True)
|
531 |
+
>>> B = MultivariateBeta('B', [a1, a2])
|
532 |
+
>>> C = MultivariateBeta('C', a1, a2)
|
533 |
+
>>> x = Symbol('x')
|
534 |
+
>>> y = Symbol('y')
|
535 |
+
>>> density(B)(x, y)
|
536 |
+
x**(a1 - 1)*y**(a2 - 1)*gamma(a1 + a2)/(gamma(a1)*gamma(a2))
|
537 |
+
>>> marginal_distribution(C, C[0])(x)
|
538 |
+
x**(a1 - 1)*gamma(a1 + a2)/(a2*gamma(a1)*gamma(a2))
|
539 |
+
|
540 |
+
References
|
541 |
+
==========
|
542 |
+
|
543 |
+
.. [1] https://en.wikipedia.org/wiki/Dirichlet_distribution
|
544 |
+
.. [2] https://mathworld.wolfram.com/DirichletDistribution.html
|
545 |
+
|
546 |
+
"""
|
547 |
+
if not isinstance(alpha[0], list):
|
548 |
+
alpha = (list(alpha),)
|
549 |
+
return multivariate_rv(MultivariateBetaDistribution, syms, alpha[0])
|
550 |
+
|
551 |
+
Dirichlet = MultivariateBeta
|
552 |
+
|
553 |
+
#-------------------------------------------------------------------------------
|
554 |
+
# Multivariate Ewens distribution ----------------------------------------------
|
555 |
+
|
556 |
+
class MultivariateEwensDistribution(JointDistribution):
|
557 |
+
|
558 |
+
_argnames = ('n', 'theta')
|
559 |
+
is_Discrete = True
|
560 |
+
is_Continuous = False
|
561 |
+
|
562 |
+
@staticmethod
|
563 |
+
def check(n, theta):
|
564 |
+
_value_check((n > 0),
|
565 |
+
"sample size should be positive integer.")
|
566 |
+
_value_check(theta.is_positive, "mutation rate should be positive.")
|
567 |
+
|
568 |
+
@property
|
569 |
+
def set(self):
|
570 |
+
if not isinstance(self.n, Integer):
|
571 |
+
i = Symbol('i', integer=True, positive=True)
|
572 |
+
return Product(Intersection(S.Naturals0, Interval(0, self.n//i)),
|
573 |
+
(i, 1, self.n))
|
574 |
+
prod_set = Range(0, self.n + 1)
|
575 |
+
for i in range(2, self.n + 1):
|
576 |
+
prod_set *= Range(0, self.n//i + 1)
|
577 |
+
return prod_set.flatten()
|
578 |
+
|
579 |
+
def pdf(self, *syms):
|
580 |
+
n, theta = self.n, self.theta
|
581 |
+
condi = isinstance(self.n, Integer)
|
582 |
+
if not (isinstance(syms[0], IndexedBase) or condi):
|
583 |
+
raise ValueError("Please use IndexedBase object for syms as "
|
584 |
+
"the dimension is symbolic")
|
585 |
+
term_1 = factorial(n)/rf(theta, n)
|
586 |
+
if condi:
|
587 |
+
term_2 = Mul.fromiter(theta**syms[j]/((j+1)**syms[j]*factorial(syms[j]))
|
588 |
+
for j in range(n))
|
589 |
+
cond = Eq(sum([(k + 1)*syms[k] for k in range(n)]), n)
|
590 |
+
return Piecewise((term_1 * term_2, cond), (0, True))
|
591 |
+
syms = syms[0]
|
592 |
+
j, k = symbols('j, k', positive=True, integer=True)
|
593 |
+
term_2 = Product(theta**syms[j]/((j+1)**syms[j]*factorial(syms[j])),
|
594 |
+
(j, 0, n - 1))
|
595 |
+
cond = Eq(Sum((k + 1)*syms[k], (k, 0, n - 1)), n)
|
596 |
+
return Piecewise((term_1 * term_2, cond), (0, True))
|
597 |
+
|
598 |
+
|
599 |
+
def MultivariateEwens(syms, n, theta):
|
600 |
+
"""
|
601 |
+
Creates a discrete random variable with Multivariate Ewens
|
602 |
+
Distribution.
|
603 |
+
|
604 |
+
The density of the said distribution can be found at [1].
|
605 |
+
|
606 |
+
Parameters
|
607 |
+
==========
|
608 |
+
|
609 |
+
n : Positive integer
|
610 |
+
Size of the sample or the integer whose partitions are considered
|
611 |
+
theta : Positive real number
|
612 |
+
Denotes Mutation rate
|
613 |
+
|
614 |
+
Returns
|
615 |
+
=======
|
616 |
+
|
617 |
+
RandomSymbol
|
618 |
+
|
619 |
+
Examples
|
620 |
+
========
|
621 |
+
|
622 |
+
>>> from sympy.stats import density, marginal_distribution, MultivariateEwens
|
623 |
+
>>> from sympy import Symbol
|
624 |
+
>>> a1 = Symbol('a1', positive=True)
|
625 |
+
>>> a2 = Symbol('a2', positive=True)
|
626 |
+
>>> ed = MultivariateEwens('E', 2, 1)
|
627 |
+
>>> density(ed)(a1, a2)
|
628 |
+
Piecewise((1/(2**a2*factorial(a1)*factorial(a2)), Eq(a1 + 2*a2, 2)), (0, True))
|
629 |
+
>>> marginal_distribution(ed, ed[0])(a1)
|
630 |
+
Piecewise((1/factorial(a1), Eq(a1, 2)), (0, True))
|
631 |
+
|
632 |
+
References
|
633 |
+
==========
|
634 |
+
|
635 |
+
.. [1] https://en.wikipedia.org/wiki/Ewens%27s_sampling_formula
|
636 |
+
.. [2] https://www.researchgate.net/publication/280311472_The_Ubiquitous_Ewens_Sampling_Formula
|
637 |
+
|
638 |
+
"""
|
639 |
+
return multivariate_rv(MultivariateEwensDistribution, syms, n, theta)
|
640 |
+
|
641 |
+
#-------------------------------------------------------------------------------
|
642 |
+
# Generalized Multivariate Log Gamma distribution ------------------------------
|
643 |
+
|
644 |
+
class GeneralizedMultivariateLogGammaDistribution(JointDistribution):
|
645 |
+
|
646 |
+
_argnames = ('delta', 'v', 'lamda', 'mu')
|
647 |
+
is_Continuous=True
|
648 |
+
|
649 |
+
def check(self, delta, v, l, mu):
|
650 |
+
_value_check((delta >= 0, delta <= 1), "delta must be in range [0, 1].")
|
651 |
+
_value_check((v > 0), "v must be positive")
|
652 |
+
for lk in l:
|
653 |
+
_value_check((lk > 0), "lamda must be a positive vector.")
|
654 |
+
for muk in mu:
|
655 |
+
_value_check((muk > 0), "mu must be a positive vector.")
|
656 |
+
_value_check(len(l) > 1,"the distribution should have at least"
|
657 |
+
" two random variables.")
|
658 |
+
|
659 |
+
@property
|
660 |
+
def set(self):
|
661 |
+
return S.Reals**len(self.lamda)
|
662 |
+
|
663 |
+
def pdf(self, *y):
|
664 |
+
d, v, l, mu = self.delta, self.v, self.lamda, self.mu
|
665 |
+
n = Symbol('n', negative=False, integer=True)
|
666 |
+
k = len(l)
|
667 |
+
sterm1 = Pow((1 - d), n)/\
|
668 |
+
((gamma(v + n)**(k - 1))*gamma(v)*gamma(n + 1))
|
669 |
+
sterm2 = Mul.fromiter(mui*li**(-v - n) for mui, li in zip(mu, l))
|
670 |
+
term1 = sterm1 * sterm2
|
671 |
+
sterm3 = (v + n) * sum([mui * yi for mui, yi in zip(mu, y)])
|
672 |
+
sterm4 = sum([exp(mui * yi)/li for (mui, yi, li) in zip(mu, y, l)])
|
673 |
+
term2 = exp(sterm3 - sterm4)
|
674 |
+
return Pow(d, v) * Sum(term1 * term2, (n, 0, S.Infinity))
|
675 |
+
|
676 |
+
def GeneralizedMultivariateLogGamma(syms, delta, v, lamda, mu):
|
677 |
+
"""
|
678 |
+
Creates a joint random variable with generalized multivariate log gamma
|
679 |
+
distribution.
|
680 |
+
|
681 |
+
The joint pdf can be found at [1].
|
682 |
+
|
683 |
+
Parameters
|
684 |
+
==========
|
685 |
+
|
686 |
+
syms : list/tuple/set of symbols for identifying each component
|
687 |
+
delta : A constant in range $[0, 1]$
|
688 |
+
v : Positive real number
|
689 |
+
lamda : List of positive real numbers
|
690 |
+
mu : List of positive real numbers
|
691 |
+
|
692 |
+
Returns
|
693 |
+
=======
|
694 |
+
|
695 |
+
RandomSymbol
|
696 |
+
|
697 |
+
Examples
|
698 |
+
========
|
699 |
+
|
700 |
+
>>> from sympy.stats import density
|
701 |
+
>>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGamma
|
702 |
+
>>> from sympy import symbols, S
|
703 |
+
>>> v = 1
|
704 |
+
>>> l, mu = [1, 1, 1], [1, 1, 1]
|
705 |
+
>>> d = S.Half
|
706 |
+
>>> y = symbols('y_1:4', positive=True)
|
707 |
+
>>> Gd = GeneralizedMultivariateLogGamma('G', d, v, l, mu)
|
708 |
+
>>> density(Gd)(y[0], y[1], y[2])
|
709 |
+
Sum(exp((n + 1)*(y_1 + y_2 + y_3) - exp(y_1) - exp(y_2) -
|
710 |
+
exp(y_3))/(2**n*gamma(n + 1)**3), (n, 0, oo))/2
|
711 |
+
|
712 |
+
References
|
713 |
+
==========
|
714 |
+
|
715 |
+
.. [1] https://en.wikipedia.org/wiki/Generalized_multivariate_log-gamma_distribution
|
716 |
+
.. [2] https://www.researchgate.net/publication/234137346_On_a_multivariate_log-gamma_distribution_and_the_use_of_the_distribution_in_the_Bayesian_analysis
|
717 |
+
|
718 |
+
Note
|
719 |
+
====
|
720 |
+
|
721 |
+
If the GeneralizedMultivariateLogGamma is too long to type use,
|
722 |
+
|
723 |
+
>>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGamma as GMVLG
|
724 |
+
>>> Gd = GMVLG('G', d, v, l, mu)
|
725 |
+
|
726 |
+
If you want to pass the matrix omega instead of the constant delta, then use
|
727 |
+
``GeneralizedMultivariateLogGammaOmega``.
|
728 |
+
|
729 |
+
"""
|
730 |
+
return multivariate_rv(GeneralizedMultivariateLogGammaDistribution,
|
731 |
+
syms, delta, v, lamda, mu)
|
732 |
+
|
733 |
+
def GeneralizedMultivariateLogGammaOmega(syms, omega, v, lamda, mu):
|
734 |
+
"""
|
735 |
+
Extends GeneralizedMultivariateLogGamma.
|
736 |
+
|
737 |
+
Parameters
|
738 |
+
==========
|
739 |
+
|
740 |
+
syms : list/tuple/set of symbols
|
741 |
+
For identifying each component
|
742 |
+
omega : A square matrix
|
743 |
+
Every element of square matrix must be absolute value of
|
744 |
+
square root of correlation coefficient
|
745 |
+
v : Positive real number
|
746 |
+
lamda : List of positive real numbers
|
747 |
+
mu : List of positive real numbers
|
748 |
+
|
749 |
+
Returns
|
750 |
+
=======
|
751 |
+
|
752 |
+
RandomSymbol
|
753 |
+
|
754 |
+
Examples
|
755 |
+
========
|
756 |
+
|
757 |
+
>>> from sympy.stats import density
|
758 |
+
>>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega
|
759 |
+
>>> from sympy import Matrix, symbols, S
|
760 |
+
>>> omega = Matrix([[1, S.Half, S.Half], [S.Half, 1, S.Half], [S.Half, S.Half, 1]])
|
761 |
+
>>> v = 1
|
762 |
+
>>> l, mu = [1, 1, 1], [1, 1, 1]
|
763 |
+
>>> G = GeneralizedMultivariateLogGammaOmega('G', omega, v, l, mu)
|
764 |
+
>>> y = symbols('y_1:4', positive=True)
|
765 |
+
>>> density(G)(y[0], y[1], y[2])
|
766 |
+
sqrt(2)*Sum((1 - sqrt(2)/2)**n*exp((n + 1)*(y_1 + y_2 + y_3) - exp(y_1) -
|
767 |
+
exp(y_2) - exp(y_3))/gamma(n + 1)**3, (n, 0, oo))/2
|
768 |
+
|
769 |
+
References
|
770 |
+
==========
|
771 |
+
|
772 |
+
.. [1] https://en.wikipedia.org/wiki/Generalized_multivariate_log-gamma_distribution
|
773 |
+
.. [2] https://www.researchgate.net/publication/234137346_On_a_multivariate_log-gamma_distribution_and_the_use_of_the_distribution_in_the_Bayesian_analysis
|
774 |
+
|
775 |
+
Notes
|
776 |
+
=====
|
777 |
+
|
778 |
+
If the GeneralizedMultivariateLogGammaOmega is too long to type use,
|
779 |
+
|
780 |
+
>>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega as GMVLGO
|
781 |
+
>>> G = GMVLGO('G', omega, v, l, mu)
|
782 |
+
|
783 |
+
"""
|
784 |
+
_value_check((omega.is_square, isinstance(omega, Matrix)), "omega must be a"
|
785 |
+
" square matrix")
|
786 |
+
for val in omega.values():
|
787 |
+
_value_check((val >= 0, val <= 1),
|
788 |
+
"all values in matrix must be between 0 and 1(both inclusive).")
|
789 |
+
_value_check(omega.diagonal().equals(ones(1, omega.shape[0])),
|
790 |
+
"all the elements of diagonal should be 1.")
|
791 |
+
_value_check((omega.shape[0] == len(lamda), len(lamda) == len(mu)),
|
792 |
+
"lamda, mu should be of same length and omega should "
|
793 |
+
" be of shape (length of lamda, length of mu)")
|
794 |
+
_value_check(len(lamda) > 1,"the distribution should have at least"
|
795 |
+
" two random variables.")
|
796 |
+
delta = Pow(Rational(omega.det()), Rational(1, len(lamda) - 1))
|
797 |
+
return GeneralizedMultivariateLogGamma(syms, delta, v, lamda, mu)
|
798 |
+
|
799 |
+
|
800 |
+
#-------------------------------------------------------------------------------
|
801 |
+
# Multinomial distribution -----------------------------------------------------
|
802 |
+
|
803 |
+
class MultinomialDistribution(JointDistribution):
|
804 |
+
|
805 |
+
_argnames = ('n', 'p')
|
806 |
+
is_Continuous=False
|
807 |
+
is_Discrete = True
|
808 |
+
|
809 |
+
@staticmethod
|
810 |
+
def check(n, p):
|
811 |
+
_value_check(n > 0,
|
812 |
+
"number of trials must be a positive integer")
|
813 |
+
for p_k in p:
|
814 |
+
_value_check((p_k >= 0, p_k <= 1),
|
815 |
+
"probability must be in range [0, 1]")
|
816 |
+
_value_check(Eq(sum(p), 1),
|
817 |
+
"probabilities must sum to 1")
|
818 |
+
|
819 |
+
@property
|
820 |
+
def set(self):
|
821 |
+
return Intersection(S.Naturals0, Interval(0, self.n))**len(self.p)
|
822 |
+
|
823 |
+
def pdf(self, *x):
|
824 |
+
n, p = self.n, self.p
|
825 |
+
term_1 = factorial(n)/Mul.fromiter(factorial(x_k) for x_k in x)
|
826 |
+
term_2 = Mul.fromiter(p_k**x_k for p_k, x_k in zip(p, x))
|
827 |
+
return Piecewise((term_1 * term_2, Eq(sum(x), n)), (0, True))
|
828 |
+
|
829 |
+
def Multinomial(syms, n, *p):
|
830 |
+
"""
|
831 |
+
Creates a discrete random variable with Multinomial Distribution.
|
832 |
+
|
833 |
+
The density of the said distribution can be found at [1].
|
834 |
+
|
835 |
+
Parameters
|
836 |
+
==========
|
837 |
+
|
838 |
+
n : Positive integer
|
839 |
+
Represents number of trials
|
840 |
+
p : List of event probabilities
|
841 |
+
Must be in the range of $[0, 1]$.
|
842 |
+
|
843 |
+
Returns
|
844 |
+
=======
|
845 |
+
|
846 |
+
RandomSymbol
|
847 |
+
|
848 |
+
Examples
|
849 |
+
========
|
850 |
+
|
851 |
+
>>> from sympy.stats import density, Multinomial, marginal_distribution
|
852 |
+
>>> from sympy import symbols
|
853 |
+
>>> x1, x2, x3 = symbols('x1, x2, x3', nonnegative=True, integer=True)
|
854 |
+
>>> p1, p2, p3 = symbols('p1, p2, p3', positive=True)
|
855 |
+
>>> M = Multinomial('M', 3, p1, p2, p3)
|
856 |
+
>>> density(M)(x1, x2, x3)
|
857 |
+
Piecewise((6*p1**x1*p2**x2*p3**x3/(factorial(x1)*factorial(x2)*factorial(x3)),
|
858 |
+
Eq(x1 + x2 + x3, 3)), (0, True))
|
859 |
+
>>> marginal_distribution(M, M[0])(x1).subs(x1, 1)
|
860 |
+
3*p1*p2**2 + 6*p1*p2*p3 + 3*p1*p3**2
|
861 |
+
|
862 |
+
References
|
863 |
+
==========
|
864 |
+
|
865 |
+
.. [1] https://en.wikipedia.org/wiki/Multinomial_distribution
|
866 |
+
.. [2] https://mathworld.wolfram.com/MultinomialDistribution.html
|
867 |
+
|
868 |
+
"""
|
869 |
+
if not isinstance(p[0], list):
|
870 |
+
p = (list(p), )
|
871 |
+
return multivariate_rv(MultinomialDistribution, syms, n, p[0])
|
872 |
+
|
873 |
+
#-------------------------------------------------------------------------------
|
874 |
+
# Negative Multinomial Distribution --------------------------------------------
|
875 |
+
|
876 |
+
class NegativeMultinomialDistribution(JointDistribution):
|
877 |
+
|
878 |
+
_argnames = ('k0', 'p')
|
879 |
+
is_Continuous=False
|
880 |
+
is_Discrete = True
|
881 |
+
|
882 |
+
@staticmethod
|
883 |
+
def check(k0, p):
|
884 |
+
_value_check(k0 > 0,
|
885 |
+
"number of failures must be a positive integer")
|
886 |
+
for p_k in p:
|
887 |
+
_value_check((p_k >= 0, p_k <= 1),
|
888 |
+
"probability must be in range [0, 1].")
|
889 |
+
_value_check(sum(p) <= 1,
|
890 |
+
"success probabilities must not be greater than 1.")
|
891 |
+
|
892 |
+
@property
|
893 |
+
def set(self):
|
894 |
+
return Range(0, S.Infinity)**len(self.p)
|
895 |
+
|
896 |
+
def pdf(self, *k):
|
897 |
+
k0, p = self.k0, self.p
|
898 |
+
term_1 = (gamma(k0 + sum(k))*(1 - sum(p))**k0)/gamma(k0)
|
899 |
+
term_2 = Mul.fromiter(pi**ki/factorial(ki) for pi, ki in zip(p, k))
|
900 |
+
return term_1 * term_2
|
901 |
+
|
902 |
+
def NegativeMultinomial(syms, k0, *p):
|
903 |
+
"""
|
904 |
+
Creates a discrete random variable with Negative Multinomial Distribution.
|
905 |
+
|
906 |
+
The density of the said distribution can be found at [1].
|
907 |
+
|
908 |
+
Parameters
|
909 |
+
==========
|
910 |
+
|
911 |
+
k0 : positive integer
|
912 |
+
Represents number of failures before the experiment is stopped
|
913 |
+
p : List of event probabilities
|
914 |
+
Must be in the range of $[0, 1]$
|
915 |
+
|
916 |
+
Returns
|
917 |
+
=======
|
918 |
+
|
919 |
+
RandomSymbol
|
920 |
+
|
921 |
+
Examples
|
922 |
+
========
|
923 |
+
|
924 |
+
>>> from sympy.stats import density, NegativeMultinomial, marginal_distribution
|
925 |
+
>>> from sympy import symbols
|
926 |
+
>>> x1, x2, x3 = symbols('x1, x2, x3', nonnegative=True, integer=True)
|
927 |
+
>>> p1, p2, p3 = symbols('p1, p2, p3', positive=True)
|
928 |
+
>>> N = NegativeMultinomial('M', 3, p1, p2, p3)
|
929 |
+
>>> N_c = NegativeMultinomial('M', 3, 0.1, 0.1, 0.1)
|
930 |
+
>>> density(N)(x1, x2, x3)
|
931 |
+
p1**x1*p2**x2*p3**x3*(-p1 - p2 - p3 + 1)**3*gamma(x1 + x2 +
|
932 |
+
x3 + 3)/(2*factorial(x1)*factorial(x2)*factorial(x3))
|
933 |
+
>>> marginal_distribution(N_c, N_c[0])(1).evalf().round(2)
|
934 |
+
0.25
|
935 |
+
|
936 |
+
|
937 |
+
References
|
938 |
+
==========
|
939 |
+
|
940 |
+
.. [1] https://en.wikipedia.org/wiki/Negative_multinomial_distribution
|
941 |
+
.. [2] https://mathworld.wolfram.com/NegativeBinomialDistribution.html
|
942 |
+
|
943 |
+
"""
|
944 |
+
if not isinstance(p[0], list):
|
945 |
+
p = (list(p), )
|
946 |
+
return multivariate_rv(NegativeMultinomialDistribution, syms, k0, p[0])
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/matrix_distributions.py
ADDED
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from math import prod
|
2 |
+
|
3 |
+
from sympy.core.basic import Basic
|
4 |
+
from sympy.core.numbers import pi
|
5 |
+
from sympy.core.singleton import S
|
6 |
+
from sympy.functions.elementary.exponential import exp
|
7 |
+
from sympy.functions.special.gamma_functions import multigamma
|
8 |
+
from sympy.core.sympify import sympify, _sympify
|
9 |
+
from sympy.matrices import (ImmutableMatrix, Inverse, Trace, Determinant,
|
10 |
+
MatrixSymbol, MatrixBase, Transpose, MatrixSet,
|
11 |
+
matrix2numpy)
|
12 |
+
from sympy.stats.rv import (_value_check, RandomMatrixSymbol, NamedArgsMixin, PSpace,
|
13 |
+
_symbol_converter, MatrixDomain, Distribution)
|
14 |
+
from sympy.external import import_module
|
15 |
+
|
16 |
+
|
17 |
+
################################################################################
|
18 |
+
#------------------------Matrix Probability Space------------------------------#
|
19 |
+
################################################################################
|
20 |
+
class MatrixPSpace(PSpace):
|
21 |
+
"""
|
22 |
+
Represents probability space for
|
23 |
+
Matrix Distributions.
|
24 |
+
"""
|
25 |
+
def __new__(cls, sym, distribution, dim_n, dim_m):
|
26 |
+
sym = _symbol_converter(sym)
|
27 |
+
dim_n, dim_m = _sympify(dim_n), _sympify(dim_m)
|
28 |
+
if not (dim_n.is_integer and dim_m.is_integer):
|
29 |
+
raise ValueError("Dimensions should be integers")
|
30 |
+
return Basic.__new__(cls, sym, distribution, dim_n, dim_m)
|
31 |
+
|
32 |
+
distribution = property(lambda self: self.args[1])
|
33 |
+
symbol = property(lambda self: self.args[0])
|
34 |
+
|
35 |
+
@property
|
36 |
+
def domain(self):
|
37 |
+
return MatrixDomain(self.symbol, self.distribution.set)
|
38 |
+
|
39 |
+
@property
|
40 |
+
def value(self):
|
41 |
+
return RandomMatrixSymbol(self.symbol, self.args[2], self.args[3], self)
|
42 |
+
|
43 |
+
@property
|
44 |
+
def values(self):
|
45 |
+
return {self.value}
|
46 |
+
|
47 |
+
def compute_density(self, expr, *args):
|
48 |
+
rms = expr.atoms(RandomMatrixSymbol)
|
49 |
+
if len(rms) > 1 or (not isinstance(expr, RandomMatrixSymbol)):
|
50 |
+
raise NotImplementedError("Currently, no algorithm has been "
|
51 |
+
"implemented to handle general expressions containing "
|
52 |
+
"multiple matrix distributions.")
|
53 |
+
return self.distribution.pdf(expr)
|
54 |
+
|
55 |
+
def sample(self, size=(), library='scipy', seed=None):
|
56 |
+
"""
|
57 |
+
Internal sample method
|
58 |
+
|
59 |
+
Returns dictionary mapping RandomMatrixSymbol to realization value.
|
60 |
+
"""
|
61 |
+
return {self.value: self.distribution.sample(size, library=library, seed=seed)}
|
62 |
+
|
63 |
+
|
64 |
+
def rv(symbol, cls, args):
|
65 |
+
args = list(map(sympify, args))
|
66 |
+
dist = cls(*args)
|
67 |
+
dist.check(*args)
|
68 |
+
dim = dist.dimension
|
69 |
+
pspace = MatrixPSpace(symbol, dist, dim[0], dim[1])
|
70 |
+
return pspace.value
|
71 |
+
|
72 |
+
|
73 |
+
class SampleMatrixScipy:
|
74 |
+
"""Returns the sample from scipy of the given distribution"""
|
75 |
+
def __new__(cls, dist, size, seed=None):
|
76 |
+
return cls._sample_scipy(dist, size, seed)
|
77 |
+
|
78 |
+
@classmethod
|
79 |
+
def _sample_scipy(cls, dist, size, seed):
|
80 |
+
"""Sample from SciPy."""
|
81 |
+
|
82 |
+
from scipy import stats as scipy_stats
|
83 |
+
import numpy
|
84 |
+
scipy_rv_map = {
|
85 |
+
'WishartDistribution': lambda dist, size, rand_state: scipy_stats.wishart.rvs(
|
86 |
+
df=int(dist.n), scale=matrix2numpy(dist.scale_matrix, float), size=size),
|
87 |
+
'MatrixNormalDistribution': lambda dist, size, rand_state: scipy_stats.matrix_normal.rvs(
|
88 |
+
mean=matrix2numpy(dist.location_matrix, float),
|
89 |
+
rowcov=matrix2numpy(dist.scale_matrix_1, float),
|
90 |
+
colcov=matrix2numpy(dist.scale_matrix_2, float), size=size, random_state=rand_state)
|
91 |
+
}
|
92 |
+
|
93 |
+
sample_shape = {
|
94 |
+
'WishartDistribution': lambda dist: dist.scale_matrix.shape,
|
95 |
+
'MatrixNormalDistribution' : lambda dist: dist.location_matrix.shape
|
96 |
+
}
|
97 |
+
|
98 |
+
dist_list = scipy_rv_map.keys()
|
99 |
+
|
100 |
+
if dist.__class__.__name__ not in dist_list:
|
101 |
+
return None
|
102 |
+
|
103 |
+
if seed is None or isinstance(seed, int):
|
104 |
+
rand_state = numpy.random.default_rng(seed=seed)
|
105 |
+
else:
|
106 |
+
rand_state = seed
|
107 |
+
samp = scipy_rv_map[dist.__class__.__name__](dist, prod(size), rand_state)
|
108 |
+
return samp.reshape(size + sample_shape[dist.__class__.__name__](dist))
|
109 |
+
|
110 |
+
|
111 |
+
class SampleMatrixNumpy:
|
112 |
+
"""Returns the sample from numpy of the given distribution"""
|
113 |
+
|
114 |
+
### TODO: Add tests after adding matrix distributions in numpy_rv_map
|
115 |
+
def __new__(cls, dist, size, seed=None):
|
116 |
+
return cls._sample_numpy(dist, size, seed)
|
117 |
+
|
118 |
+
@classmethod
|
119 |
+
def _sample_numpy(cls, dist, size, seed):
|
120 |
+
"""Sample from NumPy."""
|
121 |
+
|
122 |
+
numpy_rv_map = {
|
123 |
+
}
|
124 |
+
|
125 |
+
sample_shape = {
|
126 |
+
}
|
127 |
+
|
128 |
+
dist_list = numpy_rv_map.keys()
|
129 |
+
|
130 |
+
if dist.__class__.__name__ not in dist_list:
|
131 |
+
return None
|
132 |
+
|
133 |
+
import numpy
|
134 |
+
if seed is None or isinstance(seed, int):
|
135 |
+
rand_state = numpy.random.default_rng(seed=seed)
|
136 |
+
else:
|
137 |
+
rand_state = seed
|
138 |
+
samp = numpy_rv_map[dist.__class__.__name__](dist, prod(size), rand_state)
|
139 |
+
return samp.reshape(size + sample_shape[dist.__class__.__name__](dist))
|
140 |
+
|
141 |
+
|
142 |
+
class SampleMatrixPymc:
|
143 |
+
"""Returns the sample from pymc of the given distribution"""
|
144 |
+
|
145 |
+
def __new__(cls, dist, size, seed=None):
|
146 |
+
return cls._sample_pymc(dist, size, seed)
|
147 |
+
|
148 |
+
@classmethod
|
149 |
+
def _sample_pymc(cls, dist, size, seed):
|
150 |
+
"""Sample from PyMC."""
|
151 |
+
|
152 |
+
try:
|
153 |
+
import pymc
|
154 |
+
except ImportError:
|
155 |
+
import pymc3 as pymc
|
156 |
+
pymc_rv_map = {
|
157 |
+
'MatrixNormalDistribution': lambda dist: pymc.MatrixNormal('X',
|
158 |
+
mu=matrix2numpy(dist.location_matrix, float),
|
159 |
+
rowcov=matrix2numpy(dist.scale_matrix_1, float),
|
160 |
+
colcov=matrix2numpy(dist.scale_matrix_2, float),
|
161 |
+
shape=dist.location_matrix.shape),
|
162 |
+
'WishartDistribution': lambda dist: pymc.WishartBartlett('X',
|
163 |
+
nu=int(dist.n), S=matrix2numpy(dist.scale_matrix, float))
|
164 |
+
}
|
165 |
+
|
166 |
+
sample_shape = {
|
167 |
+
'WishartDistribution': lambda dist: dist.scale_matrix.shape,
|
168 |
+
'MatrixNormalDistribution' : lambda dist: dist.location_matrix.shape
|
169 |
+
}
|
170 |
+
|
171 |
+
dist_list = pymc_rv_map.keys()
|
172 |
+
|
173 |
+
if dist.__class__.__name__ not in dist_list:
|
174 |
+
return None
|
175 |
+
import logging
|
176 |
+
logging.getLogger("pymc").setLevel(logging.ERROR)
|
177 |
+
with pymc.Model():
|
178 |
+
pymc_rv_map[dist.__class__.__name__](dist)
|
179 |
+
samps = pymc.sample(draws=prod(size), chains=1, progressbar=False, random_seed=seed, return_inferencedata=False, compute_convergence_checks=False)['X']
|
180 |
+
return samps.reshape(size + sample_shape[dist.__class__.__name__](dist))
|
181 |
+
|
182 |
+
_get_sample_class_matrixrv = {
|
183 |
+
'scipy': SampleMatrixScipy,
|
184 |
+
'pymc3': SampleMatrixPymc,
|
185 |
+
'pymc': SampleMatrixPymc,
|
186 |
+
'numpy': SampleMatrixNumpy
|
187 |
+
}
|
188 |
+
|
189 |
+
################################################################################
|
190 |
+
#-------------------------Matrix Distribution----------------------------------#
|
191 |
+
################################################################################
|
192 |
+
|
193 |
+
class MatrixDistribution(Distribution, NamedArgsMixin):
|
194 |
+
"""
|
195 |
+
Abstract class for Matrix Distribution.
|
196 |
+
"""
|
197 |
+
def __new__(cls, *args):
|
198 |
+
args = [ImmutableMatrix(arg) if isinstance(arg, list)
|
199 |
+
else _sympify(arg) for arg in args]
|
200 |
+
return Basic.__new__(cls, *args)
|
201 |
+
|
202 |
+
@staticmethod
|
203 |
+
def check(*args):
|
204 |
+
pass
|
205 |
+
|
206 |
+
def __call__(self, expr):
|
207 |
+
if isinstance(expr, list):
|
208 |
+
expr = ImmutableMatrix(expr)
|
209 |
+
return self.pdf(expr)
|
210 |
+
|
211 |
+
def sample(self, size=(), library='scipy', seed=None):
|
212 |
+
"""
|
213 |
+
Internal sample method
|
214 |
+
|
215 |
+
Returns dictionary mapping RandomSymbol to realization value.
|
216 |
+
"""
|
217 |
+
|
218 |
+
libraries = ['scipy', 'numpy', 'pymc3', 'pymc']
|
219 |
+
if library not in libraries:
|
220 |
+
raise NotImplementedError("Sampling from %s is not supported yet."
|
221 |
+
% str(library))
|
222 |
+
if not import_module(library):
|
223 |
+
raise ValueError("Failed to import %s" % library)
|
224 |
+
|
225 |
+
samps = _get_sample_class_matrixrv[library](self, size, seed)
|
226 |
+
|
227 |
+
if samps is not None:
|
228 |
+
return samps
|
229 |
+
raise NotImplementedError(
|
230 |
+
"Sampling for %s is not currently implemented from %s"
|
231 |
+
% (self.__class__.__name__, library)
|
232 |
+
)
|
233 |
+
|
234 |
+
################################################################################
|
235 |
+
#------------------------Matrix Distribution Types-----------------------------#
|
236 |
+
################################################################################
|
237 |
+
|
238 |
+
#-------------------------------------------------------------------------------
|
239 |
+
# Matrix Gamma distribution ----------------------------------------------------
|
240 |
+
|
241 |
+
class MatrixGammaDistribution(MatrixDistribution):
|
242 |
+
|
243 |
+
_argnames = ('alpha', 'beta', 'scale_matrix')
|
244 |
+
|
245 |
+
@staticmethod
|
246 |
+
def check(alpha, beta, scale_matrix):
|
247 |
+
if not isinstance(scale_matrix, MatrixSymbol):
|
248 |
+
_value_check(scale_matrix.is_positive_definite, "The shape "
|
249 |
+
"matrix must be positive definite.")
|
250 |
+
_value_check(scale_matrix.is_square, "Should "
|
251 |
+
"be square matrix")
|
252 |
+
_value_check(alpha.is_positive, "Shape parameter should be positive.")
|
253 |
+
_value_check(beta.is_positive, "Scale parameter should be positive.")
|
254 |
+
|
255 |
+
@property
|
256 |
+
def set(self):
|
257 |
+
k = self.scale_matrix.shape[0]
|
258 |
+
return MatrixSet(k, k, S.Reals)
|
259 |
+
|
260 |
+
@property
|
261 |
+
def dimension(self):
|
262 |
+
return self.scale_matrix.shape
|
263 |
+
|
264 |
+
def pdf(self, x):
|
265 |
+
alpha, beta, scale_matrix = self.alpha, self.beta, self.scale_matrix
|
266 |
+
p = scale_matrix.shape[0]
|
267 |
+
if isinstance(x, list):
|
268 |
+
x = ImmutableMatrix(x)
|
269 |
+
if not isinstance(x, (MatrixBase, MatrixSymbol)):
|
270 |
+
raise ValueError("%s should be an isinstance of Matrix "
|
271 |
+
"or MatrixSymbol" % str(x))
|
272 |
+
sigma_inv_x = - Inverse(scale_matrix)*x / beta
|
273 |
+
term1 = exp(Trace(sigma_inv_x))/((beta**(p*alpha)) * multigamma(alpha, p))
|
274 |
+
term2 = (Determinant(scale_matrix))**(-alpha)
|
275 |
+
term3 = (Determinant(x))**(alpha - S(p + 1)/2)
|
276 |
+
return term1 * term2 * term3
|
277 |
+
|
278 |
+
def MatrixGamma(symbol, alpha, beta, scale_matrix):
|
279 |
+
"""
|
280 |
+
Creates a random variable with Matrix Gamma Distribution.
|
281 |
+
|
282 |
+
The density of the said distribution can be found at [1].
|
283 |
+
|
284 |
+
Parameters
|
285 |
+
==========
|
286 |
+
|
287 |
+
alpha: Positive Real number
|
288 |
+
Shape Parameter
|
289 |
+
beta: Positive Real number
|
290 |
+
Scale Parameter
|
291 |
+
scale_matrix: Positive definite real square matrix
|
292 |
+
Scale Matrix
|
293 |
+
|
294 |
+
Returns
|
295 |
+
=======
|
296 |
+
|
297 |
+
RandomSymbol
|
298 |
+
|
299 |
+
Examples
|
300 |
+
========
|
301 |
+
|
302 |
+
>>> from sympy.stats import density, MatrixGamma
|
303 |
+
>>> from sympy import MatrixSymbol, symbols
|
304 |
+
>>> a, b = symbols('a b', positive=True)
|
305 |
+
>>> M = MatrixGamma('M', a, b, [[2, 1], [1, 2]])
|
306 |
+
>>> X = MatrixSymbol('X', 2, 2)
|
307 |
+
>>> density(M)(X).doit()
|
308 |
+
exp(Trace(Matrix([
|
309 |
+
[-2/3, 1/3],
|
310 |
+
[ 1/3, -2/3]])*X)/b)*Determinant(X)**(a - 3/2)/(3**a*sqrt(pi)*b**(2*a)*gamma(a)*gamma(a - 1/2))
|
311 |
+
>>> density(M)([[1, 0], [0, 1]]).doit()
|
312 |
+
exp(-4/(3*b))/(3**a*sqrt(pi)*b**(2*a)*gamma(a)*gamma(a - 1/2))
|
313 |
+
|
314 |
+
|
315 |
+
References
|
316 |
+
==========
|
317 |
+
|
318 |
+
.. [1] https://en.wikipedia.org/wiki/Matrix_gamma_distribution
|
319 |
+
|
320 |
+
"""
|
321 |
+
if isinstance(scale_matrix, list):
|
322 |
+
scale_matrix = ImmutableMatrix(scale_matrix)
|
323 |
+
return rv(symbol, MatrixGammaDistribution, (alpha, beta, scale_matrix))
|
324 |
+
|
325 |
+
#-------------------------------------------------------------------------------
|
326 |
+
# Wishart Distribution ---------------------------------------------------------
|
327 |
+
|
328 |
+
class WishartDistribution(MatrixDistribution):
|
329 |
+
|
330 |
+
_argnames = ('n', 'scale_matrix')
|
331 |
+
|
332 |
+
@staticmethod
|
333 |
+
def check(n, scale_matrix):
|
334 |
+
if not isinstance(scale_matrix, MatrixSymbol):
|
335 |
+
_value_check(scale_matrix.is_positive_definite, "The shape "
|
336 |
+
"matrix must be positive definite.")
|
337 |
+
_value_check(scale_matrix.is_square, "Should "
|
338 |
+
"be square matrix")
|
339 |
+
_value_check(n.is_positive, "Shape parameter should be positive.")
|
340 |
+
|
341 |
+
@property
|
342 |
+
def set(self):
|
343 |
+
k = self.scale_matrix.shape[0]
|
344 |
+
return MatrixSet(k, k, S.Reals)
|
345 |
+
|
346 |
+
@property
|
347 |
+
def dimension(self):
|
348 |
+
return self.scale_matrix.shape
|
349 |
+
|
350 |
+
def pdf(self, x):
|
351 |
+
n, scale_matrix = self.n, self.scale_matrix
|
352 |
+
p = scale_matrix.shape[0]
|
353 |
+
if isinstance(x, list):
|
354 |
+
x = ImmutableMatrix(x)
|
355 |
+
if not isinstance(x, (MatrixBase, MatrixSymbol)):
|
356 |
+
raise ValueError("%s should be an isinstance of Matrix "
|
357 |
+
"or MatrixSymbol" % str(x))
|
358 |
+
sigma_inv_x = - Inverse(scale_matrix)*x / S(2)
|
359 |
+
term1 = exp(Trace(sigma_inv_x))/((2**(p*n/S(2))) * multigamma(n/S(2), p))
|
360 |
+
term2 = (Determinant(scale_matrix))**(-n/S(2))
|
361 |
+
term3 = (Determinant(x))**(S(n - p - 1)/2)
|
362 |
+
return term1 * term2 * term3
|
363 |
+
|
364 |
+
def Wishart(symbol, n, scale_matrix):
|
365 |
+
"""
|
366 |
+
Creates a random variable with Wishart Distribution.
|
367 |
+
|
368 |
+
The density of the said distribution can be found at [1].
|
369 |
+
|
370 |
+
Parameters
|
371 |
+
==========
|
372 |
+
|
373 |
+
n: Positive Real number
|
374 |
+
Represents degrees of freedom
|
375 |
+
scale_matrix: Positive definite real square matrix
|
376 |
+
Scale Matrix
|
377 |
+
|
378 |
+
Returns
|
379 |
+
=======
|
380 |
+
|
381 |
+
RandomSymbol
|
382 |
+
|
383 |
+
Examples
|
384 |
+
========
|
385 |
+
|
386 |
+
>>> from sympy.stats import density, Wishart
|
387 |
+
>>> from sympy import MatrixSymbol, symbols
|
388 |
+
>>> n = symbols('n', positive=True)
|
389 |
+
>>> W = Wishart('W', n, [[2, 1], [1, 2]])
|
390 |
+
>>> X = MatrixSymbol('X', 2, 2)
|
391 |
+
>>> density(W)(X).doit()
|
392 |
+
exp(Trace(Matrix([
|
393 |
+
[-1/3, 1/6],
|
394 |
+
[ 1/6, -1/3]])*X))*Determinant(X)**(n/2 - 3/2)/(2**n*3**(n/2)*sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2))
|
395 |
+
>>> density(W)([[1, 0], [0, 1]]).doit()
|
396 |
+
exp(-2/3)/(2**n*3**(n/2)*sqrt(pi)*gamma(n/2)*gamma(n/2 - 1/2))
|
397 |
+
|
398 |
+
References
|
399 |
+
==========
|
400 |
+
|
401 |
+
.. [1] https://en.wikipedia.org/wiki/Wishart_distribution
|
402 |
+
|
403 |
+
"""
|
404 |
+
if isinstance(scale_matrix, list):
|
405 |
+
scale_matrix = ImmutableMatrix(scale_matrix)
|
406 |
+
return rv(symbol, WishartDistribution, (n, scale_matrix))
|
407 |
+
|
408 |
+
#-------------------------------------------------------------------------------
|
409 |
+
# Matrix Normal distribution ---------------------------------------------------
|
410 |
+
|
411 |
+
class MatrixNormalDistribution(MatrixDistribution):
|
412 |
+
|
413 |
+
_argnames = ('location_matrix', 'scale_matrix_1', 'scale_matrix_2')
|
414 |
+
|
415 |
+
@staticmethod
|
416 |
+
def check(location_matrix, scale_matrix_1, scale_matrix_2):
|
417 |
+
if not isinstance(scale_matrix_1, MatrixSymbol):
|
418 |
+
_value_check(scale_matrix_1.is_positive_definite, "The shape "
|
419 |
+
"matrix must be positive definite.")
|
420 |
+
if not isinstance(scale_matrix_2, MatrixSymbol):
|
421 |
+
_value_check(scale_matrix_2.is_positive_definite, "The shape "
|
422 |
+
"matrix must be positive definite.")
|
423 |
+
_value_check(scale_matrix_1.is_square, "Scale matrix 1 should be "
|
424 |
+
"be square matrix")
|
425 |
+
_value_check(scale_matrix_2.is_square, "Scale matrix 2 should be "
|
426 |
+
"be square matrix")
|
427 |
+
n = location_matrix.shape[0]
|
428 |
+
p = location_matrix.shape[1]
|
429 |
+
_value_check(scale_matrix_1.shape[0] == n, "Scale matrix 1 should be"
|
430 |
+
" of shape %s x %s"% (str(n), str(n)))
|
431 |
+
_value_check(scale_matrix_2.shape[0] == p, "Scale matrix 2 should be"
|
432 |
+
" of shape %s x %s"% (str(p), str(p)))
|
433 |
+
|
434 |
+
@property
|
435 |
+
def set(self):
|
436 |
+
n, p = self.location_matrix.shape
|
437 |
+
return MatrixSet(n, p, S.Reals)
|
438 |
+
|
439 |
+
@property
|
440 |
+
def dimension(self):
|
441 |
+
return self.location_matrix.shape
|
442 |
+
|
443 |
+
def pdf(self, x):
|
444 |
+
M, U, V = self.location_matrix, self.scale_matrix_1, self.scale_matrix_2
|
445 |
+
n, p = M.shape
|
446 |
+
if isinstance(x, list):
|
447 |
+
x = ImmutableMatrix(x)
|
448 |
+
if not isinstance(x, (MatrixBase, MatrixSymbol)):
|
449 |
+
raise ValueError("%s should be an isinstance of Matrix "
|
450 |
+
"or MatrixSymbol" % str(x))
|
451 |
+
term1 = Inverse(V)*Transpose(x - M)*Inverse(U)*(x - M)
|
452 |
+
num = exp(-Trace(term1)/S(2))
|
453 |
+
den = (2*pi)**(S(n*p)/2) * Determinant(U)**(S(p)/2) * Determinant(V)**(S(n)/2)
|
454 |
+
return num/den
|
455 |
+
|
456 |
+
def MatrixNormal(symbol, location_matrix, scale_matrix_1, scale_matrix_2):
|
457 |
+
"""
|
458 |
+
Creates a random variable with Matrix Normal Distribution.
|
459 |
+
|
460 |
+
The density of the said distribution can be found at [1].
|
461 |
+
|
462 |
+
Parameters
|
463 |
+
==========
|
464 |
+
|
465 |
+
location_matrix: Real ``n x p`` matrix
|
466 |
+
Represents degrees of freedom
|
467 |
+
scale_matrix_1: Positive definite matrix
|
468 |
+
Scale Matrix of shape ``n x n``
|
469 |
+
scale_matrix_2: Positive definite matrix
|
470 |
+
Scale Matrix of shape ``p x p``
|
471 |
+
|
472 |
+
Returns
|
473 |
+
=======
|
474 |
+
|
475 |
+
RandomSymbol
|
476 |
+
|
477 |
+
Examples
|
478 |
+
========
|
479 |
+
|
480 |
+
>>> from sympy import MatrixSymbol
|
481 |
+
>>> from sympy.stats import density, MatrixNormal
|
482 |
+
>>> M = MatrixNormal('M', [[1, 2]], [1], [[1, 0], [0, 1]])
|
483 |
+
>>> X = MatrixSymbol('X', 1, 2)
|
484 |
+
>>> density(M)(X).doit()
|
485 |
+
exp(-Trace((Matrix([
|
486 |
+
[-1],
|
487 |
+
[-2]]) + X.T)*(Matrix([[-1, -2]]) + X))/2)/(2*pi)
|
488 |
+
>>> density(M)([[3, 4]]).doit()
|
489 |
+
exp(-4)/(2*pi)
|
490 |
+
|
491 |
+
References
|
492 |
+
==========
|
493 |
+
|
494 |
+
.. [1] https://en.wikipedia.org/wiki/Matrix_normal_distribution
|
495 |
+
|
496 |
+
"""
|
497 |
+
if isinstance(location_matrix, list):
|
498 |
+
location_matrix = ImmutableMatrix(location_matrix)
|
499 |
+
if isinstance(scale_matrix_1, list):
|
500 |
+
scale_matrix_1 = ImmutableMatrix(scale_matrix_1)
|
501 |
+
if isinstance(scale_matrix_2, list):
|
502 |
+
scale_matrix_2 = ImmutableMatrix(scale_matrix_2)
|
503 |
+
args = (location_matrix, scale_matrix_1, scale_matrix_2)
|
504 |
+
return rv(symbol, MatrixNormalDistribution, args)
|
505 |
+
|
506 |
+
#-------------------------------------------------------------------------------
|
507 |
+
# Matrix Student's T distribution ---------------------------------------------------
|
508 |
+
|
509 |
+
class MatrixStudentTDistribution(MatrixDistribution):
|
510 |
+
|
511 |
+
_argnames = ('nu', 'location_matrix', 'scale_matrix_1', 'scale_matrix_2')
|
512 |
+
|
513 |
+
@staticmethod
|
514 |
+
def check(nu, location_matrix, scale_matrix_1, scale_matrix_2):
|
515 |
+
if not isinstance(scale_matrix_1, MatrixSymbol):
|
516 |
+
_value_check(scale_matrix_1.is_positive_definite != False, "The shape "
|
517 |
+
"matrix must be positive definite.")
|
518 |
+
if not isinstance(scale_matrix_2, MatrixSymbol):
|
519 |
+
_value_check(scale_matrix_2.is_positive_definite != False, "The shape "
|
520 |
+
"matrix must be positive definite.")
|
521 |
+
_value_check(scale_matrix_1.is_square != False, "Scale matrix 1 should be "
|
522 |
+
"be square matrix")
|
523 |
+
_value_check(scale_matrix_2.is_square != False, "Scale matrix 2 should be "
|
524 |
+
"be square matrix")
|
525 |
+
n = location_matrix.shape[0]
|
526 |
+
p = location_matrix.shape[1]
|
527 |
+
_value_check(scale_matrix_1.shape[0] == p, "Scale matrix 1 should be"
|
528 |
+
" of shape %s x %s" % (str(p), str(p)))
|
529 |
+
_value_check(scale_matrix_2.shape[0] == n, "Scale matrix 2 should be"
|
530 |
+
" of shape %s x %s" % (str(n), str(n)))
|
531 |
+
_value_check(nu.is_positive != False, "Degrees of freedom must be positive")
|
532 |
+
|
533 |
+
@property
|
534 |
+
def set(self):
|
535 |
+
n, p = self.location_matrix.shape
|
536 |
+
return MatrixSet(n, p, S.Reals)
|
537 |
+
|
538 |
+
@property
|
539 |
+
def dimension(self):
|
540 |
+
return self.location_matrix.shape
|
541 |
+
|
542 |
+
def pdf(self, x):
|
543 |
+
from sympy.matrices.dense import eye
|
544 |
+
if isinstance(x, list):
|
545 |
+
x = ImmutableMatrix(x)
|
546 |
+
if not isinstance(x, (MatrixBase, MatrixSymbol)):
|
547 |
+
raise ValueError("%s should be an isinstance of Matrix "
|
548 |
+
"or MatrixSymbol" % str(x))
|
549 |
+
nu, M, Omega, Sigma = self.nu, self.location_matrix, self.scale_matrix_1, self.scale_matrix_2
|
550 |
+
n, p = M.shape
|
551 |
+
|
552 |
+
K = multigamma((nu + n + p - 1)/2, p) * Determinant(Omega)**(-n/2) * Determinant(Sigma)**(-p/2) \
|
553 |
+
/ ((pi)**(n*p/2) * multigamma((nu + p - 1)/2, p))
|
554 |
+
return K * (Determinant(eye(n) + Inverse(Sigma)*(x - M)*Inverse(Omega)*Transpose(x - M))) \
|
555 |
+
**(-(nu + n + p -1)/2)
|
556 |
+
|
557 |
+
|
558 |
+
|
559 |
+
def MatrixStudentT(symbol, nu, location_matrix, scale_matrix_1, scale_matrix_2):
|
560 |
+
"""
|
561 |
+
Creates a random variable with Matrix Gamma Distribution.
|
562 |
+
|
563 |
+
The density of the said distribution can be found at [1].
|
564 |
+
|
565 |
+
Parameters
|
566 |
+
==========
|
567 |
+
|
568 |
+
nu: Positive Real number
|
569 |
+
degrees of freedom
|
570 |
+
location_matrix: Positive definite real square matrix
|
571 |
+
Location Matrix of shape ``n x p``
|
572 |
+
scale_matrix_1: Positive definite real square matrix
|
573 |
+
Scale Matrix of shape ``p x p``
|
574 |
+
scale_matrix_2: Positive definite real square matrix
|
575 |
+
Scale Matrix of shape ``n x n``
|
576 |
+
|
577 |
+
Returns
|
578 |
+
=======
|
579 |
+
|
580 |
+
RandomSymbol
|
581 |
+
|
582 |
+
Examples
|
583 |
+
========
|
584 |
+
|
585 |
+
>>> from sympy import MatrixSymbol,symbols
|
586 |
+
>>> from sympy.stats import density, MatrixStudentT
|
587 |
+
>>> v = symbols('v',positive=True)
|
588 |
+
>>> M = MatrixStudentT('M', v, [[1, 2]], [[1, 0], [0, 1]], [1])
|
589 |
+
>>> X = MatrixSymbol('X', 1, 2)
|
590 |
+
>>> density(M)(X)
|
591 |
+
gamma(v/2 + 1)*Determinant((Matrix([[-1, -2]]) + X)*(Matrix([
|
592 |
+
[-1],
|
593 |
+
[-2]]) + X.T) + Matrix([[1]]))**(-v/2 - 1)/(pi**1.0*gamma(v/2)*Determinant(Matrix([[1]]))**1.0*Determinant(Matrix([
|
594 |
+
[1, 0],
|
595 |
+
[0, 1]]))**0.5)
|
596 |
+
|
597 |
+
References
|
598 |
+
==========
|
599 |
+
|
600 |
+
.. [1] https://en.wikipedia.org/wiki/Matrix_t-distribution
|
601 |
+
|
602 |
+
"""
|
603 |
+
if isinstance(location_matrix, list):
|
604 |
+
location_matrix = ImmutableMatrix(location_matrix)
|
605 |
+
if isinstance(scale_matrix_1, list):
|
606 |
+
scale_matrix_1 = ImmutableMatrix(scale_matrix_1)
|
607 |
+
if isinstance(scale_matrix_2, list):
|
608 |
+
scale_matrix_2 = ImmutableMatrix(scale_matrix_2)
|
609 |
+
args = (nu, location_matrix, scale_matrix_1, scale_matrix_2)
|
610 |
+
return rv(symbol, MatrixStudentTDistribution, args)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/random_matrix.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.basic import Basic
|
2 |
+
from sympy.stats.rv import PSpace, _symbol_converter, RandomMatrixSymbol
|
3 |
+
|
4 |
+
class RandomMatrixPSpace(PSpace):
|
5 |
+
"""
|
6 |
+
Represents probability space for
|
7 |
+
random matrices. It contains the mechanics
|
8 |
+
for handling the API calls for random matrices.
|
9 |
+
"""
|
10 |
+
def __new__(cls, sym, model=None):
|
11 |
+
sym = _symbol_converter(sym)
|
12 |
+
if model:
|
13 |
+
return Basic.__new__(cls, sym, model)
|
14 |
+
else:
|
15 |
+
return Basic.__new__(cls, sym)
|
16 |
+
|
17 |
+
@property
|
18 |
+
def model(self):
|
19 |
+
try:
|
20 |
+
return self.args[1]
|
21 |
+
except IndexError:
|
22 |
+
return None
|
23 |
+
|
24 |
+
def compute_density(self, expr, *args):
|
25 |
+
rms = expr.atoms(RandomMatrixSymbol)
|
26 |
+
if len(rms) > 2 or (not isinstance(expr, RandomMatrixSymbol)):
|
27 |
+
raise NotImplementedError("Currently, no algorithm has been "
|
28 |
+
"implemented to handle general expressions containing "
|
29 |
+
"multiple random matrices.")
|
30 |
+
return self.model.density(expr)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/random_matrix_models.py
ADDED
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.concrete.products import Product
|
2 |
+
from sympy.concrete.summations import Sum
|
3 |
+
from sympy.core.basic import Basic
|
4 |
+
from sympy.core.function import Lambda
|
5 |
+
from sympy.core.numbers import (I, pi)
|
6 |
+
from sympy.core.singleton import S
|
7 |
+
from sympy.core.symbol import Dummy
|
8 |
+
from sympy.functions.elementary.complexes import Abs
|
9 |
+
from sympy.functions.elementary.exponential import exp
|
10 |
+
from sympy.functions.special.gamma_functions import gamma
|
11 |
+
from sympy.integrals.integrals import Integral
|
12 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
13 |
+
from sympy.matrices.expressions.trace import Trace
|
14 |
+
from sympy.tensor.indexed import IndexedBase
|
15 |
+
from sympy.core.sympify import _sympify
|
16 |
+
from sympy.stats.rv import _symbol_converter, Density, RandomMatrixSymbol, is_random
|
17 |
+
from sympy.stats.joint_rv_types import JointDistributionHandmade
|
18 |
+
from sympy.stats.random_matrix import RandomMatrixPSpace
|
19 |
+
from sympy.tensor.array import ArrayComprehension
|
20 |
+
|
21 |
+
__all__ = [
|
22 |
+
'CircularEnsemble',
|
23 |
+
'CircularUnitaryEnsemble',
|
24 |
+
'CircularOrthogonalEnsemble',
|
25 |
+
'CircularSymplecticEnsemble',
|
26 |
+
'GaussianEnsemble',
|
27 |
+
'GaussianUnitaryEnsemble',
|
28 |
+
'GaussianOrthogonalEnsemble',
|
29 |
+
'GaussianSymplecticEnsemble',
|
30 |
+
'joint_eigen_distribution',
|
31 |
+
'JointEigenDistribution',
|
32 |
+
'level_spacing_distribution'
|
33 |
+
]
|
34 |
+
|
35 |
+
@is_random.register(RandomMatrixSymbol)
|
36 |
+
def _(x):
|
37 |
+
return True
|
38 |
+
|
39 |
+
|
40 |
+
class RandomMatrixEnsembleModel(Basic):
|
41 |
+
"""
|
42 |
+
Base class for random matrix ensembles.
|
43 |
+
It acts as an umbrella and contains
|
44 |
+
the methods common to all the ensembles
|
45 |
+
defined in sympy.stats.random_matrix_models.
|
46 |
+
"""
|
47 |
+
def __new__(cls, sym, dim=None):
|
48 |
+
sym, dim = _symbol_converter(sym), _sympify(dim)
|
49 |
+
if dim.is_integer == False:
|
50 |
+
raise ValueError("Dimension of the random matrices must be "
|
51 |
+
"integers, received %s instead."%(dim))
|
52 |
+
return Basic.__new__(cls, sym, dim)
|
53 |
+
|
54 |
+
symbol = property(lambda self: self.args[0])
|
55 |
+
dimension = property(lambda self: self.args[1])
|
56 |
+
|
57 |
+
def density(self, expr):
|
58 |
+
return Density(expr)
|
59 |
+
|
60 |
+
def __call__(self, expr):
|
61 |
+
return self.density(expr)
|
62 |
+
|
63 |
+
class GaussianEnsembleModel(RandomMatrixEnsembleModel):
|
64 |
+
"""
|
65 |
+
Abstract class for Gaussian ensembles.
|
66 |
+
Contains the properties common to all the
|
67 |
+
gaussian ensembles.
|
68 |
+
|
69 |
+
References
|
70 |
+
==========
|
71 |
+
|
72 |
+
.. [1] https://en.wikipedia.org/wiki/Random_matrix#Gaussian_ensembles
|
73 |
+
.. [2] https://arxiv.org/pdf/1712.07903.pdf
|
74 |
+
"""
|
75 |
+
def _compute_normalization_constant(self, beta, n):
|
76 |
+
"""
|
77 |
+
Helper function for computing normalization
|
78 |
+
constant for joint probability density of eigen
|
79 |
+
values of Gaussian ensembles.
|
80 |
+
|
81 |
+
References
|
82 |
+
==========
|
83 |
+
|
84 |
+
.. [1] https://en.wikipedia.org/wiki/Selberg_integral#Mehta's_integral
|
85 |
+
"""
|
86 |
+
n = S(n)
|
87 |
+
prod_term = lambda j: gamma(1 + beta*S(j)/2)/gamma(S.One + beta/S(2))
|
88 |
+
j = Dummy('j', integer=True, positive=True)
|
89 |
+
term1 = Product(prod_term(j), (j, 1, n)).doit()
|
90 |
+
term2 = (2/(beta*n))**(beta*n*(n - 1)/4 + n/2)
|
91 |
+
term3 = (2*pi)**(n/2)
|
92 |
+
return term1 * term2 * term3
|
93 |
+
|
94 |
+
def _compute_joint_eigen_distribution(self, beta):
|
95 |
+
"""
|
96 |
+
Helper function for computing the joint
|
97 |
+
probability distribution of eigen values
|
98 |
+
of the random matrix.
|
99 |
+
"""
|
100 |
+
n = self.dimension
|
101 |
+
Zbn = self._compute_normalization_constant(beta, n)
|
102 |
+
l = IndexedBase('l')
|
103 |
+
i = Dummy('i', integer=True, positive=True)
|
104 |
+
j = Dummy('j', integer=True, positive=True)
|
105 |
+
k = Dummy('k', integer=True, positive=True)
|
106 |
+
term1 = exp((-S(n)/2) * Sum(l[k]**2, (k, 1, n)).doit())
|
107 |
+
sub_term = Lambda(i, Product(Abs(l[j] - l[i])**beta, (j, i + 1, n)))
|
108 |
+
term2 = Product(sub_term(i).doit(), (i, 1, n - 1)).doit()
|
109 |
+
syms = ArrayComprehension(l[k], (k, 1, n)).doit()
|
110 |
+
return Lambda(tuple(syms), (term1 * term2)/Zbn)
|
111 |
+
|
112 |
+
class GaussianUnitaryEnsembleModel(GaussianEnsembleModel):
|
113 |
+
@property
|
114 |
+
def normalization_constant(self):
|
115 |
+
n = self.dimension
|
116 |
+
return 2**(S(n)/2) * pi**(S(n**2)/2)
|
117 |
+
|
118 |
+
def density(self, expr):
|
119 |
+
n, ZGUE = self.dimension, self.normalization_constant
|
120 |
+
h_pspace = RandomMatrixPSpace('P', model=self)
|
121 |
+
H = RandomMatrixSymbol('H', n, n, pspace=h_pspace)
|
122 |
+
return Lambda(H, exp(-S(n)/2 * Trace(H**2))/ZGUE)(expr)
|
123 |
+
|
124 |
+
def joint_eigen_distribution(self):
|
125 |
+
return self._compute_joint_eigen_distribution(S(2))
|
126 |
+
|
127 |
+
def level_spacing_distribution(self):
|
128 |
+
s = Dummy('s')
|
129 |
+
f = (32/pi**2)*(s**2)*exp((-4/pi)*s**2)
|
130 |
+
return Lambda(s, f)
|
131 |
+
|
132 |
+
class GaussianOrthogonalEnsembleModel(GaussianEnsembleModel):
|
133 |
+
@property
|
134 |
+
def normalization_constant(self):
|
135 |
+
n = self.dimension
|
136 |
+
_H = MatrixSymbol('_H', n, n)
|
137 |
+
return Integral(exp(-S(n)/4 * Trace(_H**2)))
|
138 |
+
|
139 |
+
def density(self, expr):
|
140 |
+
n, ZGOE = self.dimension, self.normalization_constant
|
141 |
+
h_pspace = RandomMatrixPSpace('P', model=self)
|
142 |
+
H = RandomMatrixSymbol('H', n, n, pspace=h_pspace)
|
143 |
+
return Lambda(H, exp(-S(n)/4 * Trace(H**2))/ZGOE)(expr)
|
144 |
+
|
145 |
+
def joint_eigen_distribution(self):
|
146 |
+
return self._compute_joint_eigen_distribution(S.One)
|
147 |
+
|
148 |
+
def level_spacing_distribution(self):
|
149 |
+
s = Dummy('s')
|
150 |
+
f = (pi/2)*s*exp((-pi/4)*s**2)
|
151 |
+
return Lambda(s, f)
|
152 |
+
|
153 |
+
class GaussianSymplecticEnsembleModel(GaussianEnsembleModel):
|
154 |
+
@property
|
155 |
+
def normalization_constant(self):
|
156 |
+
n = self.dimension
|
157 |
+
_H = MatrixSymbol('_H', n, n)
|
158 |
+
return Integral(exp(-S(n) * Trace(_H**2)))
|
159 |
+
|
160 |
+
def density(self, expr):
|
161 |
+
n, ZGSE = self.dimension, self.normalization_constant
|
162 |
+
h_pspace = RandomMatrixPSpace('P', model=self)
|
163 |
+
H = RandomMatrixSymbol('H', n, n, pspace=h_pspace)
|
164 |
+
return Lambda(H, exp(-S(n) * Trace(H**2))/ZGSE)(expr)
|
165 |
+
|
166 |
+
def joint_eigen_distribution(self):
|
167 |
+
return self._compute_joint_eigen_distribution(S(4))
|
168 |
+
|
169 |
+
def level_spacing_distribution(self):
|
170 |
+
s = Dummy('s')
|
171 |
+
f = ((S(2)**18)/((S(3)**6)*(pi**3)))*(s**4)*exp((-64/(9*pi))*s**2)
|
172 |
+
return Lambda(s, f)
|
173 |
+
|
174 |
+
def GaussianEnsemble(sym, dim):
|
175 |
+
sym, dim = _symbol_converter(sym), _sympify(dim)
|
176 |
+
model = GaussianEnsembleModel(sym, dim)
|
177 |
+
rmp = RandomMatrixPSpace(sym, model=model)
|
178 |
+
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
|
179 |
+
|
180 |
+
def GaussianUnitaryEnsemble(sym, dim):
|
181 |
+
"""
|
182 |
+
Represents Gaussian Unitary Ensembles.
|
183 |
+
|
184 |
+
Examples
|
185 |
+
========
|
186 |
+
|
187 |
+
>>> from sympy.stats import GaussianUnitaryEnsemble as GUE, density
|
188 |
+
>>> from sympy import MatrixSymbol
|
189 |
+
>>> G = GUE('U', 2)
|
190 |
+
>>> X = MatrixSymbol('X', 2, 2)
|
191 |
+
>>> density(G)(X)
|
192 |
+
exp(-Trace(X**2))/(2*pi**2)
|
193 |
+
"""
|
194 |
+
sym, dim = _symbol_converter(sym), _sympify(dim)
|
195 |
+
model = GaussianUnitaryEnsembleModel(sym, dim)
|
196 |
+
rmp = RandomMatrixPSpace(sym, model=model)
|
197 |
+
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
|
198 |
+
|
199 |
+
def GaussianOrthogonalEnsemble(sym, dim):
|
200 |
+
"""
|
201 |
+
Represents Gaussian Orthogonal Ensembles.
|
202 |
+
|
203 |
+
Examples
|
204 |
+
========
|
205 |
+
|
206 |
+
>>> from sympy.stats import GaussianOrthogonalEnsemble as GOE, density
|
207 |
+
>>> from sympy import MatrixSymbol
|
208 |
+
>>> G = GOE('U', 2)
|
209 |
+
>>> X = MatrixSymbol('X', 2, 2)
|
210 |
+
>>> density(G)(X)
|
211 |
+
exp(-Trace(X**2)/2)/Integral(exp(-Trace(_H**2)/2), _H)
|
212 |
+
"""
|
213 |
+
sym, dim = _symbol_converter(sym), _sympify(dim)
|
214 |
+
model = GaussianOrthogonalEnsembleModel(sym, dim)
|
215 |
+
rmp = RandomMatrixPSpace(sym, model=model)
|
216 |
+
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
|
217 |
+
|
218 |
+
def GaussianSymplecticEnsemble(sym, dim):
|
219 |
+
"""
|
220 |
+
Represents Gaussian Symplectic Ensembles.
|
221 |
+
|
222 |
+
Examples
|
223 |
+
========
|
224 |
+
|
225 |
+
>>> from sympy.stats import GaussianSymplecticEnsemble as GSE, density
|
226 |
+
>>> from sympy import MatrixSymbol
|
227 |
+
>>> G = GSE('U', 2)
|
228 |
+
>>> X = MatrixSymbol('X', 2, 2)
|
229 |
+
>>> density(G)(X)
|
230 |
+
exp(-2*Trace(X**2))/Integral(exp(-2*Trace(_H**2)), _H)
|
231 |
+
"""
|
232 |
+
sym, dim = _symbol_converter(sym), _sympify(dim)
|
233 |
+
model = GaussianSymplecticEnsembleModel(sym, dim)
|
234 |
+
rmp = RandomMatrixPSpace(sym, model=model)
|
235 |
+
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
|
236 |
+
|
237 |
+
class CircularEnsembleModel(RandomMatrixEnsembleModel):
|
238 |
+
"""
|
239 |
+
Abstract class for Circular ensembles.
|
240 |
+
Contains the properties and methods
|
241 |
+
common to all the circular ensembles.
|
242 |
+
|
243 |
+
References
|
244 |
+
==========
|
245 |
+
|
246 |
+
.. [1] https://en.wikipedia.org/wiki/Circular_ensemble
|
247 |
+
"""
|
248 |
+
def density(self, expr):
|
249 |
+
# TODO : Add support for Lie groups(as extensions of sympy.diffgeom)
|
250 |
+
# and define measures on them
|
251 |
+
raise NotImplementedError("Support for Haar measure hasn't been "
|
252 |
+
"implemented yet, therefore the density of "
|
253 |
+
"%s cannot be computed."%(self))
|
254 |
+
|
255 |
+
def _compute_joint_eigen_distribution(self, beta):
|
256 |
+
"""
|
257 |
+
Helper function to compute the joint distribution of phases
|
258 |
+
of the complex eigen values of matrices belonging to any
|
259 |
+
circular ensembles.
|
260 |
+
"""
|
261 |
+
n = self.dimension
|
262 |
+
Zbn = ((2*pi)**n)*(gamma(beta*n/2 + 1)/S(gamma(beta/2 + 1))**n)
|
263 |
+
t = IndexedBase('t')
|
264 |
+
i, j, k = (Dummy('i', integer=True), Dummy('j', integer=True),
|
265 |
+
Dummy('k', integer=True))
|
266 |
+
syms = ArrayComprehension(t[i], (i, 1, n)).doit()
|
267 |
+
f = Product(Product(Abs(exp(I*t[k]) - exp(I*t[j]))**beta, (j, k + 1, n)).doit(),
|
268 |
+
(k, 1, n - 1)).doit()
|
269 |
+
return Lambda(tuple(syms), f/Zbn)
|
270 |
+
|
271 |
+
class CircularUnitaryEnsembleModel(CircularEnsembleModel):
|
272 |
+
def joint_eigen_distribution(self):
|
273 |
+
return self._compute_joint_eigen_distribution(S(2))
|
274 |
+
|
275 |
+
class CircularOrthogonalEnsembleModel(CircularEnsembleModel):
|
276 |
+
def joint_eigen_distribution(self):
|
277 |
+
return self._compute_joint_eigen_distribution(S.One)
|
278 |
+
|
279 |
+
class CircularSymplecticEnsembleModel(CircularEnsembleModel):
|
280 |
+
def joint_eigen_distribution(self):
|
281 |
+
return self._compute_joint_eigen_distribution(S(4))
|
282 |
+
|
283 |
+
def CircularEnsemble(sym, dim):
|
284 |
+
sym, dim = _symbol_converter(sym), _sympify(dim)
|
285 |
+
model = CircularEnsembleModel(sym, dim)
|
286 |
+
rmp = RandomMatrixPSpace(sym, model=model)
|
287 |
+
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
|
288 |
+
|
289 |
+
def CircularUnitaryEnsemble(sym, dim):
|
290 |
+
"""
|
291 |
+
Represents Circular Unitary Ensembles.
|
292 |
+
|
293 |
+
Examples
|
294 |
+
========
|
295 |
+
|
296 |
+
>>> from sympy.stats import CircularUnitaryEnsemble as CUE
|
297 |
+
>>> from sympy.stats import joint_eigen_distribution
|
298 |
+
>>> C = CUE('U', 1)
|
299 |
+
>>> joint_eigen_distribution(C)
|
300 |
+
Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k]))**2, (_j, _k + 1, 1), (_k, 1, 0))/(2*pi))
|
301 |
+
|
302 |
+
Note
|
303 |
+
====
|
304 |
+
|
305 |
+
As can be seen above in the example, density of CiruclarUnitaryEnsemble
|
306 |
+
is not evaluated because the exact definition is based on haar measure of
|
307 |
+
unitary group which is not unique.
|
308 |
+
"""
|
309 |
+
sym, dim = _symbol_converter(sym), _sympify(dim)
|
310 |
+
model = CircularUnitaryEnsembleModel(sym, dim)
|
311 |
+
rmp = RandomMatrixPSpace(sym, model=model)
|
312 |
+
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
|
313 |
+
|
314 |
+
def CircularOrthogonalEnsemble(sym, dim):
|
315 |
+
"""
|
316 |
+
Represents Circular Orthogonal Ensembles.
|
317 |
+
|
318 |
+
Examples
|
319 |
+
========
|
320 |
+
|
321 |
+
>>> from sympy.stats import CircularOrthogonalEnsemble as COE
|
322 |
+
>>> from sympy.stats import joint_eigen_distribution
|
323 |
+
>>> C = COE('O', 1)
|
324 |
+
>>> joint_eigen_distribution(C)
|
325 |
+
Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k])), (_j, _k + 1, 1), (_k, 1, 0))/(2*pi))
|
326 |
+
|
327 |
+
Note
|
328 |
+
====
|
329 |
+
|
330 |
+
As can be seen above in the example, density of CiruclarOrthogonalEnsemble
|
331 |
+
is not evaluated because the exact definition is based on haar measure of
|
332 |
+
unitary group which is not unique.
|
333 |
+
"""
|
334 |
+
sym, dim = _symbol_converter(sym), _sympify(dim)
|
335 |
+
model = CircularOrthogonalEnsembleModel(sym, dim)
|
336 |
+
rmp = RandomMatrixPSpace(sym, model=model)
|
337 |
+
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
|
338 |
+
|
339 |
+
def CircularSymplecticEnsemble(sym, dim):
|
340 |
+
"""
|
341 |
+
Represents Circular Symplectic Ensembles.
|
342 |
+
|
343 |
+
Examples
|
344 |
+
========
|
345 |
+
|
346 |
+
>>> from sympy.stats import CircularSymplecticEnsemble as CSE
|
347 |
+
>>> from sympy.stats import joint_eigen_distribution
|
348 |
+
>>> C = CSE('S', 1)
|
349 |
+
>>> joint_eigen_distribution(C)
|
350 |
+
Lambda(t[1], Product(Abs(exp(I*t[_j]) - exp(I*t[_k]))**4, (_j, _k + 1, 1), (_k, 1, 0))/(2*pi))
|
351 |
+
|
352 |
+
Note
|
353 |
+
====
|
354 |
+
|
355 |
+
As can be seen above in the example, density of CiruclarSymplecticEnsemble
|
356 |
+
is not evaluated because the exact definition is based on haar measure of
|
357 |
+
unitary group which is not unique.
|
358 |
+
"""
|
359 |
+
sym, dim = _symbol_converter(sym), _sympify(dim)
|
360 |
+
model = CircularSymplecticEnsembleModel(sym, dim)
|
361 |
+
rmp = RandomMatrixPSpace(sym, model=model)
|
362 |
+
return RandomMatrixSymbol(sym, dim, dim, pspace=rmp)
|
363 |
+
|
364 |
+
def joint_eigen_distribution(mat):
|
365 |
+
"""
|
366 |
+
For obtaining joint probability distribution
|
367 |
+
of eigen values of random matrix.
|
368 |
+
|
369 |
+
Parameters
|
370 |
+
==========
|
371 |
+
|
372 |
+
mat: RandomMatrixSymbol
|
373 |
+
The matrix symbol whose eigen values are to be considered.
|
374 |
+
|
375 |
+
Returns
|
376 |
+
=======
|
377 |
+
|
378 |
+
Lambda
|
379 |
+
|
380 |
+
Examples
|
381 |
+
========
|
382 |
+
|
383 |
+
>>> from sympy.stats import GaussianUnitaryEnsemble as GUE
|
384 |
+
>>> from sympy.stats import joint_eigen_distribution
|
385 |
+
>>> U = GUE('U', 2)
|
386 |
+
>>> joint_eigen_distribution(U)
|
387 |
+
Lambda((l[1], l[2]), exp(-l[1]**2 - l[2]**2)*Product(Abs(l[_i] - l[_j])**2, (_j, _i + 1, 2), (_i, 1, 1))/pi)
|
388 |
+
"""
|
389 |
+
if not isinstance(mat, RandomMatrixSymbol):
|
390 |
+
raise ValueError("%s is not of type, RandomMatrixSymbol."%(mat))
|
391 |
+
return mat.pspace.model.joint_eigen_distribution()
|
392 |
+
|
393 |
+
def JointEigenDistribution(mat):
|
394 |
+
"""
|
395 |
+
Creates joint distribution of eigen values of matrices with random
|
396 |
+
expressions.
|
397 |
+
|
398 |
+
Parameters
|
399 |
+
==========
|
400 |
+
|
401 |
+
mat: Matrix
|
402 |
+
The matrix under consideration.
|
403 |
+
|
404 |
+
Returns
|
405 |
+
=======
|
406 |
+
|
407 |
+
JointDistributionHandmade
|
408 |
+
|
409 |
+
Examples
|
410 |
+
========
|
411 |
+
|
412 |
+
>>> from sympy.stats import Normal, JointEigenDistribution
|
413 |
+
>>> from sympy import Matrix
|
414 |
+
>>> A = [[Normal('A00', 0, 1), Normal('A01', 0, 1)],
|
415 |
+
... [Normal('A10', 0, 1), Normal('A11', 0, 1)]]
|
416 |
+
>>> JointEigenDistribution(Matrix(A))
|
417 |
+
JointDistributionHandmade(-sqrt(A00**2 - 2*A00*A11 + 4*A01*A10 + A11**2)/2
|
418 |
+
+ A00/2 + A11/2, sqrt(A00**2 - 2*A00*A11 + 4*A01*A10 + A11**2)/2 + A00/2 + A11/2)
|
419 |
+
|
420 |
+
"""
|
421 |
+
eigenvals = mat.eigenvals(multiple=True)
|
422 |
+
if not all(is_random(eigenval) for eigenval in set(eigenvals)):
|
423 |
+
raise ValueError("Eigen values do not have any random expression, "
|
424 |
+
"joint distribution cannot be generated.")
|
425 |
+
return JointDistributionHandmade(*eigenvals)
|
426 |
+
|
427 |
+
def level_spacing_distribution(mat):
|
428 |
+
"""
|
429 |
+
For obtaining distribution of level spacings.
|
430 |
+
|
431 |
+
Parameters
|
432 |
+
==========
|
433 |
+
|
434 |
+
mat: RandomMatrixSymbol
|
435 |
+
The random matrix symbol whose eigen values are
|
436 |
+
to be considered for finding the level spacings.
|
437 |
+
|
438 |
+
Returns
|
439 |
+
=======
|
440 |
+
|
441 |
+
Lambda
|
442 |
+
|
443 |
+
Examples
|
444 |
+
========
|
445 |
+
|
446 |
+
>>> from sympy.stats import GaussianUnitaryEnsemble as GUE
|
447 |
+
>>> from sympy.stats import level_spacing_distribution
|
448 |
+
>>> U = GUE('U', 2)
|
449 |
+
>>> level_spacing_distribution(U)
|
450 |
+
Lambda(_s, 32*_s**2*exp(-4*_s**2/pi)/pi**2)
|
451 |
+
|
452 |
+
References
|
453 |
+
==========
|
454 |
+
|
455 |
+
.. [1] https://en.wikipedia.org/wiki/Random_matrix#Distribution_of_level_spacings
|
456 |
+
"""
|
457 |
+
return mat.pspace.model.level_spacing_distribution()
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/rv.py
ADDED
@@ -0,0 +1,1792 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Main Random Variables Module
|
3 |
+
|
4 |
+
Defines abstract random variable type.
|
5 |
+
Contains interfaces for probability space object (PSpace) as well as standard
|
6 |
+
operators, P, E, sample, density, where, quantile
|
7 |
+
|
8 |
+
See Also
|
9 |
+
========
|
10 |
+
|
11 |
+
sympy.stats.crv
|
12 |
+
sympy.stats.frv
|
13 |
+
sympy.stats.rv_interface
|
14 |
+
"""
|
15 |
+
|
16 |
+
from __future__ import annotations
|
17 |
+
from functools import singledispatch
|
18 |
+
from math import prod
|
19 |
+
|
20 |
+
from sympy.core.add import Add
|
21 |
+
from sympy.core.basic import Basic
|
22 |
+
from sympy.core.containers import Tuple
|
23 |
+
from sympy.core.expr import Expr
|
24 |
+
from sympy.core.function import (Function, Lambda)
|
25 |
+
from sympy.core.logic import fuzzy_and
|
26 |
+
from sympy.core.mul import Mul
|
27 |
+
from sympy.core.relational import (Eq, Ne)
|
28 |
+
from sympy.core.singleton import S
|
29 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
30 |
+
from sympy.core.sympify import sympify
|
31 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
32 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
33 |
+
from sympy.logic.boolalg import (And, Or)
|
34 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
35 |
+
from sympy.tensor.indexed import Indexed
|
36 |
+
from sympy.utilities.lambdify import lambdify
|
37 |
+
from sympy.core.relational import Relational
|
38 |
+
from sympy.core.sympify import _sympify
|
39 |
+
from sympy.sets.sets import FiniteSet, ProductSet, Intersection
|
40 |
+
from sympy.solvers.solveset import solveset
|
41 |
+
from sympy.external import import_module
|
42 |
+
from sympy.utilities.decorator import doctest_depends_on
|
43 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
44 |
+
from sympy.utilities.iterables import iterable
|
45 |
+
|
46 |
+
|
47 |
+
x = Symbol('x')
|
48 |
+
|
49 |
+
@singledispatch
|
50 |
+
def is_random(x):
|
51 |
+
return False
|
52 |
+
|
53 |
+
@is_random.register(Basic)
|
54 |
+
def _(x):
|
55 |
+
atoms = x.free_symbols
|
56 |
+
return any(is_random(i) for i in atoms)
|
57 |
+
|
58 |
+
class RandomDomain(Basic):
|
59 |
+
"""
|
60 |
+
Represents a set of variables and the values which they can take.
|
61 |
+
|
62 |
+
See Also
|
63 |
+
========
|
64 |
+
|
65 |
+
sympy.stats.crv.ContinuousDomain
|
66 |
+
sympy.stats.frv.FiniteDomain
|
67 |
+
"""
|
68 |
+
|
69 |
+
is_ProductDomain = False
|
70 |
+
is_Finite = False
|
71 |
+
is_Continuous = False
|
72 |
+
is_Discrete = False
|
73 |
+
|
74 |
+
def __new__(cls, symbols, *args):
|
75 |
+
symbols = FiniteSet(*symbols)
|
76 |
+
return Basic.__new__(cls, symbols, *args)
|
77 |
+
|
78 |
+
@property
|
79 |
+
def symbols(self):
|
80 |
+
return self.args[0]
|
81 |
+
|
82 |
+
@property
|
83 |
+
def set(self):
|
84 |
+
return self.args[1]
|
85 |
+
|
86 |
+
def __contains__(self, other):
|
87 |
+
raise NotImplementedError()
|
88 |
+
|
89 |
+
def compute_expectation(self, expr):
|
90 |
+
raise NotImplementedError()
|
91 |
+
|
92 |
+
|
93 |
+
class SingleDomain(RandomDomain):
|
94 |
+
"""
|
95 |
+
A single variable and its domain.
|
96 |
+
|
97 |
+
See Also
|
98 |
+
========
|
99 |
+
|
100 |
+
sympy.stats.crv.SingleContinuousDomain
|
101 |
+
sympy.stats.frv.SingleFiniteDomain
|
102 |
+
"""
|
103 |
+
def __new__(cls, symbol, set):
|
104 |
+
assert symbol.is_Symbol
|
105 |
+
return Basic.__new__(cls, symbol, set)
|
106 |
+
|
107 |
+
@property
|
108 |
+
def symbol(self):
|
109 |
+
return self.args[0]
|
110 |
+
|
111 |
+
@property
|
112 |
+
def symbols(self):
|
113 |
+
return FiniteSet(self.symbol)
|
114 |
+
|
115 |
+
def __contains__(self, other):
|
116 |
+
if len(other) != 1:
|
117 |
+
return False
|
118 |
+
sym, val = tuple(other)[0]
|
119 |
+
return self.symbol == sym and val in self.set
|
120 |
+
|
121 |
+
|
122 |
+
class MatrixDomain(RandomDomain):
|
123 |
+
"""
|
124 |
+
A Random Matrix variable and its domain.
|
125 |
+
|
126 |
+
"""
|
127 |
+
def __new__(cls, symbol, set):
|
128 |
+
symbol, set = _symbol_converter(symbol), _sympify(set)
|
129 |
+
return Basic.__new__(cls, symbol, set)
|
130 |
+
|
131 |
+
@property
|
132 |
+
def symbol(self):
|
133 |
+
return self.args[0]
|
134 |
+
|
135 |
+
@property
|
136 |
+
def symbols(self):
|
137 |
+
return FiniteSet(self.symbol)
|
138 |
+
|
139 |
+
|
140 |
+
class ConditionalDomain(RandomDomain):
|
141 |
+
"""
|
142 |
+
A RandomDomain with an attached condition.
|
143 |
+
|
144 |
+
See Also
|
145 |
+
========
|
146 |
+
|
147 |
+
sympy.stats.crv.ConditionalContinuousDomain
|
148 |
+
sympy.stats.frv.ConditionalFiniteDomain
|
149 |
+
"""
|
150 |
+
def __new__(cls, fulldomain, condition):
|
151 |
+
condition = condition.xreplace({rs: rs.symbol
|
152 |
+
for rs in random_symbols(condition)})
|
153 |
+
return Basic.__new__(cls, fulldomain, condition)
|
154 |
+
|
155 |
+
@property
|
156 |
+
def symbols(self):
|
157 |
+
return self.fulldomain.symbols
|
158 |
+
|
159 |
+
@property
|
160 |
+
def fulldomain(self):
|
161 |
+
return self.args[0]
|
162 |
+
|
163 |
+
@property
|
164 |
+
def condition(self):
|
165 |
+
return self.args[1]
|
166 |
+
|
167 |
+
@property
|
168 |
+
def set(self):
|
169 |
+
raise NotImplementedError("Set of Conditional Domain not Implemented")
|
170 |
+
|
171 |
+
def as_boolean(self):
|
172 |
+
return And(self.fulldomain.as_boolean(), self.condition)
|
173 |
+
|
174 |
+
|
175 |
+
class PSpace(Basic):
|
176 |
+
"""
|
177 |
+
A Probability Space.
|
178 |
+
|
179 |
+
Explanation
|
180 |
+
===========
|
181 |
+
|
182 |
+
Probability Spaces encode processes that equal different values
|
183 |
+
probabilistically. These underly Random Symbols which occur in SymPy
|
184 |
+
expressions and contain the mechanics to evaluate statistical statements.
|
185 |
+
|
186 |
+
See Also
|
187 |
+
========
|
188 |
+
|
189 |
+
sympy.stats.crv.ContinuousPSpace
|
190 |
+
sympy.stats.frv.FinitePSpace
|
191 |
+
"""
|
192 |
+
|
193 |
+
is_Finite = None # type: bool
|
194 |
+
is_Continuous = None # type: bool
|
195 |
+
is_Discrete = None # type: bool
|
196 |
+
is_real = None # type: bool
|
197 |
+
|
198 |
+
@property
|
199 |
+
def domain(self):
|
200 |
+
return self.args[0]
|
201 |
+
|
202 |
+
@property
|
203 |
+
def density(self):
|
204 |
+
return self.args[1]
|
205 |
+
|
206 |
+
@property
|
207 |
+
def values(self):
|
208 |
+
return frozenset(RandomSymbol(sym, self) for sym in self.symbols)
|
209 |
+
|
210 |
+
@property
|
211 |
+
def symbols(self):
|
212 |
+
return self.domain.symbols
|
213 |
+
|
214 |
+
def where(self, condition):
|
215 |
+
raise NotImplementedError()
|
216 |
+
|
217 |
+
def compute_density(self, expr):
|
218 |
+
raise NotImplementedError()
|
219 |
+
|
220 |
+
def sample(self, size=(), library='scipy', seed=None):
|
221 |
+
raise NotImplementedError()
|
222 |
+
|
223 |
+
def probability(self, condition):
|
224 |
+
raise NotImplementedError()
|
225 |
+
|
226 |
+
def compute_expectation(self, expr):
|
227 |
+
raise NotImplementedError()
|
228 |
+
|
229 |
+
|
230 |
+
class SinglePSpace(PSpace):
|
231 |
+
"""
|
232 |
+
Represents the probabilities of a set of random events that can be
|
233 |
+
attributed to a single variable/symbol.
|
234 |
+
"""
|
235 |
+
def __new__(cls, s, distribution):
|
236 |
+
s = _symbol_converter(s)
|
237 |
+
return Basic.__new__(cls, s, distribution)
|
238 |
+
|
239 |
+
@property
|
240 |
+
def value(self):
|
241 |
+
return RandomSymbol(self.symbol, self)
|
242 |
+
|
243 |
+
@property
|
244 |
+
def symbol(self):
|
245 |
+
return self.args[0]
|
246 |
+
|
247 |
+
@property
|
248 |
+
def distribution(self):
|
249 |
+
return self.args[1]
|
250 |
+
|
251 |
+
@property
|
252 |
+
def pdf(self):
|
253 |
+
return self.distribution.pdf(self.symbol)
|
254 |
+
|
255 |
+
|
256 |
+
class RandomSymbol(Expr):
|
257 |
+
"""
|
258 |
+
Random Symbols represent ProbabilitySpaces in SymPy Expressions.
|
259 |
+
In principle they can take on any value that their symbol can take on
|
260 |
+
within the associated PSpace with probability determined by the PSpace
|
261 |
+
Density.
|
262 |
+
|
263 |
+
Explanation
|
264 |
+
===========
|
265 |
+
|
266 |
+
Random Symbols contain pspace and symbol properties.
|
267 |
+
The pspace property points to the represented Probability Space
|
268 |
+
The symbol is a standard SymPy Symbol that is used in that probability space
|
269 |
+
for example in defining a density.
|
270 |
+
|
271 |
+
You can form normal SymPy expressions using RandomSymbols and operate on
|
272 |
+
those expressions with the Functions
|
273 |
+
|
274 |
+
E - Expectation of a random expression
|
275 |
+
P - Probability of a condition
|
276 |
+
density - Probability Density of an expression
|
277 |
+
given - A new random expression (with new random symbols) given a condition
|
278 |
+
|
279 |
+
An object of the RandomSymbol type should almost never be created by the
|
280 |
+
user. They tend to be created instead by the PSpace class's value method.
|
281 |
+
Traditionally a user does not even do this but instead calls one of the
|
282 |
+
convenience functions Normal, Exponential, Coin, Die, FiniteRV, etc....
|
283 |
+
"""
|
284 |
+
|
285 |
+
def __new__(cls, symbol, pspace=None):
|
286 |
+
from sympy.stats.joint_rv import JointRandomSymbol
|
287 |
+
if pspace is None:
|
288 |
+
# Allow single arg, representing pspace == PSpace()
|
289 |
+
pspace = PSpace()
|
290 |
+
symbol = _symbol_converter(symbol)
|
291 |
+
if not isinstance(pspace, PSpace):
|
292 |
+
raise TypeError("pspace variable should be of type PSpace")
|
293 |
+
if cls == JointRandomSymbol and isinstance(pspace, SinglePSpace):
|
294 |
+
cls = RandomSymbol
|
295 |
+
return Basic.__new__(cls, symbol, pspace)
|
296 |
+
|
297 |
+
is_finite = True
|
298 |
+
is_symbol = True
|
299 |
+
is_Atom = True
|
300 |
+
|
301 |
+
_diff_wrt = True
|
302 |
+
|
303 |
+
pspace = property(lambda self: self.args[1])
|
304 |
+
symbol = property(lambda self: self.args[0])
|
305 |
+
name = property(lambda self: self.symbol.name)
|
306 |
+
|
307 |
+
def _eval_is_positive(self):
|
308 |
+
return self.symbol.is_positive
|
309 |
+
|
310 |
+
def _eval_is_integer(self):
|
311 |
+
return self.symbol.is_integer
|
312 |
+
|
313 |
+
def _eval_is_real(self):
|
314 |
+
return self.symbol.is_real or self.pspace.is_real
|
315 |
+
|
316 |
+
@property
|
317 |
+
def is_commutative(self):
|
318 |
+
return self.symbol.is_commutative
|
319 |
+
|
320 |
+
@property
|
321 |
+
def free_symbols(self):
|
322 |
+
return {self}
|
323 |
+
|
324 |
+
class RandomIndexedSymbol(RandomSymbol):
|
325 |
+
|
326 |
+
def __new__(cls, idx_obj, pspace=None):
|
327 |
+
if pspace is None:
|
328 |
+
# Allow single arg, representing pspace == PSpace()
|
329 |
+
pspace = PSpace()
|
330 |
+
if not isinstance(idx_obj, (Indexed, Function)):
|
331 |
+
raise TypeError("An Function or Indexed object is expected not %s"%(idx_obj))
|
332 |
+
return Basic.__new__(cls, idx_obj, pspace)
|
333 |
+
|
334 |
+
symbol = property(lambda self: self.args[0])
|
335 |
+
name = property(lambda self: str(self.args[0]))
|
336 |
+
|
337 |
+
@property
|
338 |
+
def key(self):
|
339 |
+
if isinstance(self.symbol, Indexed):
|
340 |
+
return self.symbol.args[1]
|
341 |
+
elif isinstance(self.symbol, Function):
|
342 |
+
return self.symbol.args[0]
|
343 |
+
|
344 |
+
@property
|
345 |
+
def free_symbols(self):
|
346 |
+
if self.key.free_symbols:
|
347 |
+
free_syms = self.key.free_symbols
|
348 |
+
free_syms.add(self)
|
349 |
+
return free_syms
|
350 |
+
return {self}
|
351 |
+
|
352 |
+
@property
|
353 |
+
def pspace(self):
|
354 |
+
return self.args[1]
|
355 |
+
|
356 |
+
class RandomMatrixSymbol(RandomSymbol, MatrixSymbol): # type: ignore
|
357 |
+
def __new__(cls, symbol, n, m, pspace=None):
|
358 |
+
n, m = _sympify(n), _sympify(m)
|
359 |
+
symbol = _symbol_converter(symbol)
|
360 |
+
if pspace is None:
|
361 |
+
# Allow single arg, representing pspace == PSpace()
|
362 |
+
pspace = PSpace()
|
363 |
+
return Basic.__new__(cls, symbol, n, m, pspace)
|
364 |
+
|
365 |
+
symbol = property(lambda self: self.args[0])
|
366 |
+
pspace = property(lambda self: self.args[3])
|
367 |
+
|
368 |
+
|
369 |
+
class ProductPSpace(PSpace):
|
370 |
+
"""
|
371 |
+
Abstract class for representing probability spaces with multiple random
|
372 |
+
variables.
|
373 |
+
|
374 |
+
See Also
|
375 |
+
========
|
376 |
+
|
377 |
+
sympy.stats.rv.IndependentProductPSpace
|
378 |
+
sympy.stats.joint_rv.JointPSpace
|
379 |
+
"""
|
380 |
+
pass
|
381 |
+
|
382 |
+
class IndependentProductPSpace(ProductPSpace):
|
383 |
+
"""
|
384 |
+
A probability space resulting from the merger of two independent probability
|
385 |
+
spaces.
|
386 |
+
|
387 |
+
Often created using the function, pspace.
|
388 |
+
"""
|
389 |
+
|
390 |
+
def __new__(cls, *spaces):
|
391 |
+
rs_space_dict = {}
|
392 |
+
for space in spaces:
|
393 |
+
for value in space.values:
|
394 |
+
rs_space_dict[value] = space
|
395 |
+
|
396 |
+
symbols = FiniteSet(*[val.symbol for val in rs_space_dict.keys()])
|
397 |
+
|
398 |
+
# Overlapping symbols
|
399 |
+
from sympy.stats.joint_rv import MarginalDistribution
|
400 |
+
from sympy.stats.compound_rv import CompoundDistribution
|
401 |
+
if len(symbols) < sum(len(space.symbols) for space in spaces if not
|
402 |
+
isinstance(space.distribution, (
|
403 |
+
CompoundDistribution, MarginalDistribution))):
|
404 |
+
raise ValueError("Overlapping Random Variables")
|
405 |
+
|
406 |
+
if all(space.is_Finite for space in spaces):
|
407 |
+
from sympy.stats.frv import ProductFinitePSpace
|
408 |
+
cls = ProductFinitePSpace
|
409 |
+
|
410 |
+
obj = Basic.__new__(cls, *FiniteSet(*spaces))
|
411 |
+
|
412 |
+
return obj
|
413 |
+
|
414 |
+
@property
|
415 |
+
def pdf(self):
|
416 |
+
p = Mul(*[space.pdf for space in self.spaces])
|
417 |
+
return p.subs({rv: rv.symbol for rv in self.values})
|
418 |
+
|
419 |
+
@property
|
420 |
+
def rs_space_dict(self):
|
421 |
+
d = {}
|
422 |
+
for space in self.spaces:
|
423 |
+
for value in space.values:
|
424 |
+
d[value] = space
|
425 |
+
return d
|
426 |
+
|
427 |
+
@property
|
428 |
+
def symbols(self):
|
429 |
+
return FiniteSet(*[val.symbol for val in self.rs_space_dict.keys()])
|
430 |
+
|
431 |
+
@property
|
432 |
+
def spaces(self):
|
433 |
+
return FiniteSet(*self.args)
|
434 |
+
|
435 |
+
@property
|
436 |
+
def values(self):
|
437 |
+
return sumsets(space.values for space in self.spaces)
|
438 |
+
|
439 |
+
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
|
440 |
+
rvs = rvs or self.values
|
441 |
+
rvs = frozenset(rvs)
|
442 |
+
for space in self.spaces:
|
443 |
+
expr = space.compute_expectation(expr, rvs & space.values, evaluate=False, **kwargs)
|
444 |
+
if evaluate and hasattr(expr, 'doit'):
|
445 |
+
return expr.doit(**kwargs)
|
446 |
+
return expr
|
447 |
+
|
448 |
+
@property
|
449 |
+
def domain(self):
|
450 |
+
return ProductDomain(*[space.domain for space in self.spaces])
|
451 |
+
|
452 |
+
@property
|
453 |
+
def density(self):
|
454 |
+
raise NotImplementedError("Density not available for ProductSpaces")
|
455 |
+
|
456 |
+
def sample(self, size=(), library='scipy', seed=None):
|
457 |
+
return {k: v for space in self.spaces
|
458 |
+
for k, v in space.sample(size=size, library=library, seed=seed).items()}
|
459 |
+
|
460 |
+
|
461 |
+
def probability(self, condition, **kwargs):
|
462 |
+
cond_inv = False
|
463 |
+
if isinstance(condition, Ne):
|
464 |
+
condition = Eq(condition.args[0], condition.args[1])
|
465 |
+
cond_inv = True
|
466 |
+
elif isinstance(condition, And): # they are independent
|
467 |
+
return Mul(*[self.probability(arg) for arg in condition.args])
|
468 |
+
elif isinstance(condition, Or): # they are independent
|
469 |
+
return Add(*[self.probability(arg) for arg in condition.args])
|
470 |
+
expr = condition.lhs - condition.rhs
|
471 |
+
rvs = random_symbols(expr)
|
472 |
+
dens = self.compute_density(expr)
|
473 |
+
if any(pspace(rv).is_Continuous for rv in rvs):
|
474 |
+
from sympy.stats.crv import SingleContinuousPSpace
|
475 |
+
from sympy.stats.crv_types import ContinuousDistributionHandmade
|
476 |
+
if expr in self.values:
|
477 |
+
# Marginalize all other random symbols out of the density
|
478 |
+
randomsymbols = tuple(set(self.values) - frozenset([expr]))
|
479 |
+
symbols = tuple(rs.symbol for rs in randomsymbols)
|
480 |
+
pdf = self.domain.integrate(self.pdf, symbols, **kwargs)
|
481 |
+
return Lambda(expr.symbol, pdf)
|
482 |
+
dens = ContinuousDistributionHandmade(dens)
|
483 |
+
z = Dummy('z', real=True)
|
484 |
+
space = SingleContinuousPSpace(z, dens)
|
485 |
+
result = space.probability(condition.__class__(space.value, 0))
|
486 |
+
else:
|
487 |
+
from sympy.stats.drv import SingleDiscretePSpace
|
488 |
+
from sympy.stats.drv_types import DiscreteDistributionHandmade
|
489 |
+
dens = DiscreteDistributionHandmade(dens)
|
490 |
+
z = Dummy('z', integer=True)
|
491 |
+
space = SingleDiscretePSpace(z, dens)
|
492 |
+
result = space.probability(condition.__class__(space.value, 0))
|
493 |
+
return result if not cond_inv else S.One - result
|
494 |
+
|
495 |
+
def compute_density(self, expr, **kwargs):
|
496 |
+
rvs = random_symbols(expr)
|
497 |
+
if any(pspace(rv).is_Continuous for rv in rvs):
|
498 |
+
z = Dummy('z', real=True)
|
499 |
+
expr = self.compute_expectation(DiracDelta(expr - z),
|
500 |
+
**kwargs)
|
501 |
+
else:
|
502 |
+
z = Dummy('z', integer=True)
|
503 |
+
expr = self.compute_expectation(KroneckerDelta(expr, z),
|
504 |
+
**kwargs)
|
505 |
+
return Lambda(z, expr)
|
506 |
+
|
507 |
+
def compute_cdf(self, expr, **kwargs):
|
508 |
+
raise ValueError("CDF not well defined on multivariate expressions")
|
509 |
+
|
510 |
+
def conditional_space(self, condition, normalize=True, **kwargs):
|
511 |
+
rvs = random_symbols(condition)
|
512 |
+
condition = condition.xreplace({rv: rv.symbol for rv in self.values})
|
513 |
+
pspaces = [pspace(rv) for rv in rvs]
|
514 |
+
if any(ps.is_Continuous for ps in pspaces):
|
515 |
+
from sympy.stats.crv import (ConditionalContinuousDomain,
|
516 |
+
ContinuousPSpace)
|
517 |
+
space = ContinuousPSpace
|
518 |
+
domain = ConditionalContinuousDomain(self.domain, condition)
|
519 |
+
elif any(ps.is_Discrete for ps in pspaces):
|
520 |
+
from sympy.stats.drv import (ConditionalDiscreteDomain,
|
521 |
+
DiscretePSpace)
|
522 |
+
space = DiscretePSpace
|
523 |
+
domain = ConditionalDiscreteDomain(self.domain, condition)
|
524 |
+
elif all(ps.is_Finite for ps in pspaces):
|
525 |
+
from sympy.stats.frv import FinitePSpace
|
526 |
+
return FinitePSpace.conditional_space(self, condition)
|
527 |
+
if normalize:
|
528 |
+
replacement = {rv: Dummy(str(rv)) for rv in self.symbols}
|
529 |
+
norm = domain.compute_expectation(self.pdf, **kwargs)
|
530 |
+
pdf = self.pdf / norm.xreplace(replacement)
|
531 |
+
# XXX: Converting symbols from set to tuple. The order matters to
|
532 |
+
# Lambda though so we shouldn't be starting with a set here...
|
533 |
+
density = Lambda(tuple(domain.symbols), pdf)
|
534 |
+
|
535 |
+
return space(domain, density)
|
536 |
+
|
537 |
+
class ProductDomain(RandomDomain):
|
538 |
+
"""
|
539 |
+
A domain resulting from the merger of two independent domains.
|
540 |
+
|
541 |
+
See Also
|
542 |
+
========
|
543 |
+
sympy.stats.crv.ProductContinuousDomain
|
544 |
+
sympy.stats.frv.ProductFiniteDomain
|
545 |
+
"""
|
546 |
+
is_ProductDomain = True
|
547 |
+
|
548 |
+
def __new__(cls, *domains):
|
549 |
+
# Flatten any product of products
|
550 |
+
domains2 = []
|
551 |
+
for domain in domains:
|
552 |
+
if not domain.is_ProductDomain:
|
553 |
+
domains2.append(domain)
|
554 |
+
else:
|
555 |
+
domains2.extend(domain.domains)
|
556 |
+
domains2 = FiniteSet(*domains2)
|
557 |
+
|
558 |
+
if all(domain.is_Finite for domain in domains2):
|
559 |
+
from sympy.stats.frv import ProductFiniteDomain
|
560 |
+
cls = ProductFiniteDomain
|
561 |
+
if all(domain.is_Continuous for domain in domains2):
|
562 |
+
from sympy.stats.crv import ProductContinuousDomain
|
563 |
+
cls = ProductContinuousDomain
|
564 |
+
if all(domain.is_Discrete for domain in domains2):
|
565 |
+
from sympy.stats.drv import ProductDiscreteDomain
|
566 |
+
cls = ProductDiscreteDomain
|
567 |
+
|
568 |
+
return Basic.__new__(cls, *domains2)
|
569 |
+
|
570 |
+
@property
|
571 |
+
def sym_domain_dict(self):
|
572 |
+
return {symbol: domain for domain in self.domains
|
573 |
+
for symbol in domain.symbols}
|
574 |
+
|
575 |
+
@property
|
576 |
+
def symbols(self):
|
577 |
+
return FiniteSet(*[sym for domain in self.domains
|
578 |
+
for sym in domain.symbols])
|
579 |
+
|
580 |
+
@property
|
581 |
+
def domains(self):
|
582 |
+
return self.args
|
583 |
+
|
584 |
+
@property
|
585 |
+
def set(self):
|
586 |
+
return ProductSet(*(domain.set for domain in self.domains))
|
587 |
+
|
588 |
+
def __contains__(self, other):
|
589 |
+
# Split event into each subdomain
|
590 |
+
for domain in self.domains:
|
591 |
+
# Collect the parts of this event which associate to this domain
|
592 |
+
elem = frozenset([item for item in other
|
593 |
+
if sympify(domain.symbols.contains(item[0]))
|
594 |
+
is S.true])
|
595 |
+
# Test this sub-event
|
596 |
+
if elem not in domain:
|
597 |
+
return False
|
598 |
+
# All subevents passed
|
599 |
+
return True
|
600 |
+
|
601 |
+
def as_boolean(self):
|
602 |
+
return And(*[domain.as_boolean() for domain in self.domains])
|
603 |
+
|
604 |
+
|
605 |
+
def random_symbols(expr):
|
606 |
+
"""
|
607 |
+
Returns all RandomSymbols within a SymPy Expression.
|
608 |
+
"""
|
609 |
+
atoms = getattr(expr, 'atoms', None)
|
610 |
+
if atoms is not None:
|
611 |
+
comp = lambda rv: rv.symbol.name
|
612 |
+
l = list(atoms(RandomSymbol))
|
613 |
+
return sorted(l, key=comp)
|
614 |
+
else:
|
615 |
+
return []
|
616 |
+
|
617 |
+
|
618 |
+
def pspace(expr):
|
619 |
+
"""
|
620 |
+
Returns the underlying Probability Space of a random expression.
|
621 |
+
|
622 |
+
For internal use.
|
623 |
+
|
624 |
+
Examples
|
625 |
+
========
|
626 |
+
|
627 |
+
>>> from sympy.stats import pspace, Normal
|
628 |
+
>>> X = Normal('X', 0, 1)
|
629 |
+
>>> pspace(2*X + 1) == X.pspace
|
630 |
+
True
|
631 |
+
"""
|
632 |
+
expr = sympify(expr)
|
633 |
+
if isinstance(expr, RandomSymbol) and expr.pspace is not None:
|
634 |
+
return expr.pspace
|
635 |
+
if expr.has(RandomMatrixSymbol):
|
636 |
+
rm = list(expr.atoms(RandomMatrixSymbol))[0]
|
637 |
+
return rm.pspace
|
638 |
+
|
639 |
+
rvs = random_symbols(expr)
|
640 |
+
if not rvs:
|
641 |
+
raise ValueError("Expression containing Random Variable expected, not %s" % (expr))
|
642 |
+
# If only one space present
|
643 |
+
if all(rv.pspace == rvs[0].pspace for rv in rvs):
|
644 |
+
return rvs[0].pspace
|
645 |
+
from sympy.stats.compound_rv import CompoundPSpace
|
646 |
+
from sympy.stats.stochastic_process import StochasticPSpace
|
647 |
+
for rv in rvs:
|
648 |
+
if isinstance(rv.pspace, (CompoundPSpace, StochasticPSpace)):
|
649 |
+
return rv.pspace
|
650 |
+
# Otherwise make a product space
|
651 |
+
return IndependentProductPSpace(*[rv.pspace for rv in rvs])
|
652 |
+
|
653 |
+
|
654 |
+
def sumsets(sets):
|
655 |
+
"""
|
656 |
+
Union of sets
|
657 |
+
"""
|
658 |
+
return frozenset().union(*sets)
|
659 |
+
|
660 |
+
|
661 |
+
def rs_swap(a, b):
|
662 |
+
"""
|
663 |
+
Build a dictionary to swap RandomSymbols based on their underlying symbol.
|
664 |
+
|
665 |
+
i.e.
|
666 |
+
if ``X = ('x', pspace1)``
|
667 |
+
and ``Y = ('x', pspace2)``
|
668 |
+
then ``X`` and ``Y`` match and the key, value pair
|
669 |
+
``{X:Y}`` will appear in the result
|
670 |
+
|
671 |
+
Inputs: collections a and b of random variables which share common symbols
|
672 |
+
Output: dict mapping RVs in a to RVs in b
|
673 |
+
"""
|
674 |
+
d = {}
|
675 |
+
for rsa in a:
|
676 |
+
d[rsa] = [rsb for rsb in b if rsa.symbol == rsb.symbol][0]
|
677 |
+
return d
|
678 |
+
|
679 |
+
|
680 |
+
def given(expr, condition=None, **kwargs):
|
681 |
+
r""" Conditional Random Expression.
|
682 |
+
|
683 |
+
Explanation
|
684 |
+
===========
|
685 |
+
|
686 |
+
From a random expression and a condition on that expression creates a new
|
687 |
+
probability space from the condition and returns the same expression on that
|
688 |
+
conditional probability space.
|
689 |
+
|
690 |
+
Examples
|
691 |
+
========
|
692 |
+
|
693 |
+
>>> from sympy.stats import given, density, Die
|
694 |
+
>>> X = Die('X', 6)
|
695 |
+
>>> Y = given(X, X > 3)
|
696 |
+
>>> density(Y).dict
|
697 |
+
{4: 1/3, 5: 1/3, 6: 1/3}
|
698 |
+
|
699 |
+
Following convention, if the condition is a random symbol then that symbol
|
700 |
+
is considered fixed.
|
701 |
+
|
702 |
+
>>> from sympy.stats import Normal
|
703 |
+
>>> from sympy import pprint
|
704 |
+
>>> from sympy.abc import z
|
705 |
+
|
706 |
+
>>> X = Normal('X', 0, 1)
|
707 |
+
>>> Y = Normal('Y', 0, 1)
|
708 |
+
>>> pprint(density(X + Y, Y)(z), use_unicode=False)
|
709 |
+
2
|
710 |
+
-(-Y + z)
|
711 |
+
-----------
|
712 |
+
___ 2
|
713 |
+
\/ 2 *e
|
714 |
+
------------------
|
715 |
+
____
|
716 |
+
2*\/ pi
|
717 |
+
"""
|
718 |
+
|
719 |
+
if not is_random(condition) or pspace_independent(expr, condition):
|
720 |
+
return expr
|
721 |
+
|
722 |
+
if isinstance(condition, RandomSymbol):
|
723 |
+
condition = Eq(condition, condition.symbol)
|
724 |
+
|
725 |
+
condsymbols = random_symbols(condition)
|
726 |
+
if (isinstance(condition, Eq) and len(condsymbols) == 1 and
|
727 |
+
not isinstance(pspace(expr).domain, ConditionalDomain)):
|
728 |
+
rv = tuple(condsymbols)[0]
|
729 |
+
|
730 |
+
results = solveset(condition, rv)
|
731 |
+
if isinstance(results, Intersection) and S.Reals in results.args:
|
732 |
+
results = list(results.args[1])
|
733 |
+
|
734 |
+
sums = 0
|
735 |
+
for res in results:
|
736 |
+
temp = expr.subs(rv, res)
|
737 |
+
if temp == True:
|
738 |
+
return True
|
739 |
+
if temp != False:
|
740 |
+
# XXX: This seems nonsensical but preserves existing behaviour
|
741 |
+
# after the change that Relational is no longer a subclass of
|
742 |
+
# Expr. Here expr is sometimes Relational and sometimes Expr
|
743 |
+
# but we are trying to add them with +=. This needs to be
|
744 |
+
# fixed somehow.
|
745 |
+
if sums == 0 and isinstance(expr, Relational):
|
746 |
+
sums = expr.subs(rv, res)
|
747 |
+
else:
|
748 |
+
sums += expr.subs(rv, res)
|
749 |
+
if sums == 0:
|
750 |
+
return False
|
751 |
+
return sums
|
752 |
+
|
753 |
+
# Get full probability space of both the expression and the condition
|
754 |
+
fullspace = pspace(Tuple(expr, condition))
|
755 |
+
# Build new space given the condition
|
756 |
+
space = fullspace.conditional_space(condition, **kwargs)
|
757 |
+
# Dictionary to swap out RandomSymbols in expr with new RandomSymbols
|
758 |
+
# That point to the new conditional space
|
759 |
+
swapdict = rs_swap(fullspace.values, space.values)
|
760 |
+
# Swap random variables in the expression
|
761 |
+
expr = expr.xreplace(swapdict)
|
762 |
+
return expr
|
763 |
+
|
764 |
+
|
765 |
+
def expectation(expr, condition=None, numsamples=None, evaluate=True, **kwargs):
|
766 |
+
"""
|
767 |
+
Returns the expected value of a random expression.
|
768 |
+
|
769 |
+
Parameters
|
770 |
+
==========
|
771 |
+
|
772 |
+
expr : Expr containing RandomSymbols
|
773 |
+
The expression of which you want to compute the expectation value
|
774 |
+
given : Expr containing RandomSymbols
|
775 |
+
A conditional expression. E(X, X>0) is expectation of X given X > 0
|
776 |
+
numsamples : int
|
777 |
+
Enables sampling and approximates the expectation with this many samples
|
778 |
+
evalf : Bool (defaults to True)
|
779 |
+
If sampling return a number rather than a complex expression
|
780 |
+
evaluate : Bool (defaults to True)
|
781 |
+
In case of continuous systems return unevaluated integral
|
782 |
+
|
783 |
+
Examples
|
784 |
+
========
|
785 |
+
|
786 |
+
>>> from sympy.stats import E, Die
|
787 |
+
>>> X = Die('X', 6)
|
788 |
+
>>> E(X)
|
789 |
+
7/2
|
790 |
+
>>> E(2*X + 1)
|
791 |
+
8
|
792 |
+
|
793 |
+
>>> E(X, X > 3) # Expectation of X given that it is above 3
|
794 |
+
5
|
795 |
+
"""
|
796 |
+
|
797 |
+
if not is_random(expr): # expr isn't random?
|
798 |
+
return expr
|
799 |
+
kwargs['numsamples'] = numsamples
|
800 |
+
from sympy.stats.symbolic_probability import Expectation
|
801 |
+
if evaluate:
|
802 |
+
return Expectation(expr, condition).doit(**kwargs)
|
803 |
+
return Expectation(expr, condition)
|
804 |
+
|
805 |
+
|
806 |
+
def probability(condition, given_condition=None, numsamples=None,
|
807 |
+
evaluate=True, **kwargs):
|
808 |
+
"""
|
809 |
+
Probability that a condition is true, optionally given a second condition.
|
810 |
+
|
811 |
+
Parameters
|
812 |
+
==========
|
813 |
+
|
814 |
+
condition : Combination of Relationals containing RandomSymbols
|
815 |
+
The condition of which you want to compute the probability
|
816 |
+
given_condition : Combination of Relationals containing RandomSymbols
|
817 |
+
A conditional expression. P(X > 1, X > 0) is expectation of X > 1
|
818 |
+
given X > 0
|
819 |
+
numsamples : int
|
820 |
+
Enables sampling and approximates the probability with this many samples
|
821 |
+
evaluate : Bool (defaults to True)
|
822 |
+
In case of continuous systems return unevaluated integral
|
823 |
+
|
824 |
+
Examples
|
825 |
+
========
|
826 |
+
|
827 |
+
>>> from sympy.stats import P, Die
|
828 |
+
>>> from sympy import Eq
|
829 |
+
>>> X, Y = Die('X', 6), Die('Y', 6)
|
830 |
+
>>> P(X > 3)
|
831 |
+
1/2
|
832 |
+
>>> P(Eq(X, 5), X > 2) # Probability that X == 5 given that X > 2
|
833 |
+
1/4
|
834 |
+
>>> P(X > Y)
|
835 |
+
5/12
|
836 |
+
"""
|
837 |
+
|
838 |
+
kwargs['numsamples'] = numsamples
|
839 |
+
from sympy.stats.symbolic_probability import Probability
|
840 |
+
if evaluate:
|
841 |
+
return Probability(condition, given_condition).doit(**kwargs)
|
842 |
+
return Probability(condition, given_condition)
|
843 |
+
|
844 |
+
|
845 |
+
class Density(Basic):
|
846 |
+
expr = property(lambda self: self.args[0])
|
847 |
+
|
848 |
+
def __new__(cls, expr, condition = None):
|
849 |
+
expr = _sympify(expr)
|
850 |
+
if condition is None:
|
851 |
+
obj = Basic.__new__(cls, expr)
|
852 |
+
else:
|
853 |
+
condition = _sympify(condition)
|
854 |
+
obj = Basic.__new__(cls, expr, condition)
|
855 |
+
return obj
|
856 |
+
|
857 |
+
@property
|
858 |
+
def condition(self):
|
859 |
+
if len(self.args) > 1:
|
860 |
+
return self.args[1]
|
861 |
+
else:
|
862 |
+
return None
|
863 |
+
|
864 |
+
def doit(self, evaluate=True, **kwargs):
|
865 |
+
from sympy.stats.random_matrix import RandomMatrixPSpace
|
866 |
+
from sympy.stats.joint_rv import JointPSpace
|
867 |
+
from sympy.stats.matrix_distributions import MatrixPSpace
|
868 |
+
from sympy.stats.compound_rv import CompoundPSpace
|
869 |
+
from sympy.stats.frv import SingleFiniteDistribution
|
870 |
+
expr, condition = self.expr, self.condition
|
871 |
+
|
872 |
+
if isinstance(expr, SingleFiniteDistribution):
|
873 |
+
return expr.dict
|
874 |
+
if condition is not None:
|
875 |
+
# Recompute on new conditional expr
|
876 |
+
expr = given(expr, condition, **kwargs)
|
877 |
+
if not random_symbols(expr):
|
878 |
+
return Lambda(x, DiracDelta(x - expr))
|
879 |
+
if isinstance(expr, RandomSymbol):
|
880 |
+
if isinstance(expr.pspace, (SinglePSpace, JointPSpace, MatrixPSpace)) and \
|
881 |
+
hasattr(expr.pspace, 'distribution'):
|
882 |
+
return expr.pspace.distribution
|
883 |
+
elif isinstance(expr.pspace, RandomMatrixPSpace):
|
884 |
+
return expr.pspace.model
|
885 |
+
if isinstance(pspace(expr), CompoundPSpace):
|
886 |
+
kwargs['compound_evaluate'] = evaluate
|
887 |
+
result = pspace(expr).compute_density(expr, **kwargs)
|
888 |
+
|
889 |
+
if evaluate and hasattr(result, 'doit'):
|
890 |
+
return result.doit()
|
891 |
+
else:
|
892 |
+
return result
|
893 |
+
|
894 |
+
|
895 |
+
def density(expr, condition=None, evaluate=True, numsamples=None, **kwargs):
|
896 |
+
"""
|
897 |
+
Probability density of a random expression, optionally given a second
|
898 |
+
condition.
|
899 |
+
|
900 |
+
Explanation
|
901 |
+
===========
|
902 |
+
|
903 |
+
This density will take on different forms for different types of
|
904 |
+
probability spaces. Discrete variables produce Dicts. Continuous
|
905 |
+
variables produce Lambdas.
|
906 |
+
|
907 |
+
Parameters
|
908 |
+
==========
|
909 |
+
|
910 |
+
expr : Expr containing RandomSymbols
|
911 |
+
The expression of which you want to compute the density value
|
912 |
+
condition : Relational containing RandomSymbols
|
913 |
+
A conditional expression. density(X > 1, X > 0) is density of X > 1
|
914 |
+
given X > 0
|
915 |
+
numsamples : int
|
916 |
+
Enables sampling and approximates the density with this many samples
|
917 |
+
|
918 |
+
Examples
|
919 |
+
========
|
920 |
+
|
921 |
+
>>> from sympy.stats import density, Die, Normal
|
922 |
+
>>> from sympy import Symbol
|
923 |
+
|
924 |
+
>>> x = Symbol('x')
|
925 |
+
>>> D = Die('D', 6)
|
926 |
+
>>> X = Normal(x, 0, 1)
|
927 |
+
|
928 |
+
>>> density(D).dict
|
929 |
+
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
|
930 |
+
>>> density(2*D).dict
|
931 |
+
{2: 1/6, 4: 1/6, 6: 1/6, 8: 1/6, 10: 1/6, 12: 1/6}
|
932 |
+
>>> density(X)(x)
|
933 |
+
sqrt(2)*exp(-x**2/2)/(2*sqrt(pi))
|
934 |
+
"""
|
935 |
+
|
936 |
+
if numsamples:
|
937 |
+
return sampling_density(expr, condition, numsamples=numsamples,
|
938 |
+
**kwargs)
|
939 |
+
|
940 |
+
return Density(expr, condition).doit(evaluate=evaluate, **kwargs)
|
941 |
+
|
942 |
+
|
943 |
+
def cdf(expr, condition=None, evaluate=True, **kwargs):
|
944 |
+
"""
|
945 |
+
Cumulative Distribution Function of a random expression.
|
946 |
+
|
947 |
+
optionally given a second condition.
|
948 |
+
|
949 |
+
Explanation
|
950 |
+
===========
|
951 |
+
|
952 |
+
This density will take on different forms for different types of
|
953 |
+
probability spaces.
|
954 |
+
Discrete variables produce Dicts.
|
955 |
+
Continuous variables produce Lambdas.
|
956 |
+
|
957 |
+
Examples
|
958 |
+
========
|
959 |
+
|
960 |
+
>>> from sympy.stats import density, Die, Normal, cdf
|
961 |
+
|
962 |
+
>>> D = Die('D', 6)
|
963 |
+
>>> X = Normal('X', 0, 1)
|
964 |
+
|
965 |
+
>>> density(D).dict
|
966 |
+
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
|
967 |
+
>>> cdf(D)
|
968 |
+
{1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1}
|
969 |
+
>>> cdf(3*D, D > 2)
|
970 |
+
{9: 1/4, 12: 1/2, 15: 3/4, 18: 1}
|
971 |
+
|
972 |
+
>>> cdf(X)
|
973 |
+
Lambda(_z, erf(sqrt(2)*_z/2)/2 + 1/2)
|
974 |
+
"""
|
975 |
+
if condition is not None: # If there is a condition
|
976 |
+
# Recompute on new conditional expr
|
977 |
+
return cdf(given(expr, condition, **kwargs), **kwargs)
|
978 |
+
|
979 |
+
# Otherwise pass work off to the ProbabilitySpace
|
980 |
+
result = pspace(expr).compute_cdf(expr, **kwargs)
|
981 |
+
|
982 |
+
if evaluate and hasattr(result, 'doit'):
|
983 |
+
return result.doit()
|
984 |
+
else:
|
985 |
+
return result
|
986 |
+
|
987 |
+
|
988 |
+
def characteristic_function(expr, condition=None, evaluate=True, **kwargs):
|
989 |
+
"""
|
990 |
+
Characteristic function of a random expression, optionally given a second condition.
|
991 |
+
|
992 |
+
Returns a Lambda.
|
993 |
+
|
994 |
+
Examples
|
995 |
+
========
|
996 |
+
|
997 |
+
>>> from sympy.stats import Normal, DiscreteUniform, Poisson, characteristic_function
|
998 |
+
|
999 |
+
>>> X = Normal('X', 0, 1)
|
1000 |
+
>>> characteristic_function(X)
|
1001 |
+
Lambda(_t, exp(-_t**2/2))
|
1002 |
+
|
1003 |
+
>>> Y = DiscreteUniform('Y', [1, 2, 7])
|
1004 |
+
>>> characteristic_function(Y)
|
1005 |
+
Lambda(_t, exp(7*_t*I)/3 + exp(2*_t*I)/3 + exp(_t*I)/3)
|
1006 |
+
|
1007 |
+
>>> Z = Poisson('Z', 2)
|
1008 |
+
>>> characteristic_function(Z)
|
1009 |
+
Lambda(_t, exp(2*exp(_t*I) - 2))
|
1010 |
+
"""
|
1011 |
+
if condition is not None:
|
1012 |
+
return characteristic_function(given(expr, condition, **kwargs), **kwargs)
|
1013 |
+
|
1014 |
+
result = pspace(expr).compute_characteristic_function(expr, **kwargs)
|
1015 |
+
|
1016 |
+
if evaluate and hasattr(result, 'doit'):
|
1017 |
+
return result.doit()
|
1018 |
+
else:
|
1019 |
+
return result
|
1020 |
+
|
1021 |
+
def moment_generating_function(expr, condition=None, evaluate=True, **kwargs):
|
1022 |
+
if condition is not None:
|
1023 |
+
return moment_generating_function(given(expr, condition, **kwargs), **kwargs)
|
1024 |
+
|
1025 |
+
result = pspace(expr).compute_moment_generating_function(expr, **kwargs)
|
1026 |
+
|
1027 |
+
if evaluate and hasattr(result, 'doit'):
|
1028 |
+
return result.doit()
|
1029 |
+
else:
|
1030 |
+
return result
|
1031 |
+
|
1032 |
+
def where(condition, given_condition=None, **kwargs):
|
1033 |
+
"""
|
1034 |
+
Returns the domain where a condition is True.
|
1035 |
+
|
1036 |
+
Examples
|
1037 |
+
========
|
1038 |
+
|
1039 |
+
>>> from sympy.stats import where, Die, Normal
|
1040 |
+
>>> from sympy import And
|
1041 |
+
|
1042 |
+
>>> D1, D2 = Die('a', 6), Die('b', 6)
|
1043 |
+
>>> a, b = D1.symbol, D2.symbol
|
1044 |
+
>>> X = Normal('x', 0, 1)
|
1045 |
+
|
1046 |
+
>>> where(X**2<1)
|
1047 |
+
Domain: (-1 < x) & (x < 1)
|
1048 |
+
|
1049 |
+
>>> where(X**2<1).set
|
1050 |
+
Interval.open(-1, 1)
|
1051 |
+
|
1052 |
+
>>> where(And(D1<=D2, D2<3))
|
1053 |
+
Domain: (Eq(a, 1) & Eq(b, 1)) | (Eq(a, 1) & Eq(b, 2)) | (Eq(a, 2) & Eq(b, 2))
|
1054 |
+
"""
|
1055 |
+
if given_condition is not None: # If there is a condition
|
1056 |
+
# Recompute on new conditional expr
|
1057 |
+
return where(given(condition, given_condition, **kwargs), **kwargs)
|
1058 |
+
|
1059 |
+
# Otherwise pass work off to the ProbabilitySpace
|
1060 |
+
return pspace(condition).where(condition, **kwargs)
|
1061 |
+
|
1062 |
+
|
1063 |
+
@doctest_depends_on(modules=('scipy',))
|
1064 |
+
def sample(expr, condition=None, size=(), library='scipy',
|
1065 |
+
numsamples=1, seed=None, **kwargs):
|
1066 |
+
"""
|
1067 |
+
A realization of the random expression.
|
1068 |
+
|
1069 |
+
Parameters
|
1070 |
+
==========
|
1071 |
+
|
1072 |
+
expr : Expression of random variables
|
1073 |
+
Expression from which sample is extracted
|
1074 |
+
condition : Expr containing RandomSymbols
|
1075 |
+
A conditional expression
|
1076 |
+
size : int, tuple
|
1077 |
+
Represents size of each sample in numsamples
|
1078 |
+
library : str
|
1079 |
+
- 'scipy' : Sample using scipy
|
1080 |
+
- 'numpy' : Sample using numpy
|
1081 |
+
- 'pymc' : Sample using PyMC
|
1082 |
+
|
1083 |
+
Choose any of the available options to sample from as string,
|
1084 |
+
by default is 'scipy'
|
1085 |
+
numsamples : int
|
1086 |
+
Number of samples, each with size as ``size``.
|
1087 |
+
|
1088 |
+
.. deprecated:: 1.9
|
1089 |
+
|
1090 |
+
The ``numsamples`` parameter is deprecated and is only provided for
|
1091 |
+
compatibility with v1.8. Use a list comprehension or an additional
|
1092 |
+
dimension in ``size`` instead. See
|
1093 |
+
:ref:`deprecated-sympy-stats-numsamples` for details.
|
1094 |
+
|
1095 |
+
seed :
|
1096 |
+
An object to be used as seed by the given external library for sampling `expr`.
|
1097 |
+
Following is the list of possible types of object for the supported libraries,
|
1098 |
+
|
1099 |
+
- 'scipy': int, numpy.random.RandomState, numpy.random.Generator
|
1100 |
+
- 'numpy': int, numpy.random.RandomState, numpy.random.Generator
|
1101 |
+
- 'pymc': int
|
1102 |
+
|
1103 |
+
Optional, by default None, in which case seed settings
|
1104 |
+
related to the given library will be used.
|
1105 |
+
No modifications to environment's global seed settings
|
1106 |
+
are done by this argument.
|
1107 |
+
|
1108 |
+
Returns
|
1109 |
+
=======
|
1110 |
+
|
1111 |
+
sample: float/list/numpy.ndarray
|
1112 |
+
one sample or a collection of samples of the random expression.
|
1113 |
+
|
1114 |
+
- sample(X) returns float/numpy.float64/numpy.int64 object.
|
1115 |
+
- sample(X, size=int/tuple) returns numpy.ndarray object.
|
1116 |
+
|
1117 |
+
Examples
|
1118 |
+
========
|
1119 |
+
|
1120 |
+
>>> from sympy.stats import Die, sample, Normal, Geometric
|
1121 |
+
>>> X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) # Finite Random Variable
|
1122 |
+
>>> die_roll = sample(X + Y + Z)
|
1123 |
+
>>> die_roll # doctest: +SKIP
|
1124 |
+
3
|
1125 |
+
>>> N = Normal('N', 3, 4) # Continuous Random Variable
|
1126 |
+
>>> samp = sample(N)
|
1127 |
+
>>> samp in N.pspace.domain.set
|
1128 |
+
True
|
1129 |
+
>>> samp = sample(N, N>0)
|
1130 |
+
>>> samp > 0
|
1131 |
+
True
|
1132 |
+
>>> samp_list = sample(N, size=4)
|
1133 |
+
>>> [sam in N.pspace.domain.set for sam in samp_list]
|
1134 |
+
[True, True, True, True]
|
1135 |
+
>>> sample(N, size = (2,3)) # doctest: +SKIP
|
1136 |
+
array([[5.42519758, 6.40207856, 4.94991743],
|
1137 |
+
[1.85819627, 6.83403519, 1.9412172 ]])
|
1138 |
+
>>> G = Geometric('G', 0.5) # Discrete Random Variable
|
1139 |
+
>>> samp_list = sample(G, size=3)
|
1140 |
+
>>> samp_list # doctest: +SKIP
|
1141 |
+
[1, 3, 2]
|
1142 |
+
>>> [sam in G.pspace.domain.set for sam in samp_list]
|
1143 |
+
[True, True, True]
|
1144 |
+
>>> MN = Normal("MN", [3, 4], [[2, 1], [1, 2]]) # Joint Random Variable
|
1145 |
+
>>> samp_list = sample(MN, size=4)
|
1146 |
+
>>> samp_list # doctest: +SKIP
|
1147 |
+
[array([2.85768055, 3.38954165]),
|
1148 |
+
array([4.11163337, 4.3176591 ]),
|
1149 |
+
array([0.79115232, 1.63232916]),
|
1150 |
+
array([4.01747268, 3.96716083])]
|
1151 |
+
>>> [tuple(sam) in MN.pspace.domain.set for sam in samp_list]
|
1152 |
+
[True, True, True, True]
|
1153 |
+
|
1154 |
+
.. versionchanged:: 1.7.0
|
1155 |
+
sample used to return an iterator containing the samples instead of value.
|
1156 |
+
|
1157 |
+
.. versionchanged:: 1.9.0
|
1158 |
+
sample returns values or array of values instead of an iterator and numsamples is deprecated.
|
1159 |
+
|
1160 |
+
"""
|
1161 |
+
|
1162 |
+
iterator = sample_iter(expr, condition, size=size, library=library,
|
1163 |
+
numsamples=numsamples, seed=seed)
|
1164 |
+
|
1165 |
+
if numsamples != 1:
|
1166 |
+
sympy_deprecation_warning(
|
1167 |
+
f"""
|
1168 |
+
The numsamples parameter to sympy.stats.sample() is deprecated.
|
1169 |
+
Either use a list comprehension, like
|
1170 |
+
|
1171 |
+
[sample(...) for i in range({numsamples})]
|
1172 |
+
|
1173 |
+
or add a dimension to size, like
|
1174 |
+
|
1175 |
+
sample(..., size={(numsamples,) + size})
|
1176 |
+
""",
|
1177 |
+
deprecated_since_version="1.9",
|
1178 |
+
active_deprecations_target="deprecated-sympy-stats-numsamples",
|
1179 |
+
)
|
1180 |
+
return [next(iterator) for i in range(numsamples)]
|
1181 |
+
|
1182 |
+
return next(iterator)
|
1183 |
+
|
1184 |
+
|
1185 |
+
def quantile(expr, evaluate=True, **kwargs):
|
1186 |
+
r"""
|
1187 |
+
Return the :math:`p^{th}` order quantile of a probability distribution.
|
1188 |
+
|
1189 |
+
Explanation
|
1190 |
+
===========
|
1191 |
+
|
1192 |
+
Quantile is defined as the value at which the probability of the random
|
1193 |
+
variable is less than or equal to the given probability.
|
1194 |
+
|
1195 |
+
.. math::
|
1196 |
+
Q(p) = \inf\{x \in (-\infty, \infty) : p \le F(x)\}
|
1197 |
+
|
1198 |
+
Examples
|
1199 |
+
========
|
1200 |
+
|
1201 |
+
>>> from sympy.stats import quantile, Die, Exponential
|
1202 |
+
>>> from sympy import Symbol, pprint
|
1203 |
+
>>> p = Symbol("p")
|
1204 |
+
|
1205 |
+
>>> l = Symbol("lambda", positive=True)
|
1206 |
+
>>> X = Exponential("x", l)
|
1207 |
+
>>> quantile(X)(p)
|
1208 |
+
-log(1 - p)/lambda
|
1209 |
+
|
1210 |
+
>>> D = Die("d", 6)
|
1211 |
+
>>> pprint(quantile(D)(p), use_unicode=False)
|
1212 |
+
/nan for Or(p > 1, p < 0)
|
1213 |
+
|
|
1214 |
+
| 1 for p <= 1/6
|
1215 |
+
|
|
1216 |
+
| 2 for p <= 1/3
|
1217 |
+
|
|
1218 |
+
< 3 for p <= 1/2
|
1219 |
+
|
|
1220 |
+
| 4 for p <= 2/3
|
1221 |
+
|
|
1222 |
+
| 5 for p <= 5/6
|
1223 |
+
|
|
1224 |
+
\ 6 for p <= 1
|
1225 |
+
|
1226 |
+
"""
|
1227 |
+
result = pspace(expr).compute_quantile(expr, **kwargs)
|
1228 |
+
|
1229 |
+
if evaluate and hasattr(result, 'doit'):
|
1230 |
+
return result.doit()
|
1231 |
+
else:
|
1232 |
+
return result
|
1233 |
+
|
1234 |
+
def sample_iter(expr, condition=None, size=(), library='scipy',
|
1235 |
+
numsamples=S.Infinity, seed=None, **kwargs):
|
1236 |
+
|
1237 |
+
"""
|
1238 |
+
Returns an iterator of realizations from the expression given a condition.
|
1239 |
+
|
1240 |
+
Parameters
|
1241 |
+
==========
|
1242 |
+
|
1243 |
+
expr: Expr
|
1244 |
+
Random expression to be realized
|
1245 |
+
condition: Expr, optional
|
1246 |
+
A conditional expression
|
1247 |
+
size : int, tuple
|
1248 |
+
Represents size of each sample in numsamples
|
1249 |
+
numsamples: integer, optional
|
1250 |
+
Length of the iterator (defaults to infinity)
|
1251 |
+
seed :
|
1252 |
+
An object to be used as seed by the given external library for sampling `expr`.
|
1253 |
+
Following is the list of possible types of object for the supported libraries,
|
1254 |
+
|
1255 |
+
- 'scipy': int, numpy.random.RandomState, numpy.random.Generator
|
1256 |
+
- 'numpy': int, numpy.random.RandomState, numpy.random.Generator
|
1257 |
+
- 'pymc': int
|
1258 |
+
|
1259 |
+
Optional, by default None, in which case seed settings
|
1260 |
+
related to the given library will be used.
|
1261 |
+
No modifications to environment's global seed settings
|
1262 |
+
are done by this argument.
|
1263 |
+
|
1264 |
+
Examples
|
1265 |
+
========
|
1266 |
+
|
1267 |
+
>>> from sympy.stats import Normal, sample_iter
|
1268 |
+
>>> X = Normal('X', 0, 1)
|
1269 |
+
>>> expr = X*X + 3
|
1270 |
+
>>> iterator = sample_iter(expr, numsamples=3) # doctest: +SKIP
|
1271 |
+
>>> list(iterator) # doctest: +SKIP
|
1272 |
+
[12, 4, 7]
|
1273 |
+
|
1274 |
+
Returns
|
1275 |
+
=======
|
1276 |
+
|
1277 |
+
sample_iter: iterator object
|
1278 |
+
iterator object containing the sample/samples of given expr
|
1279 |
+
|
1280 |
+
See Also
|
1281 |
+
========
|
1282 |
+
|
1283 |
+
sample
|
1284 |
+
sampling_P
|
1285 |
+
sampling_E
|
1286 |
+
|
1287 |
+
"""
|
1288 |
+
from sympy.stats.joint_rv import JointRandomSymbol
|
1289 |
+
if not import_module(library):
|
1290 |
+
raise ValueError("Failed to import %s" % library)
|
1291 |
+
|
1292 |
+
if condition is not None:
|
1293 |
+
ps = pspace(Tuple(expr, condition))
|
1294 |
+
else:
|
1295 |
+
ps = pspace(expr)
|
1296 |
+
|
1297 |
+
rvs = list(ps.values)
|
1298 |
+
if isinstance(expr, JointRandomSymbol):
|
1299 |
+
expr = expr.subs({expr: RandomSymbol(expr.symbol, expr.pspace)})
|
1300 |
+
else:
|
1301 |
+
sub = {}
|
1302 |
+
for arg in expr.args:
|
1303 |
+
if isinstance(arg, JointRandomSymbol):
|
1304 |
+
sub[arg] = RandomSymbol(arg.symbol, arg.pspace)
|
1305 |
+
expr = expr.subs(sub)
|
1306 |
+
|
1307 |
+
def fn_subs(*args):
|
1308 |
+
return expr.subs({rv: arg for rv, arg in zip(rvs, args)})
|
1309 |
+
|
1310 |
+
def given_fn_subs(*args):
|
1311 |
+
if condition is not None:
|
1312 |
+
return condition.subs({rv: arg for rv, arg in zip(rvs, args)})
|
1313 |
+
return False
|
1314 |
+
|
1315 |
+
if library in ('pymc', 'pymc3'):
|
1316 |
+
# Currently unable to lambdify in pymc
|
1317 |
+
# TODO : Remove when lambdify accepts 'pymc' as module
|
1318 |
+
fn = lambdify(rvs, expr, **kwargs)
|
1319 |
+
else:
|
1320 |
+
fn = lambdify(rvs, expr, modules=library, **kwargs)
|
1321 |
+
|
1322 |
+
|
1323 |
+
if condition is not None:
|
1324 |
+
given_fn = lambdify(rvs, condition, **kwargs)
|
1325 |
+
|
1326 |
+
def return_generator_infinite():
|
1327 |
+
count = 0
|
1328 |
+
_size = (1,)+((size,) if isinstance(size, int) else size)
|
1329 |
+
while count < numsamples:
|
1330 |
+
d = ps.sample(size=_size, library=library, seed=seed) # a dictionary that maps RVs to values
|
1331 |
+
args = [d[rv][0] for rv in rvs]
|
1332 |
+
|
1333 |
+
if condition is not None: # Check that these values satisfy the condition
|
1334 |
+
# TODO: Replace the try-except block with only given_fn(*args)
|
1335 |
+
# once lambdify works with unevaluated SymPy objects.
|
1336 |
+
try:
|
1337 |
+
gd = given_fn(*args)
|
1338 |
+
except (NameError, TypeError):
|
1339 |
+
gd = given_fn_subs(*args)
|
1340 |
+
if gd != True and gd != False:
|
1341 |
+
raise ValueError(
|
1342 |
+
"Conditions must not contain free symbols")
|
1343 |
+
if not gd: # If the values don't satisfy then try again
|
1344 |
+
continue
|
1345 |
+
|
1346 |
+
yield fn(*args)
|
1347 |
+
count += 1
|
1348 |
+
|
1349 |
+
def return_generator_finite():
|
1350 |
+
faulty = True
|
1351 |
+
while faulty:
|
1352 |
+
d = ps.sample(size=(numsamples,) + ((size,) if isinstance(size, int) else size),
|
1353 |
+
library=library, seed=seed) # a dictionary that maps RVs to values
|
1354 |
+
|
1355 |
+
faulty = False
|
1356 |
+
count = 0
|
1357 |
+
while count < numsamples and not faulty:
|
1358 |
+
args = [d[rv][count] for rv in rvs]
|
1359 |
+
if condition is not None: # Check that these values satisfy the condition
|
1360 |
+
# TODO: Replace the try-except block with only given_fn(*args)
|
1361 |
+
# once lambdify works with unevaluated SymPy objects.
|
1362 |
+
try:
|
1363 |
+
gd = given_fn(*args)
|
1364 |
+
except (NameError, TypeError):
|
1365 |
+
gd = given_fn_subs(*args)
|
1366 |
+
if gd != True and gd != False:
|
1367 |
+
raise ValueError(
|
1368 |
+
"Conditions must not contain free symbols")
|
1369 |
+
if not gd: # If the values don't satisfy then try again
|
1370 |
+
faulty = True
|
1371 |
+
|
1372 |
+
count += 1
|
1373 |
+
|
1374 |
+
count = 0
|
1375 |
+
while count < numsamples:
|
1376 |
+
args = [d[rv][count] for rv in rvs]
|
1377 |
+
# TODO: Replace the try-except block with only fn(*args)
|
1378 |
+
# once lambdify works with unevaluated SymPy objects.
|
1379 |
+
try:
|
1380 |
+
yield fn(*args)
|
1381 |
+
except (NameError, TypeError):
|
1382 |
+
yield fn_subs(*args)
|
1383 |
+
count += 1
|
1384 |
+
|
1385 |
+
if numsamples is S.Infinity:
|
1386 |
+
return return_generator_infinite()
|
1387 |
+
|
1388 |
+
return return_generator_finite()
|
1389 |
+
|
1390 |
+
def sample_iter_lambdify(expr, condition=None, size=(),
|
1391 |
+
numsamples=S.Infinity, seed=None, **kwargs):
|
1392 |
+
|
1393 |
+
return sample_iter(expr, condition=condition, size=size,
|
1394 |
+
numsamples=numsamples, seed=seed, **kwargs)
|
1395 |
+
|
1396 |
+
def sample_iter_subs(expr, condition=None, size=(),
|
1397 |
+
numsamples=S.Infinity, seed=None, **kwargs):
|
1398 |
+
|
1399 |
+
return sample_iter(expr, condition=condition, size=size,
|
1400 |
+
numsamples=numsamples, seed=seed, **kwargs)
|
1401 |
+
|
1402 |
+
|
1403 |
+
def sampling_P(condition, given_condition=None, library='scipy', numsamples=1,
|
1404 |
+
evalf=True, seed=None, **kwargs):
|
1405 |
+
"""
|
1406 |
+
Sampling version of P.
|
1407 |
+
|
1408 |
+
See Also
|
1409 |
+
========
|
1410 |
+
|
1411 |
+
P
|
1412 |
+
sampling_E
|
1413 |
+
sampling_density
|
1414 |
+
|
1415 |
+
"""
|
1416 |
+
|
1417 |
+
count_true = 0
|
1418 |
+
count_false = 0
|
1419 |
+
samples = sample_iter(condition, given_condition, library=library,
|
1420 |
+
numsamples=numsamples, seed=seed, **kwargs)
|
1421 |
+
|
1422 |
+
for sample in samples:
|
1423 |
+
if sample:
|
1424 |
+
count_true += 1
|
1425 |
+
else:
|
1426 |
+
count_false += 1
|
1427 |
+
|
1428 |
+
result = S(count_true) / numsamples
|
1429 |
+
if evalf:
|
1430 |
+
return result.evalf()
|
1431 |
+
else:
|
1432 |
+
return result
|
1433 |
+
|
1434 |
+
|
1435 |
+
def sampling_E(expr, given_condition=None, library='scipy', numsamples=1,
|
1436 |
+
evalf=True, seed=None, **kwargs):
|
1437 |
+
"""
|
1438 |
+
Sampling version of E.
|
1439 |
+
|
1440 |
+
See Also
|
1441 |
+
========
|
1442 |
+
|
1443 |
+
P
|
1444 |
+
sampling_P
|
1445 |
+
sampling_density
|
1446 |
+
"""
|
1447 |
+
samples = list(sample_iter(expr, given_condition, library=library,
|
1448 |
+
numsamples=numsamples, seed=seed, **kwargs))
|
1449 |
+
result = Add(*samples) / numsamples
|
1450 |
+
|
1451 |
+
if evalf:
|
1452 |
+
return result.evalf()
|
1453 |
+
else:
|
1454 |
+
return result
|
1455 |
+
|
1456 |
+
def sampling_density(expr, given_condition=None, library='scipy',
|
1457 |
+
numsamples=1, seed=None, **kwargs):
|
1458 |
+
"""
|
1459 |
+
Sampling version of density.
|
1460 |
+
|
1461 |
+
See Also
|
1462 |
+
========
|
1463 |
+
density
|
1464 |
+
sampling_P
|
1465 |
+
sampling_E
|
1466 |
+
"""
|
1467 |
+
|
1468 |
+
results = {}
|
1469 |
+
for result in sample_iter(expr, given_condition, library=library,
|
1470 |
+
numsamples=numsamples, seed=seed, **kwargs):
|
1471 |
+
results[result] = results.get(result, 0) + 1
|
1472 |
+
|
1473 |
+
return results
|
1474 |
+
|
1475 |
+
|
1476 |
+
def dependent(a, b):
|
1477 |
+
"""
|
1478 |
+
Dependence of two random expressions.
|
1479 |
+
|
1480 |
+
Two expressions are independent if knowledge of one does not change
|
1481 |
+
computations on the other.
|
1482 |
+
|
1483 |
+
Examples
|
1484 |
+
========
|
1485 |
+
|
1486 |
+
>>> from sympy.stats import Normal, dependent, given
|
1487 |
+
>>> from sympy import Tuple, Eq
|
1488 |
+
|
1489 |
+
>>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
|
1490 |
+
>>> dependent(X, Y)
|
1491 |
+
False
|
1492 |
+
>>> dependent(2*X + Y, -Y)
|
1493 |
+
True
|
1494 |
+
>>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
|
1495 |
+
>>> dependent(X, Y)
|
1496 |
+
True
|
1497 |
+
|
1498 |
+
See Also
|
1499 |
+
========
|
1500 |
+
|
1501 |
+
independent
|
1502 |
+
"""
|
1503 |
+
if pspace_independent(a, b):
|
1504 |
+
return False
|
1505 |
+
|
1506 |
+
z = Symbol('z', real=True)
|
1507 |
+
# Dependent if density is unchanged when one is given information about
|
1508 |
+
# the other
|
1509 |
+
return (density(a, Eq(b, z)) != density(a) or
|
1510 |
+
density(b, Eq(a, z)) != density(b))
|
1511 |
+
|
1512 |
+
|
1513 |
+
def independent(a, b):
|
1514 |
+
"""
|
1515 |
+
Independence of two random expressions.
|
1516 |
+
|
1517 |
+
Two expressions are independent if knowledge of one does not change
|
1518 |
+
computations on the other.
|
1519 |
+
|
1520 |
+
Examples
|
1521 |
+
========
|
1522 |
+
|
1523 |
+
>>> from sympy.stats import Normal, independent, given
|
1524 |
+
>>> from sympy import Tuple, Eq
|
1525 |
+
|
1526 |
+
>>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
|
1527 |
+
>>> independent(X, Y)
|
1528 |
+
True
|
1529 |
+
>>> independent(2*X + Y, -Y)
|
1530 |
+
False
|
1531 |
+
>>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
|
1532 |
+
>>> independent(X, Y)
|
1533 |
+
False
|
1534 |
+
|
1535 |
+
See Also
|
1536 |
+
========
|
1537 |
+
|
1538 |
+
dependent
|
1539 |
+
"""
|
1540 |
+
return not dependent(a, b)
|
1541 |
+
|
1542 |
+
|
1543 |
+
def pspace_independent(a, b):
|
1544 |
+
"""
|
1545 |
+
Tests for independence between a and b by checking if their PSpaces have
|
1546 |
+
overlapping symbols. This is a sufficient but not necessary condition for
|
1547 |
+
independence and is intended to be used internally.
|
1548 |
+
|
1549 |
+
Notes
|
1550 |
+
=====
|
1551 |
+
|
1552 |
+
pspace_independent(a, b) implies independent(a, b)
|
1553 |
+
independent(a, b) does not imply pspace_independent(a, b)
|
1554 |
+
"""
|
1555 |
+
a_symbols = set(pspace(b).symbols)
|
1556 |
+
b_symbols = set(pspace(a).symbols)
|
1557 |
+
|
1558 |
+
if len(set(random_symbols(a)).intersection(random_symbols(b))) != 0:
|
1559 |
+
return False
|
1560 |
+
|
1561 |
+
if len(a_symbols.intersection(b_symbols)) == 0:
|
1562 |
+
return True
|
1563 |
+
return None
|
1564 |
+
|
1565 |
+
|
1566 |
+
def rv_subs(expr, symbols=None):
|
1567 |
+
"""
|
1568 |
+
Given a random expression replace all random variables with their symbols.
|
1569 |
+
|
1570 |
+
If symbols keyword is given restrict the swap to only the symbols listed.
|
1571 |
+
"""
|
1572 |
+
if symbols is None:
|
1573 |
+
symbols = random_symbols(expr)
|
1574 |
+
if not symbols:
|
1575 |
+
return expr
|
1576 |
+
swapdict = {rv: rv.symbol for rv in symbols}
|
1577 |
+
return expr.subs(swapdict)
|
1578 |
+
|
1579 |
+
|
1580 |
+
class NamedArgsMixin:
|
1581 |
+
_argnames: tuple[str, ...] = ()
|
1582 |
+
|
1583 |
+
def __getattr__(self, attr):
|
1584 |
+
try:
|
1585 |
+
return self.args[self._argnames.index(attr)]
|
1586 |
+
except ValueError:
|
1587 |
+
raise AttributeError("'%s' object has no attribute '%s'" % (
|
1588 |
+
type(self).__name__, attr))
|
1589 |
+
|
1590 |
+
|
1591 |
+
class Distribution(Basic):
|
1592 |
+
|
1593 |
+
def sample(self, size=(), library='scipy', seed=None):
|
1594 |
+
""" A random realization from the distribution """
|
1595 |
+
|
1596 |
+
module = import_module(library)
|
1597 |
+
if library in {'scipy', 'numpy', 'pymc3', 'pymc'} and module is None:
|
1598 |
+
raise ValueError("Failed to import %s" % library)
|
1599 |
+
|
1600 |
+
if library == 'scipy':
|
1601 |
+
# scipy does not require map as it can handle using custom distributions.
|
1602 |
+
# However, we will still use a map where we can.
|
1603 |
+
|
1604 |
+
# TODO: do this for drv.py and frv.py if necessary.
|
1605 |
+
# TODO: add more distributions here if there are more
|
1606 |
+
# See links below referring to sections beginning with "A common parametrization..."
|
1607 |
+
# I will remove all these comments if everything is ok.
|
1608 |
+
|
1609 |
+
from sympy.stats.sampling.sample_scipy import do_sample_scipy
|
1610 |
+
import numpy
|
1611 |
+
if seed is None or isinstance(seed, int):
|
1612 |
+
rand_state = numpy.random.default_rng(seed=seed)
|
1613 |
+
else:
|
1614 |
+
rand_state = seed
|
1615 |
+
samps = do_sample_scipy(self, size, rand_state)
|
1616 |
+
|
1617 |
+
elif library == 'numpy':
|
1618 |
+
from sympy.stats.sampling.sample_numpy import do_sample_numpy
|
1619 |
+
import numpy
|
1620 |
+
if seed is None or isinstance(seed, int):
|
1621 |
+
rand_state = numpy.random.default_rng(seed=seed)
|
1622 |
+
else:
|
1623 |
+
rand_state = seed
|
1624 |
+
_size = None if size == () else size
|
1625 |
+
samps = do_sample_numpy(self, _size, rand_state)
|
1626 |
+
elif library in ('pymc', 'pymc3'):
|
1627 |
+
from sympy.stats.sampling.sample_pymc import do_sample_pymc
|
1628 |
+
import logging
|
1629 |
+
logging.getLogger("pymc").setLevel(logging.ERROR)
|
1630 |
+
try:
|
1631 |
+
import pymc
|
1632 |
+
except ImportError:
|
1633 |
+
import pymc3 as pymc
|
1634 |
+
|
1635 |
+
with pymc.Model():
|
1636 |
+
if do_sample_pymc(self):
|
1637 |
+
samps = pymc.sample(draws=prod(size), chains=1, compute_convergence_checks=False,
|
1638 |
+
progressbar=False, random_seed=seed, return_inferencedata=False)[:]['X']
|
1639 |
+
samps = samps.reshape(size)
|
1640 |
+
else:
|
1641 |
+
samps = None
|
1642 |
+
|
1643 |
+
else:
|
1644 |
+
raise NotImplementedError("Sampling from %s is not supported yet."
|
1645 |
+
% str(library))
|
1646 |
+
|
1647 |
+
if samps is not None:
|
1648 |
+
return samps
|
1649 |
+
raise NotImplementedError(
|
1650 |
+
"Sampling for %s is not currently implemented from %s"
|
1651 |
+
% (self, library))
|
1652 |
+
|
1653 |
+
|
1654 |
+
def _value_check(condition, message):
|
1655 |
+
"""
|
1656 |
+
Raise a ValueError with message if condition is False, else
|
1657 |
+
return True if all conditions were True, else False.
|
1658 |
+
|
1659 |
+
Examples
|
1660 |
+
========
|
1661 |
+
|
1662 |
+
>>> from sympy.stats.rv import _value_check
|
1663 |
+
>>> from sympy.abc import a, b, c
|
1664 |
+
>>> from sympy import And, Dummy
|
1665 |
+
|
1666 |
+
>>> _value_check(2 < 3, '')
|
1667 |
+
True
|
1668 |
+
|
1669 |
+
Here, the condition is not False, but it does not evaluate to True
|
1670 |
+
so False is returned (but no error is raised). So checking if the
|
1671 |
+
return value is True or False will tell you if all conditions were
|
1672 |
+
evaluated.
|
1673 |
+
|
1674 |
+
>>> _value_check(a < b, '')
|
1675 |
+
False
|
1676 |
+
|
1677 |
+
In this case the condition is False so an error is raised:
|
1678 |
+
|
1679 |
+
>>> r = Dummy(real=True)
|
1680 |
+
>>> _value_check(r < r - 1, 'condition is not true')
|
1681 |
+
Traceback (most recent call last):
|
1682 |
+
...
|
1683 |
+
ValueError: condition is not true
|
1684 |
+
|
1685 |
+
If no condition of many conditions must be False, they can be
|
1686 |
+
checked by passing them as an iterable:
|
1687 |
+
|
1688 |
+
>>> _value_check((a < 0, b < 0, c < 0), '')
|
1689 |
+
False
|
1690 |
+
|
1691 |
+
The iterable can be a generator, too:
|
1692 |
+
|
1693 |
+
>>> _value_check((i < 0 for i in (a, b, c)), '')
|
1694 |
+
False
|
1695 |
+
|
1696 |
+
The following are equivalent to the above but do not pass
|
1697 |
+
an iterable:
|
1698 |
+
|
1699 |
+
>>> all(_value_check(i < 0, '') for i in (a, b, c))
|
1700 |
+
False
|
1701 |
+
>>> _value_check(And(a < 0, b < 0, c < 0), '')
|
1702 |
+
False
|
1703 |
+
"""
|
1704 |
+
if not iterable(condition):
|
1705 |
+
condition = [condition]
|
1706 |
+
truth = fuzzy_and(condition)
|
1707 |
+
if truth == False:
|
1708 |
+
raise ValueError(message)
|
1709 |
+
return truth == True
|
1710 |
+
|
1711 |
+
def _symbol_converter(sym):
|
1712 |
+
"""
|
1713 |
+
Casts the parameter to Symbol if it is 'str'
|
1714 |
+
otherwise no operation is performed on it.
|
1715 |
+
|
1716 |
+
Parameters
|
1717 |
+
==========
|
1718 |
+
|
1719 |
+
sym
|
1720 |
+
The parameter to be converted.
|
1721 |
+
|
1722 |
+
Returns
|
1723 |
+
=======
|
1724 |
+
|
1725 |
+
Symbol
|
1726 |
+
the parameter converted to Symbol.
|
1727 |
+
|
1728 |
+
Raises
|
1729 |
+
======
|
1730 |
+
|
1731 |
+
TypeError
|
1732 |
+
If the parameter is not an instance of both str and
|
1733 |
+
Symbol.
|
1734 |
+
|
1735 |
+
Examples
|
1736 |
+
========
|
1737 |
+
|
1738 |
+
>>> from sympy import Symbol
|
1739 |
+
>>> from sympy.stats.rv import _symbol_converter
|
1740 |
+
>>> s = _symbol_converter('s')
|
1741 |
+
>>> isinstance(s, Symbol)
|
1742 |
+
True
|
1743 |
+
>>> _symbol_converter(1)
|
1744 |
+
Traceback (most recent call last):
|
1745 |
+
...
|
1746 |
+
TypeError: 1 is neither a Symbol nor a string
|
1747 |
+
>>> r = Symbol('r')
|
1748 |
+
>>> isinstance(r, Symbol)
|
1749 |
+
True
|
1750 |
+
"""
|
1751 |
+
if isinstance(sym, str):
|
1752 |
+
sym = Symbol(sym)
|
1753 |
+
if not isinstance(sym, Symbol):
|
1754 |
+
raise TypeError("%s is neither a Symbol nor a string"%(sym))
|
1755 |
+
return sym
|
1756 |
+
|
1757 |
+
def sample_stochastic_process(process):
|
1758 |
+
"""
|
1759 |
+
This function is used to sample from stochastic process.
|
1760 |
+
|
1761 |
+
Parameters
|
1762 |
+
==========
|
1763 |
+
|
1764 |
+
process: StochasticProcess
|
1765 |
+
Process used to extract the samples. It must be an instance of
|
1766 |
+
StochasticProcess
|
1767 |
+
|
1768 |
+
Examples
|
1769 |
+
========
|
1770 |
+
|
1771 |
+
>>> from sympy.stats import sample_stochastic_process, DiscreteMarkovChain
|
1772 |
+
>>> from sympy import Matrix
|
1773 |
+
>>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
|
1774 |
+
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
|
1775 |
+
>>> next(sample_stochastic_process(Y)) in Y.state_space
|
1776 |
+
True
|
1777 |
+
>>> next(sample_stochastic_process(Y)) # doctest: +SKIP
|
1778 |
+
0
|
1779 |
+
>>> next(sample_stochastic_process(Y)) # doctest: +SKIP
|
1780 |
+
2
|
1781 |
+
|
1782 |
+
Returns
|
1783 |
+
=======
|
1784 |
+
|
1785 |
+
sample: iterator object
|
1786 |
+
iterator object containing the sample of given process
|
1787 |
+
|
1788 |
+
"""
|
1789 |
+
from sympy.stats.stochastic_process_types import StochasticProcess
|
1790 |
+
if not isinstance(process, StochasticProcess):
|
1791 |
+
raise ValueError("Process must be an instance of Stochastic Process")
|
1792 |
+
return process.sample()
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/rv_interface.py
ADDED
@@ -0,0 +1,519 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.sets import FiniteSet
|
2 |
+
from sympy.core.numbers import Rational
|
3 |
+
from sympy.core.relational import Eq
|
4 |
+
from sympy.core.symbol import Dummy
|
5 |
+
from sympy.functions.combinatorial.factorials import FallingFactorial
|
6 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
7 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
8 |
+
from sympy.functions.elementary.piecewise import piecewise_fold
|
9 |
+
from sympy.integrals.integrals import Integral
|
10 |
+
from sympy.solvers.solveset import solveset
|
11 |
+
from .rv import (probability, expectation, density, where, given, pspace, cdf, PSpace,
|
12 |
+
characteristic_function, sample, sample_iter, random_symbols, independent, dependent,
|
13 |
+
sampling_density, moment_generating_function, quantile, is_random,
|
14 |
+
sample_stochastic_process)
|
15 |
+
|
16 |
+
|
17 |
+
__all__ = ['P', 'E', 'H', 'density', 'where', 'given', 'sample', 'cdf',
|
18 |
+
'characteristic_function', 'pspace', 'sample_iter', 'variance', 'std',
|
19 |
+
'skewness', 'kurtosis', 'covariance', 'dependent', 'entropy', 'median',
|
20 |
+
'independent', 'random_symbols', 'correlation', 'factorial_moment',
|
21 |
+
'moment', 'cmoment', 'sampling_density', 'moment_generating_function',
|
22 |
+
'smoment', 'quantile', 'sample_stochastic_process']
|
23 |
+
|
24 |
+
|
25 |
+
|
26 |
+
def moment(X, n, c=0, condition=None, *, evaluate=True, **kwargs):
|
27 |
+
"""
|
28 |
+
Return the nth moment of a random expression about c.
|
29 |
+
|
30 |
+
.. math::
|
31 |
+
moment(X, c, n) = E((X-c)^{n})
|
32 |
+
|
33 |
+
Default value of c is 0.
|
34 |
+
|
35 |
+
Examples
|
36 |
+
========
|
37 |
+
|
38 |
+
>>> from sympy.stats import Die, moment, E
|
39 |
+
>>> X = Die('X', 6)
|
40 |
+
>>> moment(X, 1, 6)
|
41 |
+
-5/2
|
42 |
+
>>> moment(X, 2)
|
43 |
+
91/6
|
44 |
+
>>> moment(X, 1) == E(X)
|
45 |
+
True
|
46 |
+
"""
|
47 |
+
from sympy.stats.symbolic_probability import Moment
|
48 |
+
if evaluate:
|
49 |
+
return Moment(X, n, c, condition).doit()
|
50 |
+
return Moment(X, n, c, condition).rewrite(Integral)
|
51 |
+
|
52 |
+
|
53 |
+
def variance(X, condition=None, **kwargs):
|
54 |
+
"""
|
55 |
+
Variance of a random expression.
|
56 |
+
|
57 |
+
.. math::
|
58 |
+
variance(X) = E((X-E(X))^{2})
|
59 |
+
|
60 |
+
Examples
|
61 |
+
========
|
62 |
+
|
63 |
+
>>> from sympy.stats import Die, Bernoulli, variance
|
64 |
+
>>> from sympy import simplify, Symbol
|
65 |
+
|
66 |
+
>>> X = Die('X', 6)
|
67 |
+
>>> p = Symbol('p')
|
68 |
+
>>> B = Bernoulli('B', p, 1, 0)
|
69 |
+
|
70 |
+
>>> variance(2*X)
|
71 |
+
35/3
|
72 |
+
|
73 |
+
>>> simplify(variance(B))
|
74 |
+
p*(1 - p)
|
75 |
+
"""
|
76 |
+
if is_random(X) and pspace(X) == PSpace():
|
77 |
+
from sympy.stats.symbolic_probability import Variance
|
78 |
+
return Variance(X, condition)
|
79 |
+
|
80 |
+
return cmoment(X, 2, condition, **kwargs)
|
81 |
+
|
82 |
+
|
83 |
+
def standard_deviation(X, condition=None, **kwargs):
|
84 |
+
r"""
|
85 |
+
Standard Deviation of a random expression
|
86 |
+
|
87 |
+
.. math::
|
88 |
+
std(X) = \sqrt(E((X-E(X))^{2}))
|
89 |
+
|
90 |
+
Examples
|
91 |
+
========
|
92 |
+
|
93 |
+
>>> from sympy.stats import Bernoulli, std
|
94 |
+
>>> from sympy import Symbol, simplify
|
95 |
+
|
96 |
+
>>> p = Symbol('p')
|
97 |
+
>>> B = Bernoulli('B', p, 1, 0)
|
98 |
+
|
99 |
+
>>> simplify(std(B))
|
100 |
+
sqrt(p*(1 - p))
|
101 |
+
"""
|
102 |
+
return sqrt(variance(X, condition, **kwargs))
|
103 |
+
std = standard_deviation
|
104 |
+
|
105 |
+
def entropy(expr, condition=None, **kwargs):
|
106 |
+
"""
|
107 |
+
Calculuates entropy of a probability distribution.
|
108 |
+
|
109 |
+
Parameters
|
110 |
+
==========
|
111 |
+
|
112 |
+
expression : the random expression whose entropy is to be calculated
|
113 |
+
condition : optional, to specify conditions on random expression
|
114 |
+
b: base of the logarithm, optional
|
115 |
+
By default, it is taken as Euler's number
|
116 |
+
|
117 |
+
Returns
|
118 |
+
=======
|
119 |
+
|
120 |
+
result : Entropy of the expression, a constant
|
121 |
+
|
122 |
+
Examples
|
123 |
+
========
|
124 |
+
|
125 |
+
>>> from sympy.stats import Normal, Die, entropy
|
126 |
+
>>> X = Normal('X', 0, 1)
|
127 |
+
>>> entropy(X)
|
128 |
+
log(2)/2 + 1/2 + log(pi)/2
|
129 |
+
|
130 |
+
>>> D = Die('D', 4)
|
131 |
+
>>> entropy(D)
|
132 |
+
log(4)
|
133 |
+
|
134 |
+
References
|
135 |
+
==========
|
136 |
+
|
137 |
+
.. [1] https://en.wikipedia.org/wiki/Entropy_%28information_theory%29
|
138 |
+
.. [2] https://www.crmarsh.com/static/pdf/Charles_Marsh_Continuous_Entropy.pdf
|
139 |
+
.. [3] https://kconrad.math.uconn.edu/blurbs/analysis/entropypost.pdf
|
140 |
+
"""
|
141 |
+
pdf = density(expr, condition, **kwargs)
|
142 |
+
base = kwargs.get('b', exp(1))
|
143 |
+
if isinstance(pdf, dict):
|
144 |
+
return sum([-prob*log(prob, base) for prob in pdf.values()])
|
145 |
+
return expectation(-log(pdf(expr), base))
|
146 |
+
|
147 |
+
def covariance(X, Y, condition=None, **kwargs):
|
148 |
+
"""
|
149 |
+
Covariance of two random expressions.
|
150 |
+
|
151 |
+
Explanation
|
152 |
+
===========
|
153 |
+
|
154 |
+
The expectation that the two variables will rise and fall together
|
155 |
+
|
156 |
+
.. math::
|
157 |
+
covariance(X,Y) = E((X-E(X)) (Y-E(Y)))
|
158 |
+
|
159 |
+
Examples
|
160 |
+
========
|
161 |
+
|
162 |
+
>>> from sympy.stats import Exponential, covariance
|
163 |
+
>>> from sympy import Symbol
|
164 |
+
|
165 |
+
>>> rate = Symbol('lambda', positive=True, real=True)
|
166 |
+
>>> X = Exponential('X', rate)
|
167 |
+
>>> Y = Exponential('Y', rate)
|
168 |
+
|
169 |
+
>>> covariance(X, X)
|
170 |
+
lambda**(-2)
|
171 |
+
>>> covariance(X, Y)
|
172 |
+
0
|
173 |
+
>>> covariance(X, Y + rate*X)
|
174 |
+
1/lambda
|
175 |
+
"""
|
176 |
+
if (is_random(X) and pspace(X) == PSpace()) or (is_random(Y) and pspace(Y) == PSpace()):
|
177 |
+
from sympy.stats.symbolic_probability import Covariance
|
178 |
+
return Covariance(X, Y, condition)
|
179 |
+
|
180 |
+
return expectation(
|
181 |
+
(X - expectation(X, condition, **kwargs)) *
|
182 |
+
(Y - expectation(Y, condition, **kwargs)),
|
183 |
+
condition, **kwargs)
|
184 |
+
|
185 |
+
|
186 |
+
def correlation(X, Y, condition=None, **kwargs):
|
187 |
+
r"""
|
188 |
+
Correlation of two random expressions, also known as correlation
|
189 |
+
coefficient or Pearson's correlation.
|
190 |
+
|
191 |
+
Explanation
|
192 |
+
===========
|
193 |
+
|
194 |
+
The normalized expectation that the two variables will rise
|
195 |
+
and fall together
|
196 |
+
|
197 |
+
.. math::
|
198 |
+
correlation(X,Y) = E((X-E(X))(Y-E(Y)) / (\sigma_x \sigma_y))
|
199 |
+
|
200 |
+
Examples
|
201 |
+
========
|
202 |
+
|
203 |
+
>>> from sympy.stats import Exponential, correlation
|
204 |
+
>>> from sympy import Symbol
|
205 |
+
|
206 |
+
>>> rate = Symbol('lambda', positive=True, real=True)
|
207 |
+
>>> X = Exponential('X', rate)
|
208 |
+
>>> Y = Exponential('Y', rate)
|
209 |
+
|
210 |
+
>>> correlation(X, X)
|
211 |
+
1
|
212 |
+
>>> correlation(X, Y)
|
213 |
+
0
|
214 |
+
>>> correlation(X, Y + rate*X)
|
215 |
+
1/sqrt(1 + lambda**(-2))
|
216 |
+
"""
|
217 |
+
return covariance(X, Y, condition, **kwargs)/(std(X, condition, **kwargs)
|
218 |
+
* std(Y, condition, **kwargs))
|
219 |
+
|
220 |
+
|
221 |
+
def cmoment(X, n, condition=None, *, evaluate=True, **kwargs):
|
222 |
+
"""
|
223 |
+
Return the nth central moment of a random expression about its mean.
|
224 |
+
|
225 |
+
.. math::
|
226 |
+
cmoment(X, n) = E((X - E(X))^{n})
|
227 |
+
|
228 |
+
Examples
|
229 |
+
========
|
230 |
+
|
231 |
+
>>> from sympy.stats import Die, cmoment, variance
|
232 |
+
>>> X = Die('X', 6)
|
233 |
+
>>> cmoment(X, 3)
|
234 |
+
0
|
235 |
+
>>> cmoment(X, 2)
|
236 |
+
35/12
|
237 |
+
>>> cmoment(X, 2) == variance(X)
|
238 |
+
True
|
239 |
+
"""
|
240 |
+
from sympy.stats.symbolic_probability import CentralMoment
|
241 |
+
if evaluate:
|
242 |
+
return CentralMoment(X, n, condition).doit()
|
243 |
+
return CentralMoment(X, n, condition).rewrite(Integral)
|
244 |
+
|
245 |
+
|
246 |
+
def smoment(X, n, condition=None, **kwargs):
|
247 |
+
r"""
|
248 |
+
Return the nth Standardized moment of a random expression.
|
249 |
+
|
250 |
+
.. math::
|
251 |
+
smoment(X, n) = E(((X - \mu)/\sigma_X)^{n})
|
252 |
+
|
253 |
+
Examples
|
254 |
+
========
|
255 |
+
|
256 |
+
>>> from sympy.stats import skewness, Exponential, smoment
|
257 |
+
>>> from sympy import Symbol
|
258 |
+
>>> rate = Symbol('lambda', positive=True, real=True)
|
259 |
+
>>> Y = Exponential('Y', rate)
|
260 |
+
>>> smoment(Y, 4)
|
261 |
+
9
|
262 |
+
>>> smoment(Y, 4) == smoment(3*Y, 4)
|
263 |
+
True
|
264 |
+
>>> smoment(Y, 3) == skewness(Y)
|
265 |
+
True
|
266 |
+
"""
|
267 |
+
sigma = std(X, condition, **kwargs)
|
268 |
+
return (1/sigma)**n*cmoment(X, n, condition, **kwargs)
|
269 |
+
|
270 |
+
def skewness(X, condition=None, **kwargs):
|
271 |
+
r"""
|
272 |
+
Measure of the asymmetry of the probability distribution.
|
273 |
+
|
274 |
+
Explanation
|
275 |
+
===========
|
276 |
+
|
277 |
+
Positive skew indicates that most of the values lie to the right of
|
278 |
+
the mean.
|
279 |
+
|
280 |
+
.. math::
|
281 |
+
skewness(X) = E(((X - E(X))/\sigma_X)^{3})
|
282 |
+
|
283 |
+
Parameters
|
284 |
+
==========
|
285 |
+
|
286 |
+
condition : Expr containing RandomSymbols
|
287 |
+
A conditional expression. skewness(X, X>0) is skewness of X given X > 0
|
288 |
+
|
289 |
+
Examples
|
290 |
+
========
|
291 |
+
|
292 |
+
>>> from sympy.stats import skewness, Exponential, Normal
|
293 |
+
>>> from sympy import Symbol
|
294 |
+
>>> X = Normal('X', 0, 1)
|
295 |
+
>>> skewness(X)
|
296 |
+
0
|
297 |
+
>>> skewness(X, X > 0) # find skewness given X > 0
|
298 |
+
(-sqrt(2)/sqrt(pi) + 4*sqrt(2)/pi**(3/2))/(1 - 2/pi)**(3/2)
|
299 |
+
|
300 |
+
>>> rate = Symbol('lambda', positive=True, real=True)
|
301 |
+
>>> Y = Exponential('Y', rate)
|
302 |
+
>>> skewness(Y)
|
303 |
+
2
|
304 |
+
"""
|
305 |
+
return smoment(X, 3, condition=condition, **kwargs)
|
306 |
+
|
307 |
+
def kurtosis(X, condition=None, **kwargs):
|
308 |
+
r"""
|
309 |
+
Characterizes the tails/outliers of a probability distribution.
|
310 |
+
|
311 |
+
Explanation
|
312 |
+
===========
|
313 |
+
|
314 |
+
Kurtosis of any univariate normal distribution is 3. Kurtosis less than
|
315 |
+
3 means that the distribution produces fewer and less extreme outliers
|
316 |
+
than the normal distribution.
|
317 |
+
|
318 |
+
.. math::
|
319 |
+
kurtosis(X) = E(((X - E(X))/\sigma_X)^{4})
|
320 |
+
|
321 |
+
Parameters
|
322 |
+
==========
|
323 |
+
|
324 |
+
condition : Expr containing RandomSymbols
|
325 |
+
A conditional expression. kurtosis(X, X>0) is kurtosis of X given X > 0
|
326 |
+
|
327 |
+
Examples
|
328 |
+
========
|
329 |
+
|
330 |
+
>>> from sympy.stats import kurtosis, Exponential, Normal
|
331 |
+
>>> from sympy import Symbol
|
332 |
+
>>> X = Normal('X', 0, 1)
|
333 |
+
>>> kurtosis(X)
|
334 |
+
3
|
335 |
+
>>> kurtosis(X, X > 0) # find kurtosis given X > 0
|
336 |
+
(-4/pi - 12/pi**2 + 3)/(1 - 2/pi)**2
|
337 |
+
|
338 |
+
>>> rate = Symbol('lamda', positive=True, real=True)
|
339 |
+
>>> Y = Exponential('Y', rate)
|
340 |
+
>>> kurtosis(Y)
|
341 |
+
9
|
342 |
+
|
343 |
+
References
|
344 |
+
==========
|
345 |
+
|
346 |
+
.. [1] https://en.wikipedia.org/wiki/Kurtosis
|
347 |
+
.. [2] https://mathworld.wolfram.com/Kurtosis.html
|
348 |
+
"""
|
349 |
+
return smoment(X, 4, condition=condition, **kwargs)
|
350 |
+
|
351 |
+
|
352 |
+
def factorial_moment(X, n, condition=None, **kwargs):
|
353 |
+
"""
|
354 |
+
The factorial moment is a mathematical quantity defined as the expectation
|
355 |
+
or average of the falling factorial of a random variable.
|
356 |
+
|
357 |
+
.. math::
|
358 |
+
factorial-moment(X, n) = E(X(X - 1)(X - 2)...(X - n + 1))
|
359 |
+
|
360 |
+
Parameters
|
361 |
+
==========
|
362 |
+
|
363 |
+
n: A natural number, n-th factorial moment.
|
364 |
+
|
365 |
+
condition : Expr containing RandomSymbols
|
366 |
+
A conditional expression.
|
367 |
+
|
368 |
+
Examples
|
369 |
+
========
|
370 |
+
|
371 |
+
>>> from sympy.stats import factorial_moment, Poisson, Binomial
|
372 |
+
>>> from sympy import Symbol, S
|
373 |
+
>>> lamda = Symbol('lamda')
|
374 |
+
>>> X = Poisson('X', lamda)
|
375 |
+
>>> factorial_moment(X, 2)
|
376 |
+
lamda**2
|
377 |
+
>>> Y = Binomial('Y', 2, S.Half)
|
378 |
+
>>> factorial_moment(Y, 2)
|
379 |
+
1/2
|
380 |
+
>>> factorial_moment(Y, 2, Y > 1) # find factorial moment for Y > 1
|
381 |
+
2
|
382 |
+
|
383 |
+
References
|
384 |
+
==========
|
385 |
+
|
386 |
+
.. [1] https://en.wikipedia.org/wiki/Factorial_moment
|
387 |
+
.. [2] https://mathworld.wolfram.com/FactorialMoment.html
|
388 |
+
"""
|
389 |
+
return expectation(FallingFactorial(X, n), condition=condition, **kwargs)
|
390 |
+
|
391 |
+
def median(X, evaluate=True, **kwargs):
|
392 |
+
r"""
|
393 |
+
Calculuates the median of the probability distribution.
|
394 |
+
|
395 |
+
Explanation
|
396 |
+
===========
|
397 |
+
|
398 |
+
Mathematically, median of Probability distribution is defined as all those
|
399 |
+
values of `m` for which the following condition is satisfied
|
400 |
+
|
401 |
+
.. math::
|
402 |
+
P(X\leq m) \geq \frac{1}{2} \text{ and} \text{ } P(X\geq m)\geq \frac{1}{2}
|
403 |
+
|
404 |
+
Parameters
|
405 |
+
==========
|
406 |
+
|
407 |
+
X: The random expression whose median is to be calculated.
|
408 |
+
|
409 |
+
Returns
|
410 |
+
=======
|
411 |
+
|
412 |
+
The FiniteSet or an Interval which contains the median of the
|
413 |
+
random expression.
|
414 |
+
|
415 |
+
Examples
|
416 |
+
========
|
417 |
+
|
418 |
+
>>> from sympy.stats import Normal, Die, median
|
419 |
+
>>> N = Normal('N', 3, 1)
|
420 |
+
>>> median(N)
|
421 |
+
{3}
|
422 |
+
>>> D = Die('D')
|
423 |
+
>>> median(D)
|
424 |
+
{3, 4}
|
425 |
+
|
426 |
+
References
|
427 |
+
==========
|
428 |
+
|
429 |
+
.. [1] https://en.wikipedia.org/wiki/Median#Probability_distributions
|
430 |
+
|
431 |
+
"""
|
432 |
+
if not is_random(X):
|
433 |
+
return X
|
434 |
+
|
435 |
+
from sympy.stats.crv import ContinuousPSpace
|
436 |
+
from sympy.stats.drv import DiscretePSpace
|
437 |
+
from sympy.stats.frv import FinitePSpace
|
438 |
+
|
439 |
+
if isinstance(pspace(X), FinitePSpace):
|
440 |
+
cdf = pspace(X).compute_cdf(X)
|
441 |
+
result = []
|
442 |
+
for key, value in cdf.items():
|
443 |
+
if value>= Rational(1, 2) and (1 - value) + \
|
444 |
+
pspace(X).probability(Eq(X, key)) >= Rational(1, 2):
|
445 |
+
result.append(key)
|
446 |
+
return FiniteSet(*result)
|
447 |
+
if isinstance(pspace(X), (ContinuousPSpace, DiscretePSpace)):
|
448 |
+
cdf = pspace(X).compute_cdf(X)
|
449 |
+
x = Dummy('x')
|
450 |
+
result = solveset(piecewise_fold(cdf(x) - Rational(1, 2)), x, pspace(X).set)
|
451 |
+
return result
|
452 |
+
raise NotImplementedError("The median of %s is not implemented."%str(pspace(X)))
|
453 |
+
|
454 |
+
|
455 |
+
def coskewness(X, Y, Z, condition=None, **kwargs):
|
456 |
+
r"""
|
457 |
+
Calculates the co-skewness of three random variables.
|
458 |
+
|
459 |
+
Explanation
|
460 |
+
===========
|
461 |
+
|
462 |
+
Mathematically Coskewness is defined as
|
463 |
+
|
464 |
+
.. math::
|
465 |
+
coskewness(X,Y,Z)=\frac{E[(X-E[X]) * (Y-E[Y]) * (Z-E[Z])]} {\sigma_{X}\sigma_{Y}\sigma_{Z}}
|
466 |
+
|
467 |
+
Parameters
|
468 |
+
==========
|
469 |
+
|
470 |
+
X : RandomSymbol
|
471 |
+
Random Variable used to calculate coskewness
|
472 |
+
Y : RandomSymbol
|
473 |
+
Random Variable used to calculate coskewness
|
474 |
+
Z : RandomSymbol
|
475 |
+
Random Variable used to calculate coskewness
|
476 |
+
condition : Expr containing RandomSymbols
|
477 |
+
A conditional expression
|
478 |
+
|
479 |
+
Examples
|
480 |
+
========
|
481 |
+
|
482 |
+
>>> from sympy.stats import coskewness, Exponential, skewness
|
483 |
+
>>> from sympy import symbols
|
484 |
+
>>> p = symbols('p', positive=True)
|
485 |
+
>>> X = Exponential('X', p)
|
486 |
+
>>> Y = Exponential('Y', 2*p)
|
487 |
+
>>> coskewness(X, Y, Y)
|
488 |
+
0
|
489 |
+
>>> coskewness(X, Y + X, Y + 2*X)
|
490 |
+
16*sqrt(85)/85
|
491 |
+
>>> coskewness(X + 2*Y, Y + X, Y + 2*X, X > 3)
|
492 |
+
9*sqrt(170)/85
|
493 |
+
>>> coskewness(Y, Y, Y) == skewness(Y)
|
494 |
+
True
|
495 |
+
>>> coskewness(X, Y + p*X, Y + 2*p*X)
|
496 |
+
4/(sqrt(1 + 1/(4*p**2))*sqrt(4 + 1/(4*p**2)))
|
497 |
+
|
498 |
+
Returns
|
499 |
+
=======
|
500 |
+
|
501 |
+
coskewness : The coskewness of the three random variables
|
502 |
+
|
503 |
+
References
|
504 |
+
==========
|
505 |
+
|
506 |
+
.. [1] https://en.wikipedia.org/wiki/Coskewness
|
507 |
+
|
508 |
+
"""
|
509 |
+
num = expectation((X - expectation(X, condition, **kwargs)) \
|
510 |
+
* (Y - expectation(Y, condition, **kwargs)) \
|
511 |
+
* (Z - expectation(Z, condition, **kwargs)), condition, **kwargs)
|
512 |
+
den = std(X, condition, **kwargs) * std(Y, condition, **kwargs) \
|
513 |
+
* std(Z, condition, **kwargs)
|
514 |
+
return num/den
|
515 |
+
|
516 |
+
|
517 |
+
P = probability
|
518 |
+
E = expectation
|
519 |
+
H = entropy
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (185 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_numpy.cpython-310.pyc
ADDED
Binary file (3.93 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_pymc.cpython-310.pyc
ADDED
Binary file (3.36 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_scipy.cpython-310.pyc
ADDED
Binary file (5.81 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/sample_numpy.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import singledispatch
|
2 |
+
|
3 |
+
from sympy.external import import_module
|
4 |
+
from sympy.stats.crv_types import BetaDistribution, ChiSquaredDistribution, ExponentialDistribution, GammaDistribution, \
|
5 |
+
LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution, FDistributionDistribution, GumbelDistribution, LaplaceDistribution, \
|
6 |
+
LogisticDistribution, RayleighDistribution, TriangularDistribution
|
7 |
+
from sympy.stats.drv_types import GeometricDistribution, PoissonDistribution, ZetaDistribution
|
8 |
+
from sympy.stats.frv_types import BinomialDistribution, HypergeometricDistribution
|
9 |
+
|
10 |
+
|
11 |
+
numpy = import_module('numpy')
|
12 |
+
|
13 |
+
|
14 |
+
@singledispatch
|
15 |
+
def do_sample_numpy(dist, size, rand_state):
|
16 |
+
return None
|
17 |
+
|
18 |
+
|
19 |
+
# CRV:
|
20 |
+
|
21 |
+
@do_sample_numpy.register(BetaDistribution)
|
22 |
+
def _(dist: BetaDistribution, size, rand_state):
|
23 |
+
return rand_state.beta(a=float(dist.alpha), b=float(dist.beta), size=size)
|
24 |
+
|
25 |
+
|
26 |
+
@do_sample_numpy.register(ChiSquaredDistribution)
|
27 |
+
def _(dist: ChiSquaredDistribution, size, rand_state):
|
28 |
+
return rand_state.chisquare(df=float(dist.k), size=size)
|
29 |
+
|
30 |
+
|
31 |
+
@do_sample_numpy.register(ExponentialDistribution)
|
32 |
+
def _(dist: ExponentialDistribution, size, rand_state):
|
33 |
+
return rand_state.exponential(1 / float(dist.rate), size=size)
|
34 |
+
|
35 |
+
@do_sample_numpy.register(FDistributionDistribution)
|
36 |
+
def _(dist: FDistributionDistribution, size, rand_state):
|
37 |
+
return rand_state.f(dfnum = float(dist.d1), dfden = float(dist.d2), size=size)
|
38 |
+
|
39 |
+
@do_sample_numpy.register(GammaDistribution)
|
40 |
+
def _(dist: GammaDistribution, size, rand_state):
|
41 |
+
return rand_state.gamma(shape = float(dist.k), scale = float(dist.theta), size=size)
|
42 |
+
|
43 |
+
@do_sample_numpy.register(GumbelDistribution)
|
44 |
+
def _(dist: GumbelDistribution, size, rand_state):
|
45 |
+
return rand_state.gumbel(loc = float(dist.mu), scale = float(dist.beta), size=size)
|
46 |
+
|
47 |
+
@do_sample_numpy.register(LaplaceDistribution)
|
48 |
+
def _(dist: LaplaceDistribution, size, rand_state):
|
49 |
+
return rand_state.laplace(loc = float(dist.mu), scale = float(dist.b), size=size)
|
50 |
+
|
51 |
+
@do_sample_numpy.register(LogisticDistribution)
|
52 |
+
def _(dist: LogisticDistribution, size, rand_state):
|
53 |
+
return rand_state.logistic(loc = float(dist.mu), scale = float(dist.s), size=size)
|
54 |
+
|
55 |
+
@do_sample_numpy.register(LogNormalDistribution)
|
56 |
+
def _(dist: LogNormalDistribution, size, rand_state):
|
57 |
+
return rand_state.lognormal(mean = float(dist.mean), sigma = float(dist.std), size=size)
|
58 |
+
|
59 |
+
@do_sample_numpy.register(NormalDistribution)
|
60 |
+
def _(dist: NormalDistribution, size, rand_state):
|
61 |
+
return rand_state.normal(loc = float(dist.mean), scale = float(dist.std), size=size)
|
62 |
+
|
63 |
+
@do_sample_numpy.register(RayleighDistribution)
|
64 |
+
def _(dist: RayleighDistribution, size, rand_state):
|
65 |
+
return rand_state.rayleigh(scale = float(dist.sigma), size=size)
|
66 |
+
|
67 |
+
@do_sample_numpy.register(ParetoDistribution)
|
68 |
+
def _(dist: ParetoDistribution, size, rand_state):
|
69 |
+
return (numpy.random.pareto(a=float(dist.alpha), size=size) + 1) * float(dist.xm)
|
70 |
+
|
71 |
+
@do_sample_numpy.register(TriangularDistribution)
|
72 |
+
def _(dist: TriangularDistribution, size, rand_state):
|
73 |
+
return rand_state.triangular(left = float(dist.a), mode = float(dist.b), right = float(dist.c), size=size)
|
74 |
+
|
75 |
+
@do_sample_numpy.register(UniformDistribution)
|
76 |
+
def _(dist: UniformDistribution, size, rand_state):
|
77 |
+
return rand_state.uniform(low=float(dist.left), high=float(dist.right), size=size)
|
78 |
+
|
79 |
+
|
80 |
+
# DRV:
|
81 |
+
|
82 |
+
@do_sample_numpy.register(GeometricDistribution)
|
83 |
+
def _(dist: GeometricDistribution, size, rand_state):
|
84 |
+
return rand_state.geometric(p=float(dist.p), size=size)
|
85 |
+
|
86 |
+
|
87 |
+
@do_sample_numpy.register(PoissonDistribution)
|
88 |
+
def _(dist: PoissonDistribution, size, rand_state):
|
89 |
+
return rand_state.poisson(lam=float(dist.lamda), size=size)
|
90 |
+
|
91 |
+
|
92 |
+
@do_sample_numpy.register(ZetaDistribution)
|
93 |
+
def _(dist: ZetaDistribution, size, rand_state):
|
94 |
+
return rand_state.zipf(a=float(dist.s), size=size)
|
95 |
+
|
96 |
+
|
97 |
+
# FRV:
|
98 |
+
|
99 |
+
@do_sample_numpy.register(BinomialDistribution)
|
100 |
+
def _(dist: BinomialDistribution, size, rand_state):
|
101 |
+
return rand_state.binomial(n=int(dist.n), p=float(dist.p), size=size)
|
102 |
+
|
103 |
+
@do_sample_numpy.register(HypergeometricDistribution)
|
104 |
+
def _(dist: HypergeometricDistribution, size, rand_state):
|
105 |
+
return rand_state.hypergeometric(ngood = int(dist.N), nbad = int(dist.m), nsample = int(dist.n), size=size)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/sample_pymc.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import singledispatch
|
2 |
+
from sympy.external import import_module
|
3 |
+
from sympy.stats.crv_types import BetaDistribution, CauchyDistribution, ChiSquaredDistribution, ExponentialDistribution, \
|
4 |
+
GammaDistribution, LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution, \
|
5 |
+
GaussianInverseDistribution
|
6 |
+
from sympy.stats.drv_types import PoissonDistribution, GeometricDistribution, NegativeBinomialDistribution
|
7 |
+
from sympy.stats.frv_types import BinomialDistribution, BernoulliDistribution
|
8 |
+
|
9 |
+
|
10 |
+
try:
|
11 |
+
import pymc
|
12 |
+
except ImportError:
|
13 |
+
pymc = import_module('pymc3')
|
14 |
+
|
15 |
+
@singledispatch
|
16 |
+
def do_sample_pymc(dist):
|
17 |
+
return None
|
18 |
+
|
19 |
+
|
20 |
+
# CRV:
|
21 |
+
|
22 |
+
@do_sample_pymc.register(BetaDistribution)
|
23 |
+
def _(dist: BetaDistribution):
|
24 |
+
return pymc.Beta('X', alpha=float(dist.alpha), beta=float(dist.beta))
|
25 |
+
|
26 |
+
|
27 |
+
@do_sample_pymc.register(CauchyDistribution)
|
28 |
+
def _(dist: CauchyDistribution):
|
29 |
+
return pymc.Cauchy('X', alpha=float(dist.x0), beta=float(dist.gamma))
|
30 |
+
|
31 |
+
|
32 |
+
@do_sample_pymc.register(ChiSquaredDistribution)
|
33 |
+
def _(dist: ChiSquaredDistribution):
|
34 |
+
return pymc.ChiSquared('X', nu=float(dist.k))
|
35 |
+
|
36 |
+
|
37 |
+
@do_sample_pymc.register(ExponentialDistribution)
|
38 |
+
def _(dist: ExponentialDistribution):
|
39 |
+
return pymc.Exponential('X', lam=float(dist.rate))
|
40 |
+
|
41 |
+
|
42 |
+
@do_sample_pymc.register(GammaDistribution)
|
43 |
+
def _(dist: GammaDistribution):
|
44 |
+
return pymc.Gamma('X', alpha=float(dist.k), beta=1 / float(dist.theta))
|
45 |
+
|
46 |
+
|
47 |
+
@do_sample_pymc.register(LogNormalDistribution)
|
48 |
+
def _(dist: LogNormalDistribution):
|
49 |
+
return pymc.Lognormal('X', mu=float(dist.mean), sigma=float(dist.std))
|
50 |
+
|
51 |
+
|
52 |
+
@do_sample_pymc.register(NormalDistribution)
|
53 |
+
def _(dist: NormalDistribution):
|
54 |
+
return pymc.Normal('X', float(dist.mean), float(dist.std))
|
55 |
+
|
56 |
+
|
57 |
+
@do_sample_pymc.register(GaussianInverseDistribution)
|
58 |
+
def _(dist: GaussianInverseDistribution):
|
59 |
+
return pymc.Wald('X', mu=float(dist.mean), lam=float(dist.shape))
|
60 |
+
|
61 |
+
|
62 |
+
@do_sample_pymc.register(ParetoDistribution)
|
63 |
+
def _(dist: ParetoDistribution):
|
64 |
+
return pymc.Pareto('X', alpha=float(dist.alpha), m=float(dist.xm))
|
65 |
+
|
66 |
+
|
67 |
+
@do_sample_pymc.register(UniformDistribution)
|
68 |
+
def _(dist: UniformDistribution):
|
69 |
+
return pymc.Uniform('X', lower=float(dist.left), upper=float(dist.right))
|
70 |
+
|
71 |
+
|
72 |
+
# DRV:
|
73 |
+
|
74 |
+
@do_sample_pymc.register(GeometricDistribution)
|
75 |
+
def _(dist: GeometricDistribution):
|
76 |
+
return pymc.Geometric('X', p=float(dist.p))
|
77 |
+
|
78 |
+
|
79 |
+
@do_sample_pymc.register(NegativeBinomialDistribution)
|
80 |
+
def _(dist: NegativeBinomialDistribution):
|
81 |
+
return pymc.NegativeBinomial('X', mu=float((dist.p * dist.r) / (1 - dist.p)),
|
82 |
+
alpha=float(dist.r))
|
83 |
+
|
84 |
+
|
85 |
+
@do_sample_pymc.register(PoissonDistribution)
|
86 |
+
def _(dist: PoissonDistribution):
|
87 |
+
return pymc.Poisson('X', mu=float(dist.lamda))
|
88 |
+
|
89 |
+
|
90 |
+
# FRV:
|
91 |
+
|
92 |
+
@do_sample_pymc.register(BernoulliDistribution)
|
93 |
+
def _(dist: BernoulliDistribution):
|
94 |
+
return pymc.Bernoulli('X', p=float(dist.p))
|
95 |
+
|
96 |
+
|
97 |
+
@do_sample_pymc.register(BinomialDistribution)
|
98 |
+
def _(dist: BinomialDistribution):
|
99 |
+
return pymc.Binomial('X', n=int(dist.n), p=float(dist.p))
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/sample_scipy.py
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import singledispatch
|
2 |
+
|
3 |
+
from sympy.core.symbol import Dummy
|
4 |
+
from sympy.functions.elementary.exponential import exp
|
5 |
+
from sympy.utilities.lambdify import lambdify
|
6 |
+
from sympy.external import import_module
|
7 |
+
from sympy.stats import DiscreteDistributionHandmade
|
8 |
+
from sympy.stats.crv import SingleContinuousDistribution
|
9 |
+
from sympy.stats.crv_types import ChiSquaredDistribution, ExponentialDistribution, GammaDistribution, \
|
10 |
+
LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution, BetaDistribution, \
|
11 |
+
StudentTDistribution, CauchyDistribution
|
12 |
+
from sympy.stats.drv_types import GeometricDistribution, LogarithmicDistribution, NegativeBinomialDistribution, \
|
13 |
+
PoissonDistribution, SkellamDistribution, YuleSimonDistribution, ZetaDistribution
|
14 |
+
from sympy.stats.frv import SingleFiniteDistribution
|
15 |
+
|
16 |
+
|
17 |
+
scipy = import_module("scipy", import_kwargs={'fromlist':['stats']})
|
18 |
+
|
19 |
+
|
20 |
+
@singledispatch
|
21 |
+
def do_sample_scipy(dist, size, seed):
|
22 |
+
return None
|
23 |
+
|
24 |
+
|
25 |
+
# CRV
|
26 |
+
|
27 |
+
@do_sample_scipy.register(SingleContinuousDistribution)
|
28 |
+
def _(dist: SingleContinuousDistribution, size, seed):
|
29 |
+
# if we don't need to make a handmade pdf, we won't
|
30 |
+
import scipy.stats
|
31 |
+
|
32 |
+
z = Dummy('z')
|
33 |
+
handmade_pdf = lambdify(z, dist.pdf(z), ['numpy', 'scipy'])
|
34 |
+
|
35 |
+
class scipy_pdf(scipy.stats.rv_continuous):
|
36 |
+
def _pdf(dist, x):
|
37 |
+
return handmade_pdf(x)
|
38 |
+
|
39 |
+
scipy_rv = scipy_pdf(a=float(dist.set._inf),
|
40 |
+
b=float(dist.set._sup), name='scipy_pdf')
|
41 |
+
return scipy_rv.rvs(size=size, random_state=seed)
|
42 |
+
|
43 |
+
|
44 |
+
@do_sample_scipy.register(ChiSquaredDistribution)
|
45 |
+
def _(dist: ChiSquaredDistribution, size, seed):
|
46 |
+
# same parametrisation
|
47 |
+
return scipy.stats.chi2.rvs(df=float(dist.k), size=size, random_state=seed)
|
48 |
+
|
49 |
+
|
50 |
+
@do_sample_scipy.register(ExponentialDistribution)
|
51 |
+
def _(dist: ExponentialDistribution, size, seed):
|
52 |
+
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.expon.html#scipy.stats.expon
|
53 |
+
return scipy.stats.expon.rvs(scale=1 / float(dist.rate), size=size, random_state=seed)
|
54 |
+
|
55 |
+
|
56 |
+
@do_sample_scipy.register(GammaDistribution)
|
57 |
+
def _(dist: GammaDistribution, size, seed):
|
58 |
+
# https://stackoverflow.com/questions/42150965/how-to-plot-gamma-distribution-with-alpha-and-beta-parameters-in-python
|
59 |
+
return scipy.stats.gamma.rvs(a=float(dist.k), scale=float(dist.theta), size=size, random_state=seed)
|
60 |
+
|
61 |
+
|
62 |
+
@do_sample_scipy.register(LogNormalDistribution)
|
63 |
+
def _(dist: LogNormalDistribution, size, seed):
|
64 |
+
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html
|
65 |
+
return scipy.stats.lognorm.rvs(scale=float(exp(dist.mean)), s=float(dist.std), size=size, random_state=seed)
|
66 |
+
|
67 |
+
|
68 |
+
@do_sample_scipy.register(NormalDistribution)
|
69 |
+
def _(dist: NormalDistribution, size, seed):
|
70 |
+
return scipy.stats.norm.rvs(loc=float(dist.mean), scale=float(dist.std), size=size, random_state=seed)
|
71 |
+
|
72 |
+
|
73 |
+
@do_sample_scipy.register(ParetoDistribution)
|
74 |
+
def _(dist: ParetoDistribution, size, seed):
|
75 |
+
# https://stackoverflow.com/questions/42260519/defining-pareto-distribution-in-python-scipy
|
76 |
+
return scipy.stats.pareto.rvs(b=float(dist.alpha), scale=float(dist.xm), size=size, random_state=seed)
|
77 |
+
|
78 |
+
|
79 |
+
@do_sample_scipy.register(StudentTDistribution)
|
80 |
+
def _(dist: StudentTDistribution, size, seed):
|
81 |
+
return scipy.stats.t.rvs(df=float(dist.nu), size=size, random_state=seed)
|
82 |
+
|
83 |
+
|
84 |
+
@do_sample_scipy.register(UniformDistribution)
|
85 |
+
def _(dist: UniformDistribution, size, seed):
|
86 |
+
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.uniform.html
|
87 |
+
return scipy.stats.uniform.rvs(loc=float(dist.left), scale=float(dist.right - dist.left), size=size, random_state=seed)
|
88 |
+
|
89 |
+
|
90 |
+
@do_sample_scipy.register(BetaDistribution)
|
91 |
+
def _(dist: BetaDistribution, size, seed):
|
92 |
+
# same parametrisation
|
93 |
+
return scipy.stats.beta.rvs(a=float(dist.alpha), b=float(dist.beta), size=size, random_state=seed)
|
94 |
+
|
95 |
+
|
96 |
+
@do_sample_scipy.register(CauchyDistribution)
|
97 |
+
def _(dist: CauchyDistribution, size, seed):
|
98 |
+
return scipy.stats.cauchy.rvs(loc=float(dist.x0), scale=float(dist.gamma), size=size, random_state=seed)
|
99 |
+
|
100 |
+
|
101 |
+
# DRV:
|
102 |
+
|
103 |
+
@do_sample_scipy.register(DiscreteDistributionHandmade)
|
104 |
+
def _(dist: DiscreteDistributionHandmade, size, seed):
|
105 |
+
from scipy.stats import rv_discrete
|
106 |
+
|
107 |
+
z = Dummy('z')
|
108 |
+
handmade_pmf = lambdify(z, dist.pdf(z), ['numpy', 'scipy'])
|
109 |
+
|
110 |
+
class scipy_pmf(rv_discrete):
|
111 |
+
def _pmf(dist, x):
|
112 |
+
return handmade_pmf(x)
|
113 |
+
|
114 |
+
scipy_rv = scipy_pmf(a=float(dist.set._inf), b=float(dist.set._sup),
|
115 |
+
name='scipy_pmf')
|
116 |
+
return scipy_rv.rvs(size=size, random_state=seed)
|
117 |
+
|
118 |
+
|
119 |
+
@do_sample_scipy.register(GeometricDistribution)
|
120 |
+
def _(dist: GeometricDistribution, size, seed):
|
121 |
+
return scipy.stats.geom.rvs(p=float(dist.p), size=size, random_state=seed)
|
122 |
+
|
123 |
+
|
124 |
+
@do_sample_scipy.register(LogarithmicDistribution)
|
125 |
+
def _(dist: LogarithmicDistribution, size, seed):
|
126 |
+
return scipy.stats.logser.rvs(p=float(dist.p), size=size, random_state=seed)
|
127 |
+
|
128 |
+
|
129 |
+
@do_sample_scipy.register(NegativeBinomialDistribution)
|
130 |
+
def _(dist: NegativeBinomialDistribution, size, seed):
|
131 |
+
return scipy.stats.nbinom.rvs(n=float(dist.r), p=float(dist.p), size=size, random_state=seed)
|
132 |
+
|
133 |
+
|
134 |
+
@do_sample_scipy.register(PoissonDistribution)
|
135 |
+
def _(dist: PoissonDistribution, size, seed):
|
136 |
+
return scipy.stats.poisson.rvs(mu=float(dist.lamda), size=size, random_state=seed)
|
137 |
+
|
138 |
+
|
139 |
+
@do_sample_scipy.register(SkellamDistribution)
|
140 |
+
def _(dist: SkellamDistribution, size, seed):
|
141 |
+
return scipy.stats.skellam.rvs(mu1=float(dist.mu1), mu2=float(dist.mu2), size=size, random_state=seed)
|
142 |
+
|
143 |
+
|
144 |
+
@do_sample_scipy.register(YuleSimonDistribution)
|
145 |
+
def _(dist: YuleSimonDistribution, size, seed):
|
146 |
+
return scipy.stats.yulesimon.rvs(alpha=float(dist.rho), size=size, random_state=seed)
|
147 |
+
|
148 |
+
|
149 |
+
@do_sample_scipy.register(ZetaDistribution)
|
150 |
+
def _(dist: ZetaDistribution, size, seed):
|
151 |
+
return scipy.stats.zipf.rvs(a=float(dist.s), size=size, random_state=seed)
|
152 |
+
|
153 |
+
|
154 |
+
# FRV:
|
155 |
+
|
156 |
+
@do_sample_scipy.register(SingleFiniteDistribution)
|
157 |
+
def _(dist: SingleFiniteDistribution, size, seed):
|
158 |
+
# scipy can handle with custom distributions
|
159 |
+
|
160 |
+
from scipy.stats import rv_discrete
|
161 |
+
density_ = dist.dict
|
162 |
+
x, y = [], []
|
163 |
+
for k, v in density_.items():
|
164 |
+
x.append(int(k))
|
165 |
+
y.append(float(v))
|
166 |
+
scipy_rv = rv_discrete(name='scipy_rv', values=(x, y))
|
167 |
+
return scipy_rv.rvs(size=size, random_state=seed)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (191 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/test_sample_continuous_rv.cpython-310.pyc
ADDED
Binary file (5.88 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/test_sample_discrete_rv.cpython-310.pyc
ADDED
Binary file (3.44 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/test_sample_finite_rv.cpython-310.pyc
ADDED
Binary file (3.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/test_sample_continuous_rv.py
ADDED
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import oo
|
2 |
+
from sympy.core.symbol import Symbol
|
3 |
+
from sympy.functions.elementary.exponential import exp
|
4 |
+
from sympy.sets.sets import Interval
|
5 |
+
from sympy.external import import_module
|
6 |
+
from sympy.stats import Beta, Chi, Normal, Gamma, Exponential, LogNormal, Pareto, ChiSquared, Uniform, sample, \
|
7 |
+
BetaPrime, Cauchy, GammaInverse, GaussianInverse, StudentT, Weibull, density, ContinuousRV, FDistribution, \
|
8 |
+
Gumbel, Laplace, Logistic, Rayleigh, Triangular
|
9 |
+
from sympy.testing.pytest import skip, raises
|
10 |
+
|
11 |
+
|
12 |
+
def test_sample_numpy():
|
13 |
+
distribs_numpy = [
|
14 |
+
Beta("B", 1, 1),
|
15 |
+
Normal("N", 0, 1),
|
16 |
+
Gamma("G", 2, 7),
|
17 |
+
Exponential("E", 2),
|
18 |
+
LogNormal("LN", 0, 1),
|
19 |
+
Pareto("P", 1, 1),
|
20 |
+
ChiSquared("CS", 2),
|
21 |
+
Uniform("U", 0, 1),
|
22 |
+
FDistribution("FD", 1, 2),
|
23 |
+
Gumbel("GB", 1, 2),
|
24 |
+
Laplace("L", 1, 2),
|
25 |
+
Logistic("LO", 1, 2),
|
26 |
+
Rayleigh("R", 1),
|
27 |
+
Triangular("T", 1, 2, 2),
|
28 |
+
]
|
29 |
+
size = 3
|
30 |
+
numpy = import_module('numpy')
|
31 |
+
if not numpy:
|
32 |
+
skip('Numpy is not installed. Abort tests for _sample_numpy.')
|
33 |
+
else:
|
34 |
+
for X in distribs_numpy:
|
35 |
+
samps = sample(X, size=size, library='numpy')
|
36 |
+
for sam in samps:
|
37 |
+
assert sam in X.pspace.domain.set
|
38 |
+
raises(NotImplementedError,
|
39 |
+
lambda: sample(Chi("C", 1), library='numpy'))
|
40 |
+
raises(NotImplementedError,
|
41 |
+
lambda: Chi("C", 1).pspace.distribution.sample(library='tensorflow'))
|
42 |
+
|
43 |
+
|
44 |
+
def test_sample_scipy():
|
45 |
+
distribs_scipy = [
|
46 |
+
Beta("B", 1, 1),
|
47 |
+
BetaPrime("BP", 1, 1),
|
48 |
+
Cauchy("C", 1, 1),
|
49 |
+
Chi("C", 1),
|
50 |
+
Normal("N", 0, 1),
|
51 |
+
Gamma("G", 2, 7),
|
52 |
+
GammaInverse("GI", 1, 1),
|
53 |
+
GaussianInverse("GUI", 1, 1),
|
54 |
+
Exponential("E", 2),
|
55 |
+
LogNormal("LN", 0, 1),
|
56 |
+
Pareto("P", 1, 1),
|
57 |
+
StudentT("S", 2),
|
58 |
+
ChiSquared("CS", 2),
|
59 |
+
Uniform("U", 0, 1)
|
60 |
+
]
|
61 |
+
size = 3
|
62 |
+
scipy = import_module('scipy')
|
63 |
+
if not scipy:
|
64 |
+
skip('Scipy is not installed. Abort tests for _sample_scipy.')
|
65 |
+
else:
|
66 |
+
for X in distribs_scipy:
|
67 |
+
samps = sample(X, size=size, library='scipy')
|
68 |
+
samps2 = sample(X, size=(2, 2), library='scipy')
|
69 |
+
for sam in samps:
|
70 |
+
assert sam in X.pspace.domain.set
|
71 |
+
for i in range(2):
|
72 |
+
for j in range(2):
|
73 |
+
assert samps2[i][j] in X.pspace.domain.set
|
74 |
+
|
75 |
+
|
76 |
+
def test_sample_pymc():
|
77 |
+
distribs_pymc = [
|
78 |
+
Beta("B", 1, 1),
|
79 |
+
Cauchy("C", 1, 1),
|
80 |
+
Normal("N", 0, 1),
|
81 |
+
Gamma("G", 2, 7),
|
82 |
+
GaussianInverse("GI", 1, 1),
|
83 |
+
Exponential("E", 2),
|
84 |
+
LogNormal("LN", 0, 1),
|
85 |
+
Pareto("P", 1, 1),
|
86 |
+
ChiSquared("CS", 2),
|
87 |
+
Uniform("U", 0, 1)
|
88 |
+
]
|
89 |
+
size = 3
|
90 |
+
pymc = import_module('pymc')
|
91 |
+
if not pymc:
|
92 |
+
skip('PyMC is not installed. Abort tests for _sample_pymc.')
|
93 |
+
else:
|
94 |
+
for X in distribs_pymc:
|
95 |
+
samps = sample(X, size=size, library='pymc')
|
96 |
+
for sam in samps:
|
97 |
+
assert sam in X.pspace.domain.set
|
98 |
+
raises(NotImplementedError,
|
99 |
+
lambda: sample(Chi("C", 1), library='pymc'))
|
100 |
+
|
101 |
+
|
102 |
+
def test_sampling_gamma_inverse():
|
103 |
+
scipy = import_module('scipy')
|
104 |
+
if not scipy:
|
105 |
+
skip('Scipy not installed. Abort tests for sampling of gamma inverse.')
|
106 |
+
X = GammaInverse("x", 1, 1)
|
107 |
+
assert sample(X) in X.pspace.domain.set
|
108 |
+
|
109 |
+
|
110 |
+
def test_lognormal_sampling():
|
111 |
+
# Right now, only density function and sampling works
|
112 |
+
scipy = import_module('scipy')
|
113 |
+
if not scipy:
|
114 |
+
skip('Scipy is not installed. Abort tests')
|
115 |
+
for i in range(3):
|
116 |
+
X = LogNormal('x', i, 1)
|
117 |
+
assert sample(X) in X.pspace.domain.set
|
118 |
+
|
119 |
+
size = 5
|
120 |
+
samps = sample(X, size=size)
|
121 |
+
for samp in samps:
|
122 |
+
assert samp in X.pspace.domain.set
|
123 |
+
|
124 |
+
|
125 |
+
def test_sampling_gaussian_inverse():
|
126 |
+
scipy = import_module('scipy')
|
127 |
+
if not scipy:
|
128 |
+
skip('Scipy not installed. Abort tests for sampling of Gaussian inverse.')
|
129 |
+
X = GaussianInverse("x", 1, 1)
|
130 |
+
assert sample(X, library='scipy') in X.pspace.domain.set
|
131 |
+
|
132 |
+
|
133 |
+
def test_prefab_sampling():
|
134 |
+
scipy = import_module('scipy')
|
135 |
+
if not scipy:
|
136 |
+
skip('Scipy is not installed. Abort tests')
|
137 |
+
N = Normal('X', 0, 1)
|
138 |
+
L = LogNormal('L', 0, 1)
|
139 |
+
E = Exponential('Ex', 1)
|
140 |
+
P = Pareto('P', 1, 3)
|
141 |
+
W = Weibull('W', 1, 1)
|
142 |
+
U = Uniform('U', 0, 1)
|
143 |
+
B = Beta('B', 2, 5)
|
144 |
+
G = Gamma('G', 1, 3)
|
145 |
+
|
146 |
+
variables = [N, L, E, P, W, U, B, G]
|
147 |
+
niter = 10
|
148 |
+
size = 5
|
149 |
+
for var in variables:
|
150 |
+
for _ in range(niter):
|
151 |
+
assert sample(var) in var.pspace.domain.set
|
152 |
+
samps = sample(var, size=size)
|
153 |
+
for samp in samps:
|
154 |
+
assert samp in var.pspace.domain.set
|
155 |
+
|
156 |
+
|
157 |
+
def test_sample_continuous():
|
158 |
+
z = Symbol('z')
|
159 |
+
Z = ContinuousRV(z, exp(-z), set=Interval(0, oo))
|
160 |
+
assert density(Z)(-1) == 0
|
161 |
+
|
162 |
+
scipy = import_module('scipy')
|
163 |
+
if not scipy:
|
164 |
+
skip('Scipy is not installed. Abort tests')
|
165 |
+
assert sample(Z) in Z.pspace.domain.set
|
166 |
+
sym, val = list(Z.pspace.sample().items())[0]
|
167 |
+
assert sym == Z and val in Interval(0, oo)
|
168 |
+
|
169 |
+
libraries = ['scipy', 'numpy', 'pymc']
|
170 |
+
for lib in libraries:
|
171 |
+
try:
|
172 |
+
imported_lib = import_module(lib)
|
173 |
+
if imported_lib:
|
174 |
+
s0, s1, s2 = [], [], []
|
175 |
+
s0 = sample(Z, size=10, library=lib, seed=0)
|
176 |
+
s1 = sample(Z, size=10, library=lib, seed=0)
|
177 |
+
s2 = sample(Z, size=10, library=lib, seed=1)
|
178 |
+
assert all(s0 == s1)
|
179 |
+
assert all(s1 != s2)
|
180 |
+
except NotImplementedError:
|
181 |
+
continue
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/test_sample_discrete_rv.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.singleton import S
|
2 |
+
from sympy.core.symbol import Symbol
|
3 |
+
from sympy.external import import_module
|
4 |
+
from sympy.stats import Geometric, Poisson, Zeta, sample, Skellam, DiscreteRV, Logarithmic, NegativeBinomial, YuleSimon
|
5 |
+
from sympy.testing.pytest import skip, raises, slow
|
6 |
+
|
7 |
+
|
8 |
+
def test_sample_numpy():
|
9 |
+
distribs_numpy = [
|
10 |
+
Geometric('G', 0.5),
|
11 |
+
Poisson('P', 1),
|
12 |
+
Zeta('Z', 2)
|
13 |
+
]
|
14 |
+
size = 3
|
15 |
+
numpy = import_module('numpy')
|
16 |
+
if not numpy:
|
17 |
+
skip('Numpy is not installed. Abort tests for _sample_numpy.')
|
18 |
+
else:
|
19 |
+
for X in distribs_numpy:
|
20 |
+
samps = sample(X, size=size, library='numpy')
|
21 |
+
for sam in samps:
|
22 |
+
assert sam in X.pspace.domain.set
|
23 |
+
raises(NotImplementedError,
|
24 |
+
lambda: sample(Skellam('S', 1, 1), library='numpy'))
|
25 |
+
raises(NotImplementedError,
|
26 |
+
lambda: Skellam('S', 1, 1).pspace.distribution.sample(library='tensorflow'))
|
27 |
+
|
28 |
+
|
29 |
+
def test_sample_scipy():
|
30 |
+
p = S(2)/3
|
31 |
+
x = Symbol('x', integer=True, positive=True)
|
32 |
+
pdf = p*(1 - p)**(x - 1) # pdf of Geometric Distribution
|
33 |
+
distribs_scipy = [
|
34 |
+
DiscreteRV(x, pdf, set=S.Naturals),
|
35 |
+
Geometric('G', 0.5),
|
36 |
+
Logarithmic('L', 0.5),
|
37 |
+
NegativeBinomial('N', 5, 0.4),
|
38 |
+
Poisson('P', 1),
|
39 |
+
Skellam('S', 1, 1),
|
40 |
+
YuleSimon('Y', 1),
|
41 |
+
Zeta('Z', 2)
|
42 |
+
]
|
43 |
+
size = 3
|
44 |
+
scipy = import_module('scipy')
|
45 |
+
if not scipy:
|
46 |
+
skip('Scipy is not installed. Abort tests for _sample_scipy.')
|
47 |
+
else:
|
48 |
+
for X in distribs_scipy:
|
49 |
+
samps = sample(X, size=size, library='scipy')
|
50 |
+
samps2 = sample(X, size=(2, 2), library='scipy')
|
51 |
+
for sam in samps:
|
52 |
+
assert sam in X.pspace.domain.set
|
53 |
+
for i in range(2):
|
54 |
+
for j in range(2):
|
55 |
+
assert samps2[i][j] in X.pspace.domain.set
|
56 |
+
|
57 |
+
|
58 |
+
def test_sample_pymc():
|
59 |
+
distribs_pymc = [
|
60 |
+
Geometric('G', 0.5),
|
61 |
+
Poisson('P', 1),
|
62 |
+
NegativeBinomial('N', 5, 0.4)
|
63 |
+
]
|
64 |
+
size = 3
|
65 |
+
pymc = import_module('pymc')
|
66 |
+
if not pymc:
|
67 |
+
skip('PyMC is not installed. Abort tests for _sample_pymc.')
|
68 |
+
else:
|
69 |
+
for X in distribs_pymc:
|
70 |
+
samps = sample(X, size=size, library='pymc')
|
71 |
+
for sam in samps:
|
72 |
+
assert sam in X.pspace.domain.set
|
73 |
+
raises(NotImplementedError,
|
74 |
+
lambda: sample(Skellam('S', 1, 1), library='pymc'))
|
75 |
+
|
76 |
+
@slow
|
77 |
+
def test_sample_discrete():
|
78 |
+
X = Geometric('X', S.Half)
|
79 |
+
scipy = import_module('scipy')
|
80 |
+
if not scipy:
|
81 |
+
skip('Scipy not installed. Abort tests')
|
82 |
+
assert sample(X) in X.pspace.domain.set
|
83 |
+
samps = sample(X, size=2) # This takes long time if ran without scipy
|
84 |
+
for samp in samps:
|
85 |
+
assert samp in X.pspace.domain.set
|
86 |
+
|
87 |
+
libraries = ['scipy', 'numpy', 'pymc']
|
88 |
+
for lib in libraries:
|
89 |
+
try:
|
90 |
+
imported_lib = import_module(lib)
|
91 |
+
if imported_lib:
|
92 |
+
s0, s1, s2 = [], [], []
|
93 |
+
s0 = sample(X, size=10, library=lib, seed=0)
|
94 |
+
s1 = sample(X, size=10, library=lib, seed=0)
|
95 |
+
s2 = sample(X, size=10, library=lib, seed=1)
|
96 |
+
assert all(s0 == s1)
|
97 |
+
assert not all(s1 == s2)
|
98 |
+
except NotImplementedError:
|
99 |
+
continue
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/sampling/tests/test_sample_finite_rv.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.numbers import Rational
|
2 |
+
from sympy.core.singleton import S
|
3 |
+
from sympy.external import import_module
|
4 |
+
from sympy.stats import Binomial, sample, Die, FiniteRV, DiscreteUniform, Bernoulli, BetaBinomial, Hypergeometric, \
|
5 |
+
Rademacher
|
6 |
+
from sympy.testing.pytest import skip, raises
|
7 |
+
|
8 |
+
def test_given_sample():
|
9 |
+
X = Die('X', 6)
|
10 |
+
scipy = import_module('scipy')
|
11 |
+
if not scipy:
|
12 |
+
skip('Scipy is not installed. Abort tests')
|
13 |
+
assert sample(X, X > 5) == 6
|
14 |
+
|
15 |
+
def test_sample_numpy():
|
16 |
+
distribs_numpy = [
|
17 |
+
Binomial("B", 5, 0.4),
|
18 |
+
Hypergeometric("H", 2, 1, 1)
|
19 |
+
]
|
20 |
+
size = 3
|
21 |
+
numpy = import_module('numpy')
|
22 |
+
if not numpy:
|
23 |
+
skip('Numpy is not installed. Abort tests for _sample_numpy.')
|
24 |
+
else:
|
25 |
+
for X in distribs_numpy:
|
26 |
+
samps = sample(X, size=size, library='numpy')
|
27 |
+
for sam in samps:
|
28 |
+
assert sam in X.pspace.domain.set
|
29 |
+
raises(NotImplementedError,
|
30 |
+
lambda: sample(Die("D"), library='numpy'))
|
31 |
+
raises(NotImplementedError,
|
32 |
+
lambda: Die("D").pspace.sample(library='tensorflow'))
|
33 |
+
|
34 |
+
|
35 |
+
def test_sample_scipy():
|
36 |
+
distribs_scipy = [
|
37 |
+
FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)}),
|
38 |
+
DiscreteUniform("Y", list(range(5))),
|
39 |
+
Die("D"),
|
40 |
+
Bernoulli("Be", 0.3),
|
41 |
+
Binomial("Bi", 5, 0.4),
|
42 |
+
BetaBinomial("Bb", 2, 1, 1),
|
43 |
+
Hypergeometric("H", 1, 1, 1),
|
44 |
+
Rademacher("R")
|
45 |
+
]
|
46 |
+
|
47 |
+
size = 3
|
48 |
+
scipy = import_module('scipy')
|
49 |
+
if not scipy:
|
50 |
+
skip('Scipy not installed. Abort tests for _sample_scipy.')
|
51 |
+
else:
|
52 |
+
for X in distribs_scipy:
|
53 |
+
samps = sample(X, size=size)
|
54 |
+
samps2 = sample(X, size=(2, 2))
|
55 |
+
for sam in samps:
|
56 |
+
assert sam in X.pspace.domain.set
|
57 |
+
for i in range(2):
|
58 |
+
for j in range(2):
|
59 |
+
assert samps2[i][j] in X.pspace.domain.set
|
60 |
+
|
61 |
+
|
62 |
+
def test_sample_pymc():
|
63 |
+
distribs_pymc = [
|
64 |
+
Bernoulli('B', 0.2),
|
65 |
+
Binomial('N', 5, 0.4)
|
66 |
+
]
|
67 |
+
size = 3
|
68 |
+
pymc = import_module('pymc')
|
69 |
+
if not pymc:
|
70 |
+
skip('PyMC is not installed. Abort tests for _sample_pymc.')
|
71 |
+
else:
|
72 |
+
for X in distribs_pymc:
|
73 |
+
samps = sample(X, size=size, library='pymc')
|
74 |
+
for sam in samps:
|
75 |
+
assert sam in X.pspace.domain.set
|
76 |
+
raises(NotImplementedError,
|
77 |
+
lambda: (sample(Die("D"), library='pymc')))
|
78 |
+
|
79 |
+
|
80 |
+
def test_sample_seed():
|
81 |
+
F = FiniteRV('F', {1: S.Half, 2: Rational(1, 4), 3: Rational(1, 4)})
|
82 |
+
size = 10
|
83 |
+
libraries = ['scipy', 'numpy', 'pymc']
|
84 |
+
for lib in libraries:
|
85 |
+
try:
|
86 |
+
imported_lib = import_module(lib)
|
87 |
+
if imported_lib:
|
88 |
+
s0 = sample(F, size=size, library=lib, seed=0)
|
89 |
+
s1 = sample(F, size=size, library=lib, seed=0)
|
90 |
+
s2 = sample(F, size=size, library=lib, seed=1)
|
91 |
+
assert all(s0 == s1)
|
92 |
+
assert not all(s1 == s2)
|
93 |
+
except NotImplementedError:
|
94 |
+
continue
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/stochastic_process.py
ADDED
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.basic import Basic
|
2 |
+
from sympy.stats.joint_rv import ProductPSpace
|
3 |
+
from sympy.stats.rv import ProductDomain, _symbol_converter, Distribution
|
4 |
+
|
5 |
+
|
6 |
+
class StochasticPSpace(ProductPSpace):
|
7 |
+
"""
|
8 |
+
Represents probability space of stochastic processes
|
9 |
+
and their random variables. Contains mechanics to do
|
10 |
+
computations for queries of stochastic processes.
|
11 |
+
|
12 |
+
Explanation
|
13 |
+
===========
|
14 |
+
|
15 |
+
Initialized by symbol, the specific process and
|
16 |
+
distribution(optional) if the random indexed symbols
|
17 |
+
of the process follows any specific distribution, like,
|
18 |
+
in Bernoulli Process, each random indexed symbol follows
|
19 |
+
Bernoulli distribution. For processes with memory, this
|
20 |
+
parameter should not be passed.
|
21 |
+
"""
|
22 |
+
|
23 |
+
def __new__(cls, sym, process, distribution=None):
|
24 |
+
sym = _symbol_converter(sym)
|
25 |
+
from sympy.stats.stochastic_process_types import StochasticProcess
|
26 |
+
if not isinstance(process, StochasticProcess):
|
27 |
+
raise TypeError("`process` must be an instance of StochasticProcess.")
|
28 |
+
if distribution is None:
|
29 |
+
distribution = Distribution()
|
30 |
+
return Basic.__new__(cls, sym, process, distribution)
|
31 |
+
|
32 |
+
@property
|
33 |
+
def process(self):
|
34 |
+
"""
|
35 |
+
The associated stochastic process.
|
36 |
+
"""
|
37 |
+
return self.args[1]
|
38 |
+
|
39 |
+
@property
|
40 |
+
def domain(self):
|
41 |
+
return ProductDomain(self.process.index_set,
|
42 |
+
self.process.state_space)
|
43 |
+
|
44 |
+
@property
|
45 |
+
def symbol(self):
|
46 |
+
return self.args[0]
|
47 |
+
|
48 |
+
@property
|
49 |
+
def distribution(self):
|
50 |
+
return self.args[2]
|
51 |
+
|
52 |
+
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
|
53 |
+
"""
|
54 |
+
Transfers the task of handling queries to the specific stochastic
|
55 |
+
process because every process has their own logic of handling such
|
56 |
+
queries.
|
57 |
+
"""
|
58 |
+
return self.process.probability(condition, given_condition, evaluate, **kwargs)
|
59 |
+
|
60 |
+
def compute_expectation(self, expr, condition=None, evaluate=True, **kwargs):
|
61 |
+
"""
|
62 |
+
Transfers the task of handling queries to the specific stochastic
|
63 |
+
process because every process has their own logic of handling such
|
64 |
+
queries.
|
65 |
+
"""
|
66 |
+
return self.process.expectation(expr, condition, evaluate, **kwargs)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/stochastic_process_types.py
ADDED
@@ -0,0 +1,2382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
import itertools
|
3 |
+
from typing import (Sequence as tSequence, Union as tUnion, List as tList,
|
4 |
+
Tuple as tTuple, Set as tSet)
|
5 |
+
from sympy.concrete.summations import Sum
|
6 |
+
from sympy.core.add import Add
|
7 |
+
from sympy.core.basic import Basic
|
8 |
+
from sympy.core.cache import cacheit
|
9 |
+
from sympy.core.containers import Tuple
|
10 |
+
from sympy.core.expr import Expr
|
11 |
+
from sympy.core.function import (Function, Lambda)
|
12 |
+
from sympy.core.mul import Mul
|
13 |
+
from sympy.core.numbers import (Integer, Rational, igcd, oo, pi)
|
14 |
+
from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
|
15 |
+
from sympy.core.singleton import S
|
16 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
17 |
+
from sympy.functions.combinatorial.factorials import factorial
|
18 |
+
from sympy.functions.elementary.exponential import exp
|
19 |
+
from sympy.functions.elementary.integers import ceiling
|
20 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
21 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
22 |
+
from sympy.functions.special.gamma_functions import gamma
|
23 |
+
from sympy.logic.boolalg import (And, Not, Or)
|
24 |
+
from sympy.matrices.common import NonSquareMatrixError
|
25 |
+
from sympy.matrices.dense import (Matrix, eye, ones, zeros)
|
26 |
+
from sympy.matrices.expressions.blockmatrix import BlockMatrix
|
27 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
28 |
+
from sympy.matrices.expressions.special import Identity
|
29 |
+
from sympy.matrices.immutable import ImmutableMatrix
|
30 |
+
from sympy.sets.conditionset import ConditionSet
|
31 |
+
from sympy.sets.contains import Contains
|
32 |
+
from sympy.sets.fancysets import Range
|
33 |
+
from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union)
|
34 |
+
from sympy.solvers.solveset import linsolve
|
35 |
+
from sympy.tensor.indexed import (Indexed, IndexedBase)
|
36 |
+
from sympy.core.relational import Relational
|
37 |
+
from sympy.logic.boolalg import Boolean
|
38 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
39 |
+
from sympy.utilities.iterables import strongly_connected_components
|
40 |
+
from sympy.stats.joint_rv import JointDistribution
|
41 |
+
from sympy.stats.joint_rv_types import JointDistributionHandmade
|
42 |
+
from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol,
|
43 |
+
_symbol_converter, _value_check, pspace, given,
|
44 |
+
dependent, is_random, sample_iter, Distribution,
|
45 |
+
Density)
|
46 |
+
from sympy.stats.stochastic_process import StochasticPSpace
|
47 |
+
from sympy.stats.symbolic_probability import Probability, Expectation
|
48 |
+
from sympy.stats.frv_types import Bernoulli, BernoulliDistribution, FiniteRV
|
49 |
+
from sympy.stats.drv_types import Poisson, PoissonDistribution
|
50 |
+
from sympy.stats.crv_types import Normal, NormalDistribution, Gamma, GammaDistribution
|
51 |
+
from sympy.core.sympify import _sympify, sympify
|
52 |
+
|
53 |
+
EmptySet = S.EmptySet
|
54 |
+
|
55 |
+
__all__ = [
|
56 |
+
'StochasticProcess',
|
57 |
+
'DiscreteTimeStochasticProcess',
|
58 |
+
'DiscreteMarkovChain',
|
59 |
+
'TransitionMatrixOf',
|
60 |
+
'StochasticStateSpaceOf',
|
61 |
+
'GeneratorMatrixOf',
|
62 |
+
'ContinuousMarkovChain',
|
63 |
+
'BernoulliProcess',
|
64 |
+
'PoissonProcess',
|
65 |
+
'WienerProcess',
|
66 |
+
'GammaProcess'
|
67 |
+
]
|
68 |
+
|
69 |
+
|
70 |
+
@is_random.register(Indexed)
|
71 |
+
def _(x):
|
72 |
+
return is_random(x.base)
|
73 |
+
|
74 |
+
@is_random.register(RandomIndexedSymbol) # type: ignore
|
75 |
+
def _(x):
|
76 |
+
return True
|
77 |
+
|
78 |
+
def _set_converter(itr):
|
79 |
+
"""
|
80 |
+
Helper function for converting list/tuple/set to Set.
|
81 |
+
If parameter is not an instance of list/tuple/set then
|
82 |
+
no operation is performed.
|
83 |
+
|
84 |
+
Returns
|
85 |
+
=======
|
86 |
+
|
87 |
+
Set
|
88 |
+
The argument converted to Set.
|
89 |
+
|
90 |
+
|
91 |
+
Raises
|
92 |
+
======
|
93 |
+
|
94 |
+
TypeError
|
95 |
+
If the argument is not an instance of list/tuple/set.
|
96 |
+
"""
|
97 |
+
if isinstance(itr, (list, tuple, set)):
|
98 |
+
itr = FiniteSet(*itr)
|
99 |
+
if not isinstance(itr, Set):
|
100 |
+
raise TypeError("%s is not an instance of list/tuple/set."%(itr))
|
101 |
+
return itr
|
102 |
+
|
103 |
+
def _state_converter(itr: tSequence) -> tUnion[Tuple, Range]:
|
104 |
+
"""
|
105 |
+
Helper function for converting list/tuple/set/Range/Tuple/FiniteSet
|
106 |
+
to tuple/Range.
|
107 |
+
"""
|
108 |
+
itr_ret: tUnion[Tuple, Range]
|
109 |
+
|
110 |
+
if isinstance(itr, (Tuple, set, FiniteSet)):
|
111 |
+
itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
|
112 |
+
|
113 |
+
elif isinstance(itr, (list, tuple)):
|
114 |
+
# check if states are unique
|
115 |
+
if len(set(itr)) != len(itr):
|
116 |
+
raise ValueError('The state space must have unique elements.')
|
117 |
+
itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
|
118 |
+
|
119 |
+
elif isinstance(itr, Range):
|
120 |
+
# the only ordered set in SymPy I know of
|
121 |
+
# try to convert to tuple
|
122 |
+
try:
|
123 |
+
itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
|
124 |
+
except (TypeError, ValueError):
|
125 |
+
itr_ret = itr
|
126 |
+
|
127 |
+
else:
|
128 |
+
raise TypeError("%s is not an instance of list/tuple/set/Range/Tuple/FiniteSet." % (itr))
|
129 |
+
return itr_ret
|
130 |
+
|
131 |
+
def _sym_sympify(arg):
|
132 |
+
"""
|
133 |
+
Converts an arbitrary expression to a type that can be used inside SymPy.
|
134 |
+
As generally strings are unwise to use in the expressions,
|
135 |
+
it returns the Symbol of argument if the string type argument is passed.
|
136 |
+
|
137 |
+
Parameters
|
138 |
+
=========
|
139 |
+
|
140 |
+
arg: The parameter to be converted to be used in SymPy.
|
141 |
+
|
142 |
+
Returns
|
143 |
+
=======
|
144 |
+
|
145 |
+
The converted parameter.
|
146 |
+
|
147 |
+
"""
|
148 |
+
if isinstance(arg, str):
|
149 |
+
return Symbol(arg)
|
150 |
+
else:
|
151 |
+
return _sympify(arg)
|
152 |
+
|
153 |
+
def _matrix_checks(matrix):
|
154 |
+
if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)):
|
155 |
+
raise TypeError("Transition probabilities either should "
|
156 |
+
"be a Matrix or a MatrixSymbol.")
|
157 |
+
if matrix.shape[0] != matrix.shape[1]:
|
158 |
+
raise NonSquareMatrixError("%s is not a square matrix"%(matrix))
|
159 |
+
if isinstance(matrix, Matrix):
|
160 |
+
matrix = ImmutableMatrix(matrix.tolist())
|
161 |
+
return matrix
|
162 |
+
|
163 |
+
class StochasticProcess(Basic):
|
164 |
+
"""
|
165 |
+
Base class for all the stochastic processes whether
|
166 |
+
discrete or continuous.
|
167 |
+
|
168 |
+
Parameters
|
169 |
+
==========
|
170 |
+
|
171 |
+
sym: Symbol or str
|
172 |
+
state_space: Set
|
173 |
+
The state space of the stochastic process, by default S.Reals.
|
174 |
+
For discrete sets it is zero indexed.
|
175 |
+
|
176 |
+
See Also
|
177 |
+
========
|
178 |
+
|
179 |
+
DiscreteTimeStochasticProcess
|
180 |
+
"""
|
181 |
+
|
182 |
+
index_set = S.Reals
|
183 |
+
|
184 |
+
def __new__(cls, sym, state_space=S.Reals, **kwargs):
|
185 |
+
sym = _symbol_converter(sym)
|
186 |
+
state_space = _set_converter(state_space)
|
187 |
+
return Basic.__new__(cls, sym, state_space)
|
188 |
+
|
189 |
+
@property
|
190 |
+
def symbol(self):
|
191 |
+
return self.args[0]
|
192 |
+
|
193 |
+
@property
|
194 |
+
def state_space(self) -> tUnion[FiniteSet, Range]:
|
195 |
+
if not isinstance(self.args[1], (FiniteSet, Range)):
|
196 |
+
assert isinstance(self.args[1], Tuple)
|
197 |
+
return FiniteSet(*self.args[1])
|
198 |
+
return self.args[1]
|
199 |
+
|
200 |
+
def _deprecation_warn_distribution(self):
|
201 |
+
sympy_deprecation_warning(
|
202 |
+
"""
|
203 |
+
Calling the distribution method with a RandomIndexedSymbol
|
204 |
+
argument, like X.distribution(X(t)) is deprecated. Instead, call
|
205 |
+
distribution() with the given timestamp, like
|
206 |
+
|
207 |
+
X.distribution(t)
|
208 |
+
""",
|
209 |
+
deprecated_since_version="1.7.1",
|
210 |
+
active_deprecations_target="deprecated-distribution-randomindexedsymbol",
|
211 |
+
stacklevel=4,
|
212 |
+
)
|
213 |
+
|
214 |
+
def distribution(self, key=None):
|
215 |
+
if key is None:
|
216 |
+
self._deprecation_warn_distribution()
|
217 |
+
return Distribution()
|
218 |
+
|
219 |
+
def density(self, x):
|
220 |
+
return Density()
|
221 |
+
|
222 |
+
def __call__(self, time):
|
223 |
+
"""
|
224 |
+
Overridden in ContinuousTimeStochasticProcess.
|
225 |
+
"""
|
226 |
+
raise NotImplementedError("Use [] for indexing discrete time stochastic process.")
|
227 |
+
|
228 |
+
def __getitem__(self, time):
|
229 |
+
"""
|
230 |
+
Overridden in DiscreteTimeStochasticProcess.
|
231 |
+
"""
|
232 |
+
raise NotImplementedError("Use () for indexing continuous time stochastic process.")
|
233 |
+
|
234 |
+
def probability(self, condition):
|
235 |
+
raise NotImplementedError()
|
236 |
+
|
237 |
+
def joint_distribution(self, *args):
|
238 |
+
"""
|
239 |
+
Computes the joint distribution of the random indexed variables.
|
240 |
+
|
241 |
+
Parameters
|
242 |
+
==========
|
243 |
+
|
244 |
+
args: iterable
|
245 |
+
The finite list of random indexed variables/the key of a stochastic
|
246 |
+
process whose joint distribution has to be computed.
|
247 |
+
|
248 |
+
Returns
|
249 |
+
=======
|
250 |
+
|
251 |
+
JointDistribution
|
252 |
+
The joint distribution of the list of random indexed variables.
|
253 |
+
An unevaluated object is returned if it is not possible to
|
254 |
+
compute the joint distribution.
|
255 |
+
|
256 |
+
Raises
|
257 |
+
======
|
258 |
+
|
259 |
+
ValueError: When the arguments passed are not of type RandomIndexSymbol
|
260 |
+
or Number.
|
261 |
+
"""
|
262 |
+
args = list(args)
|
263 |
+
for i, arg in enumerate(args):
|
264 |
+
if S(arg).is_Number:
|
265 |
+
if self.index_set.is_subset(S.Integers):
|
266 |
+
args[i] = self.__getitem__(arg)
|
267 |
+
else:
|
268 |
+
args[i] = self.__call__(arg)
|
269 |
+
elif not isinstance(arg, RandomIndexedSymbol):
|
270 |
+
raise ValueError("Expected a RandomIndexedSymbol or "
|
271 |
+
"key not %s"%(type(arg)))
|
272 |
+
|
273 |
+
if args[0].pspace.distribution == Distribution():
|
274 |
+
return JointDistribution(*args)
|
275 |
+
density = Lambda(tuple(args),
|
276 |
+
expr=Mul.fromiter(arg.pspace.process.density(arg) for arg in args))
|
277 |
+
return JointDistributionHandmade(density)
|
278 |
+
|
279 |
+
def expectation(self, condition, given_condition):
|
280 |
+
raise NotImplementedError("Abstract method for expectation queries.")
|
281 |
+
|
282 |
+
def sample(self):
|
283 |
+
raise NotImplementedError("Abstract method for sampling queries.")
|
284 |
+
|
285 |
+
class DiscreteTimeStochasticProcess(StochasticProcess):
|
286 |
+
"""
|
287 |
+
Base class for all discrete stochastic processes.
|
288 |
+
"""
|
289 |
+
def __getitem__(self, time):
|
290 |
+
"""
|
291 |
+
For indexing discrete time stochastic processes.
|
292 |
+
|
293 |
+
Returns
|
294 |
+
=======
|
295 |
+
|
296 |
+
RandomIndexedSymbol
|
297 |
+
"""
|
298 |
+
time = sympify(time)
|
299 |
+
if not time.is_symbol and time not in self.index_set:
|
300 |
+
raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
|
301 |
+
idx_obj = Indexed(self.symbol, time)
|
302 |
+
pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time))
|
303 |
+
return RandomIndexedSymbol(idx_obj, pspace_obj)
|
304 |
+
|
305 |
+
class ContinuousTimeStochasticProcess(StochasticProcess):
|
306 |
+
"""
|
307 |
+
Base class for all continuous time stochastic process.
|
308 |
+
"""
|
309 |
+
def __call__(self, time):
|
310 |
+
"""
|
311 |
+
For indexing continuous time stochastic processes.
|
312 |
+
|
313 |
+
Returns
|
314 |
+
=======
|
315 |
+
|
316 |
+
RandomIndexedSymbol
|
317 |
+
"""
|
318 |
+
time = sympify(time)
|
319 |
+
if not time.is_symbol and time not in self.index_set:
|
320 |
+
raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
|
321 |
+
func_obj = Function(self.symbol)(time)
|
322 |
+
pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time))
|
323 |
+
return RandomIndexedSymbol(func_obj, pspace_obj)
|
324 |
+
|
325 |
+
class TransitionMatrixOf(Boolean):
|
326 |
+
"""
|
327 |
+
Assumes that the matrix is the transition matrix
|
328 |
+
of the process.
|
329 |
+
"""
|
330 |
+
|
331 |
+
def __new__(cls, process, matrix):
|
332 |
+
if not isinstance(process, DiscreteMarkovChain):
|
333 |
+
raise ValueError("Currently only DiscreteMarkovChain "
|
334 |
+
"support TransitionMatrixOf.")
|
335 |
+
matrix = _matrix_checks(matrix)
|
336 |
+
return Basic.__new__(cls, process, matrix)
|
337 |
+
|
338 |
+
process = property(lambda self: self.args[0])
|
339 |
+
matrix = property(lambda self: self.args[1])
|
340 |
+
|
341 |
+
class GeneratorMatrixOf(TransitionMatrixOf):
|
342 |
+
"""
|
343 |
+
Assumes that the matrix is the generator matrix
|
344 |
+
of the process.
|
345 |
+
"""
|
346 |
+
|
347 |
+
def __new__(cls, process, matrix):
|
348 |
+
if not isinstance(process, ContinuousMarkovChain):
|
349 |
+
raise ValueError("Currently only ContinuousMarkovChain "
|
350 |
+
"support GeneratorMatrixOf.")
|
351 |
+
matrix = _matrix_checks(matrix)
|
352 |
+
return Basic.__new__(cls, process, matrix)
|
353 |
+
|
354 |
+
class StochasticStateSpaceOf(Boolean):
|
355 |
+
|
356 |
+
def __new__(cls, process, state_space):
|
357 |
+
if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)):
|
358 |
+
raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain "
|
359 |
+
"support StochasticStateSpaceOf.")
|
360 |
+
state_space = _state_converter(state_space)
|
361 |
+
if isinstance(state_space, Range):
|
362 |
+
ss_size = ceiling((state_space.stop - state_space.start) / state_space.step)
|
363 |
+
else:
|
364 |
+
ss_size = len(state_space)
|
365 |
+
state_index = Range(ss_size)
|
366 |
+
return Basic.__new__(cls, process, state_index)
|
367 |
+
|
368 |
+
process = property(lambda self: self.args[0])
|
369 |
+
state_index = property(lambda self: self.args[1])
|
370 |
+
|
371 |
+
class MarkovProcess(StochasticProcess):
|
372 |
+
"""
|
373 |
+
Contains methods that handle queries
|
374 |
+
common to Markov processes.
|
375 |
+
"""
|
376 |
+
|
377 |
+
@property
|
378 |
+
def number_of_states(self) -> tUnion[Integer, Symbol]:
|
379 |
+
"""
|
380 |
+
The number of states in the Markov Chain.
|
381 |
+
"""
|
382 |
+
return _sympify(self.args[2].shape[0]) # type: ignore
|
383 |
+
|
384 |
+
@property
|
385 |
+
def _state_index(self):
|
386 |
+
"""
|
387 |
+
Returns state index as Range.
|
388 |
+
"""
|
389 |
+
return self.args[1]
|
390 |
+
|
391 |
+
@classmethod
|
392 |
+
def _sanity_checks(cls, state_space, trans_probs):
|
393 |
+
# Try to never have None as state_space or trans_probs.
|
394 |
+
# This helps a lot if we get it done at the start.
|
395 |
+
if (state_space is None) and (trans_probs is None):
|
396 |
+
_n = Dummy('n', integer=True, nonnegative=True)
|
397 |
+
state_space = _state_converter(Range(_n))
|
398 |
+
trans_probs = _matrix_checks(MatrixSymbol('_T', _n, _n))
|
399 |
+
|
400 |
+
elif state_space is None:
|
401 |
+
trans_probs = _matrix_checks(trans_probs)
|
402 |
+
state_space = _state_converter(Range(trans_probs.shape[0]))
|
403 |
+
|
404 |
+
elif trans_probs is None:
|
405 |
+
state_space = _state_converter(state_space)
|
406 |
+
if isinstance(state_space, Range):
|
407 |
+
_n = ceiling((state_space.stop - state_space.start) / state_space.step)
|
408 |
+
else:
|
409 |
+
_n = len(state_space)
|
410 |
+
trans_probs = MatrixSymbol('_T', _n, _n)
|
411 |
+
|
412 |
+
else:
|
413 |
+
state_space = _state_converter(state_space)
|
414 |
+
trans_probs = _matrix_checks(trans_probs)
|
415 |
+
# Range object doesn't want to give a symbolic size
|
416 |
+
# so we do it ourselves.
|
417 |
+
if isinstance(state_space, Range):
|
418 |
+
ss_size = ceiling((state_space.stop - state_space.start) / state_space.step)
|
419 |
+
else:
|
420 |
+
ss_size = len(state_space)
|
421 |
+
if ss_size != trans_probs.shape[0]:
|
422 |
+
raise ValueError('The size of the state space and the number of '
|
423 |
+
'rows of the transition matrix must be the same.')
|
424 |
+
|
425 |
+
return state_space, trans_probs
|
426 |
+
|
427 |
+
def _extract_information(self, given_condition):
|
428 |
+
"""
|
429 |
+
Helper function to extract information, like,
|
430 |
+
transition matrix/generator matrix, state space, etc.
|
431 |
+
"""
|
432 |
+
if isinstance(self, DiscreteMarkovChain):
|
433 |
+
trans_probs = self.transition_probabilities
|
434 |
+
state_index = self._state_index
|
435 |
+
elif isinstance(self, ContinuousMarkovChain):
|
436 |
+
trans_probs = self.generator_matrix
|
437 |
+
state_index = self._state_index
|
438 |
+
if isinstance(given_condition, And):
|
439 |
+
gcs = given_condition.args
|
440 |
+
given_condition = S.true
|
441 |
+
for gc in gcs:
|
442 |
+
if isinstance(gc, TransitionMatrixOf):
|
443 |
+
trans_probs = gc.matrix
|
444 |
+
if isinstance(gc, StochasticStateSpaceOf):
|
445 |
+
state_index = gc.state_index
|
446 |
+
if isinstance(gc, Relational):
|
447 |
+
given_condition = given_condition & gc
|
448 |
+
if isinstance(given_condition, TransitionMatrixOf):
|
449 |
+
trans_probs = given_condition.matrix
|
450 |
+
given_condition = S.true
|
451 |
+
if isinstance(given_condition, StochasticStateSpaceOf):
|
452 |
+
state_index = given_condition.state_index
|
453 |
+
given_condition = S.true
|
454 |
+
return trans_probs, state_index, given_condition
|
455 |
+
|
456 |
+
def _check_trans_probs(self, trans_probs, row_sum=1):
|
457 |
+
"""
|
458 |
+
Helper function for checking the validity of transition
|
459 |
+
probabilities.
|
460 |
+
"""
|
461 |
+
if not isinstance(trans_probs, MatrixSymbol):
|
462 |
+
rows = trans_probs.tolist()
|
463 |
+
for row in rows:
|
464 |
+
if (sum(row) - row_sum) != 0:
|
465 |
+
raise ValueError("Values in a row must sum to %s. "
|
466 |
+
"If you are using Float or floats then please use Rational."%(row_sum))
|
467 |
+
|
468 |
+
def _work_out_state_index(self, state_index, given_condition, trans_probs):
|
469 |
+
"""
|
470 |
+
Helper function to extract state space if there
|
471 |
+
is a random symbol in the given condition.
|
472 |
+
"""
|
473 |
+
# if given condition is None, then there is no need to work out
|
474 |
+
# state_space from random variables
|
475 |
+
if given_condition != None:
|
476 |
+
rand_var = list(given_condition.atoms(RandomSymbol) -
|
477 |
+
given_condition.atoms(RandomIndexedSymbol))
|
478 |
+
if len(rand_var) == 1:
|
479 |
+
state_index = rand_var[0].pspace.set
|
480 |
+
|
481 |
+
# `not None` is `True`. So the old test fails for symbolic sizes.
|
482 |
+
# Need to build the statement differently.
|
483 |
+
sym_cond = not self.number_of_states.is_Integer
|
484 |
+
cond1 = not sym_cond and len(state_index) != trans_probs.shape[0]
|
485 |
+
if cond1:
|
486 |
+
raise ValueError("state space is not compatible with the transition probabilities.")
|
487 |
+
if not isinstance(trans_probs.shape[0], Symbol):
|
488 |
+
state_index = FiniteSet(*range(trans_probs.shape[0]))
|
489 |
+
return state_index
|
490 |
+
|
491 |
+
@cacheit
|
492 |
+
def _preprocess(self, given_condition, evaluate):
|
493 |
+
"""
|
494 |
+
Helper function for pre-processing the information.
|
495 |
+
"""
|
496 |
+
is_insufficient = False
|
497 |
+
|
498 |
+
if not evaluate: # avoid pre-processing if the result is not to be evaluated
|
499 |
+
return (True, None, None, None)
|
500 |
+
|
501 |
+
# extracting transition matrix and state space
|
502 |
+
trans_probs, state_index, given_condition = self._extract_information(given_condition)
|
503 |
+
|
504 |
+
# given_condition does not have sufficient information
|
505 |
+
# for computations
|
506 |
+
if trans_probs is None or \
|
507 |
+
given_condition is None:
|
508 |
+
is_insufficient = True
|
509 |
+
else:
|
510 |
+
# checking transition probabilities
|
511 |
+
if isinstance(self, DiscreteMarkovChain):
|
512 |
+
self._check_trans_probs(trans_probs, row_sum=1)
|
513 |
+
elif isinstance(self, ContinuousMarkovChain):
|
514 |
+
self._check_trans_probs(trans_probs, row_sum=0)
|
515 |
+
|
516 |
+
# working out state space
|
517 |
+
state_index = self._work_out_state_index(state_index, given_condition, trans_probs)
|
518 |
+
|
519 |
+
return is_insufficient, trans_probs, state_index, given_condition
|
520 |
+
|
521 |
+
def replace_with_index(self, condition):
|
522 |
+
if isinstance(condition, Relational):
|
523 |
+
lhs, rhs = condition.lhs, condition.rhs
|
524 |
+
if not isinstance(lhs, RandomIndexedSymbol):
|
525 |
+
lhs, rhs = rhs, lhs
|
526 |
+
condition = type(condition)(self.index_of.get(lhs, lhs),
|
527 |
+
self.index_of.get(rhs, rhs))
|
528 |
+
return condition
|
529 |
+
|
530 |
+
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
|
531 |
+
"""
|
532 |
+
Handles probability queries for Markov process.
|
533 |
+
|
534 |
+
Parameters
|
535 |
+
==========
|
536 |
+
|
537 |
+
condition: Relational
|
538 |
+
given_condition: Relational/And
|
539 |
+
|
540 |
+
Returns
|
541 |
+
=======
|
542 |
+
Probability
|
543 |
+
If the information is not sufficient.
|
544 |
+
Expr
|
545 |
+
In all other cases.
|
546 |
+
|
547 |
+
Note
|
548 |
+
====
|
549 |
+
Any information passed at the time of query overrides
|
550 |
+
any information passed at the time of object creation like
|
551 |
+
transition probabilities, state space.
|
552 |
+
Pass the transition matrix using TransitionMatrixOf,
|
553 |
+
generator matrix using GeneratorMatrixOf and state space
|
554 |
+
using StochasticStateSpaceOf in given_condition using & or And.
|
555 |
+
"""
|
556 |
+
check, mat, state_index, new_given_condition = \
|
557 |
+
self._preprocess(given_condition, evaluate)
|
558 |
+
|
559 |
+
rv = list(condition.atoms(RandomIndexedSymbol))
|
560 |
+
symbolic = False
|
561 |
+
for sym in rv:
|
562 |
+
if sym.key.is_symbol:
|
563 |
+
symbolic = True
|
564 |
+
break
|
565 |
+
|
566 |
+
if check:
|
567 |
+
return Probability(condition, new_given_condition)
|
568 |
+
|
569 |
+
if isinstance(self, ContinuousMarkovChain):
|
570 |
+
trans_probs = self.transition_probabilities(mat)
|
571 |
+
elif isinstance(self, DiscreteMarkovChain):
|
572 |
+
trans_probs = mat
|
573 |
+
condition = self.replace_with_index(condition)
|
574 |
+
given_condition = self.replace_with_index(given_condition)
|
575 |
+
new_given_condition = self.replace_with_index(new_given_condition)
|
576 |
+
|
577 |
+
if isinstance(condition, Relational):
|
578 |
+
if isinstance(new_given_condition, And):
|
579 |
+
gcs = new_given_condition.args
|
580 |
+
else:
|
581 |
+
gcs = (new_given_condition, )
|
582 |
+
min_key_rv = list(new_given_condition.atoms(RandomIndexedSymbol))
|
583 |
+
|
584 |
+
if len(min_key_rv):
|
585 |
+
min_key_rv = min_key_rv[0]
|
586 |
+
for r in rv:
|
587 |
+
if min_key_rv.key.is_symbol or r.key.is_symbol:
|
588 |
+
continue
|
589 |
+
if min_key_rv.key > r.key:
|
590 |
+
return Probability(condition)
|
591 |
+
else:
|
592 |
+
min_key_rv = None
|
593 |
+
return Probability(condition)
|
594 |
+
|
595 |
+
if symbolic:
|
596 |
+
return self._symbolic_probability(condition, new_given_condition, rv, min_key_rv)
|
597 |
+
|
598 |
+
if len(rv) > 1:
|
599 |
+
rv[0] = condition.lhs
|
600 |
+
rv[1] = condition.rhs
|
601 |
+
if rv[0].key < rv[1].key:
|
602 |
+
rv[0], rv[1] = rv[1], rv[0]
|
603 |
+
if isinstance(condition, Gt):
|
604 |
+
condition = Lt(condition.lhs, condition.rhs)
|
605 |
+
elif isinstance(condition, Lt):
|
606 |
+
condition = Gt(condition.lhs, condition.rhs)
|
607 |
+
elif isinstance(condition, Ge):
|
608 |
+
condition = Le(condition.lhs, condition.rhs)
|
609 |
+
elif isinstance(condition, Le):
|
610 |
+
condition = Ge(condition.lhs, condition.rhs)
|
611 |
+
s = Rational(0, 1)
|
612 |
+
n = len(self.state_space)
|
613 |
+
|
614 |
+
if isinstance(condition, (Eq, Ne)):
|
615 |
+
for i in range(0, n):
|
616 |
+
s += self.probability(Eq(rv[0], i), Eq(rv[1], i)) * self.probability(Eq(rv[1], i), new_given_condition)
|
617 |
+
return s if isinstance(condition, Eq) else 1 - s
|
618 |
+
else:
|
619 |
+
upper = 0
|
620 |
+
greater = False
|
621 |
+
if isinstance(condition, (Ge, Lt)):
|
622 |
+
upper = 1
|
623 |
+
if isinstance(condition, (Ge, Gt)):
|
624 |
+
greater = True
|
625 |
+
|
626 |
+
for i in range(0, n):
|
627 |
+
if i <= n//2:
|
628 |
+
for j in range(0, i + upper):
|
629 |
+
s += self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition)
|
630 |
+
else:
|
631 |
+
s += self.probability(Eq(rv[0], i), new_given_condition)
|
632 |
+
for j in range(i + upper, n):
|
633 |
+
s -= self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition)
|
634 |
+
return s if greater else 1 - s
|
635 |
+
|
636 |
+
rv = rv[0]
|
637 |
+
states = condition.as_set()
|
638 |
+
prob, gstate = {}, None
|
639 |
+
for gc in gcs:
|
640 |
+
if gc.has(min_key_rv):
|
641 |
+
if gc.has(Probability):
|
642 |
+
p, gp = (gc.rhs, gc.lhs) if isinstance(gc.lhs, Probability) \
|
643 |
+
else (gc.lhs, gc.rhs)
|
644 |
+
gr = gp.args[0]
|
645 |
+
gset = Intersection(gr.as_set(), state_index)
|
646 |
+
gstate = list(gset)[0]
|
647 |
+
prob[gset] = p
|
648 |
+
else:
|
649 |
+
_, gstate = (gc.lhs.key, gc.rhs) if isinstance(gc.lhs, RandomIndexedSymbol) \
|
650 |
+
else (gc.rhs.key, gc.lhs)
|
651 |
+
|
652 |
+
if not all(k in self.index_set for k in (rv.key, min_key_rv.key)):
|
653 |
+
raise IndexError("The timestamps of the process are not in it's index set.")
|
654 |
+
states = Intersection(states, state_index) if not isinstance(self.number_of_states, Symbol) else states
|
655 |
+
for state in Union(states, FiniteSet(gstate)):
|
656 |
+
if not state.is_Integer or Ge(state, mat.shape[0]) is True:
|
657 |
+
raise IndexError("No information is available for (%s, %s) in "
|
658 |
+
"transition probabilities of shape, (%s, %s). "
|
659 |
+
"State space is zero indexed."
|
660 |
+
%(gstate, state, mat.shape[0], mat.shape[1]))
|
661 |
+
if prob:
|
662 |
+
gstates = Union(*prob.keys())
|
663 |
+
if len(gstates) == 1:
|
664 |
+
gstate = list(gstates)[0]
|
665 |
+
gprob = list(prob.values())[0]
|
666 |
+
prob[gstates] = gprob
|
667 |
+
elif len(gstates) == len(state_index) - 1:
|
668 |
+
gstate = list(state_index - gstates)[0]
|
669 |
+
gprob = S.One - sum(prob.values())
|
670 |
+
prob[state_index - gstates] = gprob
|
671 |
+
else:
|
672 |
+
raise ValueError("Conflicting information.")
|
673 |
+
else:
|
674 |
+
gprob = S.One
|
675 |
+
|
676 |
+
if min_key_rv == rv:
|
677 |
+
return sum([prob[FiniteSet(state)] for state in states])
|
678 |
+
if isinstance(self, ContinuousMarkovChain):
|
679 |
+
return gprob * sum([trans_probs(rv.key - min_key_rv.key).__getitem__((gstate, state))
|
680 |
+
for state in states])
|
681 |
+
if isinstance(self, DiscreteMarkovChain):
|
682 |
+
return gprob * sum([(trans_probs**(rv.key - min_key_rv.key)).__getitem__((gstate, state))
|
683 |
+
for state in states])
|
684 |
+
|
685 |
+
if isinstance(condition, Not):
|
686 |
+
expr = condition.args[0]
|
687 |
+
return S.One - self.probability(expr, given_condition, evaluate, **kwargs)
|
688 |
+
|
689 |
+
if isinstance(condition, And):
|
690 |
+
compute_later, state2cond, conds = [], {}, condition.args
|
691 |
+
for expr in conds:
|
692 |
+
if isinstance(expr, Relational):
|
693 |
+
ris = list(expr.atoms(RandomIndexedSymbol))[0]
|
694 |
+
if state2cond.get(ris, None) is None:
|
695 |
+
state2cond[ris] = S.true
|
696 |
+
state2cond[ris] &= expr
|
697 |
+
else:
|
698 |
+
compute_later.append(expr)
|
699 |
+
ris = []
|
700 |
+
for ri in state2cond:
|
701 |
+
ris.append(ri)
|
702 |
+
cset = Intersection(state2cond[ri].as_set(), state_index)
|
703 |
+
if len(cset) == 0:
|
704 |
+
return S.Zero
|
705 |
+
state2cond[ri] = cset.as_relational(ri)
|
706 |
+
sorted_ris = sorted(ris, key=lambda ri: ri.key)
|
707 |
+
prod = self.probability(state2cond[sorted_ris[0]], given_condition, evaluate, **kwargs)
|
708 |
+
for i in range(1, len(sorted_ris)):
|
709 |
+
ri, prev_ri = sorted_ris[i], sorted_ris[i-1]
|
710 |
+
if not isinstance(state2cond[ri], Eq):
|
711 |
+
raise ValueError("The process is in multiple states at %s, unable to determine the probability."%(ri))
|
712 |
+
mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
|
713 |
+
prod *= self.probability(state2cond[ri], state2cond[prev_ri]
|
714 |
+
& mat_of
|
715 |
+
& StochasticStateSpaceOf(self, state_index),
|
716 |
+
evaluate, **kwargs)
|
717 |
+
for expr in compute_later:
|
718 |
+
prod *= self.probability(expr, given_condition, evaluate, **kwargs)
|
719 |
+
return prod
|
720 |
+
|
721 |
+
if isinstance(condition, Or):
|
722 |
+
return sum([self.probability(expr, given_condition, evaluate, **kwargs)
|
723 |
+
for expr in condition.args])
|
724 |
+
|
725 |
+
raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
|
726 |
+
"implemented yet."%(condition, given_condition))
|
727 |
+
|
728 |
+
def _symbolic_probability(self, condition, new_given_condition, rv, min_key_rv):
|
729 |
+
#Function to calculate probability for queries with symbols
|
730 |
+
if isinstance(condition, Relational):
|
731 |
+
curr_state = new_given_condition.rhs if isinstance(new_given_condition.lhs, RandomIndexedSymbol) \
|
732 |
+
else new_given_condition.lhs
|
733 |
+
next_state = condition.rhs if isinstance(condition.lhs, RandomIndexedSymbol) \
|
734 |
+
else condition.lhs
|
735 |
+
|
736 |
+
if isinstance(condition, (Eq, Ne)):
|
737 |
+
if isinstance(self, DiscreteMarkovChain):
|
738 |
+
P = self.transition_probabilities**(rv[0].key - min_key_rv.key)
|
739 |
+
else:
|
740 |
+
P = exp(self.generator_matrix*(rv[0].key - min_key_rv.key))
|
741 |
+
prob = P[curr_state, next_state] if isinstance(condition, Eq) else 1 - P[curr_state, next_state]
|
742 |
+
return Piecewise((prob, rv[0].key > min_key_rv.key), (Probability(condition), True))
|
743 |
+
else:
|
744 |
+
upper = 1
|
745 |
+
greater = False
|
746 |
+
if isinstance(condition, (Ge, Lt)):
|
747 |
+
upper = 0
|
748 |
+
if isinstance(condition, (Ge, Gt)):
|
749 |
+
greater = True
|
750 |
+
k = Dummy('k')
|
751 |
+
condition = Eq(condition.lhs, k) if isinstance(condition.lhs, RandomIndexedSymbol)\
|
752 |
+
else Eq(condition.rhs, k)
|
753 |
+
total = Sum(self.probability(condition, new_given_condition), (k, next_state + upper, self.state_space._sup))
|
754 |
+
return Piecewise((total, rv[0].key > min_key_rv.key), (Probability(condition), True)) if greater\
|
755 |
+
else Piecewise((1 - total, rv[0].key > min_key_rv.key), (Probability(condition), True))
|
756 |
+
else:
|
757 |
+
return Probability(condition, new_given_condition)
|
758 |
+
|
759 |
+
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
|
760 |
+
"""
|
761 |
+
Handles expectation queries for markov process.
|
762 |
+
|
763 |
+
Parameters
|
764 |
+
==========
|
765 |
+
|
766 |
+
expr: RandomIndexedSymbol, Relational, Logic
|
767 |
+
Condition for which expectation has to be computed. Must
|
768 |
+
contain a RandomIndexedSymbol of the process.
|
769 |
+
condition: Relational, Logic
|
770 |
+
The given conditions under which computations should be done.
|
771 |
+
|
772 |
+
Returns
|
773 |
+
=======
|
774 |
+
|
775 |
+
Expectation
|
776 |
+
Unevaluated object if computations cannot be done due to
|
777 |
+
insufficient information.
|
778 |
+
Expr
|
779 |
+
In all other cases when the computations are successful.
|
780 |
+
|
781 |
+
Note
|
782 |
+
====
|
783 |
+
|
784 |
+
Any information passed at the time of query overrides
|
785 |
+
any information passed at the time of object creation like
|
786 |
+
transition probabilities, state space.
|
787 |
+
|
788 |
+
Pass the transition matrix using TransitionMatrixOf,
|
789 |
+
generator matrix using GeneratorMatrixOf and state space
|
790 |
+
using StochasticStateSpaceOf in given_condition using & or And.
|
791 |
+
"""
|
792 |
+
|
793 |
+
check, mat, state_index, condition = \
|
794 |
+
self._preprocess(condition, evaluate)
|
795 |
+
|
796 |
+
if check:
|
797 |
+
return Expectation(expr, condition)
|
798 |
+
|
799 |
+
rvs = random_symbols(expr)
|
800 |
+
if isinstance(expr, Expr) and isinstance(condition, Eq) \
|
801 |
+
and len(rvs) == 1:
|
802 |
+
# handle queries similar to E(f(X[i]), Eq(X[i-m], <some-state>))
|
803 |
+
condition=self.replace_with_index(condition)
|
804 |
+
state_index=self.replace_with_index(state_index)
|
805 |
+
rv = list(rvs)[0]
|
806 |
+
lhsg, rhsg = condition.lhs, condition.rhs
|
807 |
+
if not isinstance(lhsg, RandomIndexedSymbol):
|
808 |
+
lhsg, rhsg = (rhsg, lhsg)
|
809 |
+
if rhsg not in state_index:
|
810 |
+
raise ValueError("%s state is not in the state space."%(rhsg))
|
811 |
+
if rv.key < lhsg.key:
|
812 |
+
raise ValueError("Incorrect given condition is given, expectation "
|
813 |
+
"time %s < time %s"%(rv.key, rv.key))
|
814 |
+
mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
|
815 |
+
cond = condition & mat_of & \
|
816 |
+
StochasticStateSpaceOf(self, state_index)
|
817 |
+
func = lambda s: self.probability(Eq(rv, s), cond) * expr.subs(rv, self._state_index[s])
|
818 |
+
return sum([func(s) for s in state_index])
|
819 |
+
|
820 |
+
raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
|
821 |
+
"implemented yet."%(expr, condition))
|
822 |
+
|
823 |
+
class DiscreteMarkovChain(DiscreteTimeStochasticProcess, MarkovProcess):
|
824 |
+
"""
|
825 |
+
Represents a finite discrete time-homogeneous Markov chain.
|
826 |
+
|
827 |
+
This type of Markov Chain can be uniquely characterised by
|
828 |
+
its (ordered) state space and its one-step transition probability
|
829 |
+
matrix.
|
830 |
+
|
831 |
+
Parameters
|
832 |
+
==========
|
833 |
+
|
834 |
+
sym:
|
835 |
+
The name given to the Markov Chain
|
836 |
+
state_space:
|
837 |
+
Optional, by default, Range(n)
|
838 |
+
trans_probs:
|
839 |
+
Optional, by default, MatrixSymbol('_T', n, n)
|
840 |
+
|
841 |
+
Examples
|
842 |
+
========
|
843 |
+
|
844 |
+
>>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf, P, E
|
845 |
+
>>> from sympy import Matrix, MatrixSymbol, Eq, symbols
|
846 |
+
>>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
|
847 |
+
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
|
848 |
+
>>> YS = DiscreteMarkovChain("Y")
|
849 |
+
|
850 |
+
>>> Y.state_space
|
851 |
+
{0, 1, 2}
|
852 |
+
>>> Y.transition_probabilities
|
853 |
+
Matrix([
|
854 |
+
[0.5, 0.2, 0.3],
|
855 |
+
[0.2, 0.5, 0.3],
|
856 |
+
[0.2, 0.3, 0.5]])
|
857 |
+
>>> TS = MatrixSymbol('T', 3, 3)
|
858 |
+
>>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS))
|
859 |
+
T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2]
|
860 |
+
>>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2)
|
861 |
+
0.36
|
862 |
+
|
863 |
+
Probabilities will be calculated based on indexes rather
|
864 |
+
than state names. For example, with the Sunny-Cloudy-Rainy
|
865 |
+
model with string state names:
|
866 |
+
|
867 |
+
>>> from sympy.core.symbol import Str
|
868 |
+
>>> Y = DiscreteMarkovChain("Y", [Str('Sunny'), Str('Cloudy'), Str('Rainy')], T)
|
869 |
+
>>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2)
|
870 |
+
0.36
|
871 |
+
|
872 |
+
This gives the same answer as the ``[0, 1, 2]`` state space.
|
873 |
+
Currently, there is no support for state names within probability
|
874 |
+
and expectation statements. Here is a work-around using ``Str``:
|
875 |
+
|
876 |
+
>>> P(Eq(Str('Rainy'), Y[3]), Eq(Y[1], Str('Cloudy'))).round(2)
|
877 |
+
0.36
|
878 |
+
|
879 |
+
Symbol state names can also be used:
|
880 |
+
|
881 |
+
>>> sunny, cloudy, rainy = symbols('Sunny, Cloudy, Rainy')
|
882 |
+
>>> Y = DiscreteMarkovChain("Y", [sunny, cloudy, rainy], T)
|
883 |
+
>>> P(Eq(Y[3], rainy), Eq(Y[1], cloudy)).round(2)
|
884 |
+
0.36
|
885 |
+
|
886 |
+
Expectations will be calculated as follows:
|
887 |
+
|
888 |
+
>>> E(Y[3], Eq(Y[1], cloudy))
|
889 |
+
0.38*Cloudy + 0.36*Rainy + 0.26*Sunny
|
890 |
+
|
891 |
+
Probability of expressions with multiple RandomIndexedSymbols
|
892 |
+
can also be calculated provided there is only 1 RandomIndexedSymbol
|
893 |
+
in the given condition. It is always better to use Rational instead
|
894 |
+
of floating point numbers for the probabilities in the
|
895 |
+
transition matrix to avoid errors.
|
896 |
+
|
897 |
+
>>> from sympy import Gt, Le, Rational
|
898 |
+
>>> T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]])
|
899 |
+
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
|
900 |
+
>>> P(Eq(Y[3], Y[1]), Eq(Y[0], 0)).round(3)
|
901 |
+
0.409
|
902 |
+
>>> P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2)
|
903 |
+
0.36
|
904 |
+
>>> P(Le(Y[15], Y[10]), Eq(Y[8], 2)).round(7)
|
905 |
+
0.6963328
|
906 |
+
|
907 |
+
Symbolic probability queries are also supported
|
908 |
+
|
909 |
+
>>> a, b, c, d = symbols('a b c d')
|
910 |
+
>>> T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]])
|
911 |
+
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
|
912 |
+
>>> query = P(Eq(Y[a], b), Eq(Y[c], d))
|
913 |
+
>>> query.subs({a:10, b:2, c:5, d:1}).round(4)
|
914 |
+
0.3096
|
915 |
+
>>> P(Eq(Y[10], 2), Eq(Y[5], 1)).evalf().round(4)
|
916 |
+
0.3096
|
917 |
+
>>> query_gt = P(Gt(Y[a], b), Eq(Y[c], d))
|
918 |
+
>>> query_gt.subs({a:21, b:0, c:5, d:0}).evalf().round(5)
|
919 |
+
0.64705
|
920 |
+
>>> P(Gt(Y[21], 0), Eq(Y[5], 0)).round(5)
|
921 |
+
0.64705
|
922 |
+
|
923 |
+
There is limited support for arbitrarily sized states:
|
924 |
+
|
925 |
+
>>> n = symbols('n', nonnegative=True, integer=True)
|
926 |
+
>>> T = MatrixSymbol('T', n, n)
|
927 |
+
>>> Y = DiscreteMarkovChain("Y", trans_probs=T)
|
928 |
+
>>> Y.state_space
|
929 |
+
Range(0, n, 1)
|
930 |
+
>>> query = P(Eq(Y[a], b), Eq(Y[c], d))
|
931 |
+
>>> query.subs({a:10, b:2, c:5, d:1})
|
932 |
+
(T**5)[1, 2]
|
933 |
+
|
934 |
+
References
|
935 |
+
==========
|
936 |
+
|
937 |
+
.. [1] https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain
|
938 |
+
.. [2] https://web.archive.org/web/20201230182007/https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf
|
939 |
+
"""
|
940 |
+
index_set = S.Naturals0
|
941 |
+
|
942 |
+
def __new__(cls, sym, state_space=None, trans_probs=None):
|
943 |
+
sym = _symbol_converter(sym)
|
944 |
+
|
945 |
+
state_space, trans_probs = MarkovProcess._sanity_checks(state_space, trans_probs)
|
946 |
+
|
947 |
+
obj = Basic.__new__(cls, sym, state_space, trans_probs) # type: ignore
|
948 |
+
indices = {}
|
949 |
+
if isinstance(obj.number_of_states, Integer):
|
950 |
+
for index, state in enumerate(obj._state_index):
|
951 |
+
indices[state] = index
|
952 |
+
obj.index_of = indices
|
953 |
+
return obj
|
954 |
+
|
955 |
+
@property
|
956 |
+
def transition_probabilities(self):
|
957 |
+
"""
|
958 |
+
Transition probabilities of discrete Markov chain,
|
959 |
+
either an instance of Matrix or MatrixSymbol.
|
960 |
+
"""
|
961 |
+
return self.args[2]
|
962 |
+
|
963 |
+
def communication_classes(self) -> tList[tTuple[tList[Basic], Boolean, Integer]]:
|
964 |
+
"""
|
965 |
+
Returns the list of communication classes that partition
|
966 |
+
the states of the markov chain.
|
967 |
+
|
968 |
+
A communication class is defined to be a set of states
|
969 |
+
such that every state in that set is reachable from
|
970 |
+
every other state in that set. Due to its properties
|
971 |
+
this forms a class in the mathematical sense.
|
972 |
+
Communication classes are also known as recurrence
|
973 |
+
classes.
|
974 |
+
|
975 |
+
Returns
|
976 |
+
=======
|
977 |
+
|
978 |
+
classes
|
979 |
+
The ``classes`` are a list of tuples. Each
|
980 |
+
tuple represents a single communication class
|
981 |
+
with its properties. The first element in the
|
982 |
+
tuple is the list of states in the class, the
|
983 |
+
second element is whether the class is recurrent
|
984 |
+
and the third element is the period of the
|
985 |
+
communication class.
|
986 |
+
|
987 |
+
Examples
|
988 |
+
========
|
989 |
+
|
990 |
+
>>> from sympy.stats import DiscreteMarkovChain
|
991 |
+
>>> from sympy import Matrix
|
992 |
+
>>> T = Matrix([[0, 1, 0],
|
993 |
+
... [1, 0, 0],
|
994 |
+
... [1, 0, 0]])
|
995 |
+
>>> X = DiscreteMarkovChain('X', [1, 2, 3], T)
|
996 |
+
>>> classes = X.communication_classes()
|
997 |
+
>>> for states, is_recurrent, period in classes:
|
998 |
+
... states, is_recurrent, period
|
999 |
+
([1, 2], True, 2)
|
1000 |
+
([3], False, 1)
|
1001 |
+
|
1002 |
+
From this we can see that states ``1`` and ``2``
|
1003 |
+
communicate, are recurrent and have a period
|
1004 |
+
of 2. We can also see state ``3`` is transient
|
1005 |
+
with a period of 1.
|
1006 |
+
|
1007 |
+
Notes
|
1008 |
+
=====
|
1009 |
+
|
1010 |
+
The algorithm used is of order ``O(n**2)`` where
|
1011 |
+
``n`` is the number of states in the markov chain.
|
1012 |
+
It uses Tarjan's algorithm to find the classes
|
1013 |
+
themselves and then it uses a breadth-first search
|
1014 |
+
algorithm to find each class's periodicity.
|
1015 |
+
Most of the algorithm's components approach ``O(n)``
|
1016 |
+
as the matrix becomes more and more sparse.
|
1017 |
+
|
1018 |
+
References
|
1019 |
+
==========
|
1020 |
+
|
1021 |
+
.. [1] https://web.archive.org/web/20220207032113/https://www.columbia.edu/~ww2040/4701Sum07/4701-06-Notes-MCII.pdf
|
1022 |
+
.. [2] https://cecas.clemson.edu/~shierd/Shier/markov.pdf
|
1023 |
+
.. [3] https://ujcontent.uj.ac.za/esploro/outputs/graduate/Markov-chains--a-graph-theoretical/999849107691#file-0
|
1024 |
+
.. [4] https://www.mathworks.com/help/econ/dtmc.classify.html
|
1025 |
+
"""
|
1026 |
+
n = self.number_of_states
|
1027 |
+
T = self.transition_probabilities
|
1028 |
+
|
1029 |
+
if isinstance(T, MatrixSymbol):
|
1030 |
+
raise NotImplementedError("Cannot perform the operation with a symbolic matrix.")
|
1031 |
+
|
1032 |
+
# begin Tarjan's algorithm
|
1033 |
+
V = Range(n)
|
1034 |
+
# don't use state names. Rather use state
|
1035 |
+
# indexes since we use them for matrix
|
1036 |
+
# indexing here and later onward
|
1037 |
+
E = [(i, j) for i in V for j in V if T[i, j] != 0]
|
1038 |
+
classes = strongly_connected_components((V, E))
|
1039 |
+
# end Tarjan's algorithm
|
1040 |
+
|
1041 |
+
recurrence = []
|
1042 |
+
periods = []
|
1043 |
+
for class_ in classes:
|
1044 |
+
# begin recurrent check (similar to self._check_trans_probs())
|
1045 |
+
submatrix = T[class_, class_] # get the submatrix with those states
|
1046 |
+
is_recurrent = S.true
|
1047 |
+
rows = submatrix.tolist()
|
1048 |
+
for row in rows:
|
1049 |
+
if (sum(row) - 1) != 0:
|
1050 |
+
is_recurrent = S.false
|
1051 |
+
break
|
1052 |
+
recurrence.append(is_recurrent)
|
1053 |
+
# end recurrent check
|
1054 |
+
|
1055 |
+
# begin breadth-first search
|
1056 |
+
non_tree_edge_values: tSet[int] = set()
|
1057 |
+
visited = {class_[0]}
|
1058 |
+
newly_visited = {class_[0]}
|
1059 |
+
level = {class_[0]: 0}
|
1060 |
+
current_level = 0
|
1061 |
+
done = False # imitate a do-while loop
|
1062 |
+
while not done: # runs at most len(class_) times
|
1063 |
+
done = len(visited) == len(class_)
|
1064 |
+
current_level += 1
|
1065 |
+
|
1066 |
+
# this loop and the while loop above run a combined len(class_) number of times.
|
1067 |
+
# so this triple nested loop runs through each of the n states once.
|
1068 |
+
for i in newly_visited:
|
1069 |
+
|
1070 |
+
# the loop below runs len(class_) number of times
|
1071 |
+
# complexity is around about O(n * avg(len(class_)))
|
1072 |
+
newly_visited = {j for j in class_ if T[i, j] != 0}
|
1073 |
+
|
1074 |
+
new_tree_edges = newly_visited.difference(visited)
|
1075 |
+
for j in new_tree_edges:
|
1076 |
+
level[j] = current_level
|
1077 |
+
|
1078 |
+
new_non_tree_edges = newly_visited.intersection(visited)
|
1079 |
+
new_non_tree_edge_values = {level[i]-level[j]+1 for j in new_non_tree_edges}
|
1080 |
+
|
1081 |
+
non_tree_edge_values = non_tree_edge_values.union(new_non_tree_edge_values)
|
1082 |
+
visited = visited.union(new_tree_edges)
|
1083 |
+
|
1084 |
+
# igcd needs at least 2 arguments
|
1085 |
+
positive_ntev = {val_e for val_e in non_tree_edge_values if val_e > 0}
|
1086 |
+
if len(positive_ntev) == 0:
|
1087 |
+
periods.append(len(class_))
|
1088 |
+
elif len(positive_ntev) == 1:
|
1089 |
+
periods.append(positive_ntev.pop())
|
1090 |
+
else:
|
1091 |
+
periods.append(igcd(*positive_ntev))
|
1092 |
+
# end breadth-first search
|
1093 |
+
|
1094 |
+
# convert back to the user's state names
|
1095 |
+
classes = [[_sympify(self._state_index[i]) for i in class_] for class_ in classes]
|
1096 |
+
return list(zip(classes, recurrence, map(Integer,periods)))
|
1097 |
+
|
1098 |
+
def fundamental_matrix(self):
|
1099 |
+
"""
|
1100 |
+
Each entry fundamental matrix can be interpreted as
|
1101 |
+
the expected number of times the chains is in state j
|
1102 |
+
if it started in state i.
|
1103 |
+
|
1104 |
+
References
|
1105 |
+
==========
|
1106 |
+
|
1107 |
+
.. [1] https://lips.cs.princeton.edu/the-fundamental-matrix-of-a-finite-markov-chain/
|
1108 |
+
|
1109 |
+
"""
|
1110 |
+
_, _, _, Q = self.decompose()
|
1111 |
+
|
1112 |
+
if Q.shape[0] > 0: # if non-ergodic
|
1113 |
+
I = eye(Q.shape[0])
|
1114 |
+
if (I - Q).det() == 0:
|
1115 |
+
raise ValueError("The fundamental matrix doesn't exist.")
|
1116 |
+
return (I - Q).inv().as_immutable()
|
1117 |
+
else: # if ergodic
|
1118 |
+
P = self.transition_probabilities
|
1119 |
+
I = eye(P.shape[0])
|
1120 |
+
w = self.fixed_row_vector()
|
1121 |
+
W = Matrix([list(w) for i in range(0, P.shape[0])])
|
1122 |
+
if (I - P + W).det() == 0:
|
1123 |
+
raise ValueError("The fundamental matrix doesn't exist.")
|
1124 |
+
return (I - P + W).inv().as_immutable()
|
1125 |
+
|
1126 |
+
def absorbing_probabilities(self):
|
1127 |
+
"""
|
1128 |
+
Computes the absorbing probabilities, i.e.
|
1129 |
+
the ij-th entry of the matrix denotes the
|
1130 |
+
probability of Markov chain being absorbed
|
1131 |
+
in state j starting from state i.
|
1132 |
+
"""
|
1133 |
+
_, _, R, _ = self.decompose()
|
1134 |
+
N = self.fundamental_matrix()
|
1135 |
+
if R is None or N is None:
|
1136 |
+
return None
|
1137 |
+
return N*R
|
1138 |
+
|
1139 |
+
def absorbing_probabilites(self):
|
1140 |
+
sympy_deprecation_warning(
|
1141 |
+
"""
|
1142 |
+
DiscreteMarkovChain.absorbing_probabilites() is deprecated. Use
|
1143 |
+
absorbing_probabilities() instead (note the spelling difference).
|
1144 |
+
""",
|
1145 |
+
deprecated_since_version="1.7",
|
1146 |
+
active_deprecations_target="deprecated-absorbing_probabilites",
|
1147 |
+
)
|
1148 |
+
return self.absorbing_probabilities()
|
1149 |
+
|
1150 |
+
def is_regular(self):
|
1151 |
+
tuples = self.communication_classes()
|
1152 |
+
if len(tuples) == 0:
|
1153 |
+
return S.false # not defined for a 0x0 matrix
|
1154 |
+
classes, _, periods = list(zip(*tuples))
|
1155 |
+
return And(len(classes) == 1, periods[0] == 1)
|
1156 |
+
|
1157 |
+
def is_ergodic(self):
|
1158 |
+
tuples = self.communication_classes()
|
1159 |
+
if len(tuples) == 0:
|
1160 |
+
return S.false # not defined for a 0x0 matrix
|
1161 |
+
classes, _, _ = list(zip(*tuples))
|
1162 |
+
return S(len(classes) == 1)
|
1163 |
+
|
1164 |
+
def is_absorbing_state(self, state):
|
1165 |
+
trans_probs = self.transition_probabilities
|
1166 |
+
if isinstance(trans_probs, ImmutableMatrix) and \
|
1167 |
+
state < trans_probs.shape[0]:
|
1168 |
+
return S(trans_probs[state, state]) is S.One
|
1169 |
+
|
1170 |
+
def is_absorbing_chain(self):
|
1171 |
+
states, A, B, C = self.decompose()
|
1172 |
+
r = A.shape[0]
|
1173 |
+
return And(r > 0, A == Identity(r).as_explicit())
|
1174 |
+
|
1175 |
+
def stationary_distribution(self, condition_set=False) -> tUnion[ImmutableMatrix, ConditionSet, Lambda]:
|
1176 |
+
r"""
|
1177 |
+
The stationary distribution is any row vector, p, that solves p = pP,
|
1178 |
+
is row stochastic and each element in p must be nonnegative.
|
1179 |
+
That means in matrix form: :math:`(P-I)^T p^T = 0` and
|
1180 |
+
:math:`(1, \dots, 1) p = 1`
|
1181 |
+
where ``P`` is the one-step transition matrix.
|
1182 |
+
|
1183 |
+
All time-homogeneous Markov Chains with a finite state space
|
1184 |
+
have at least one stationary distribution. In addition, if
|
1185 |
+
a finite time-homogeneous Markov Chain is irreducible, the
|
1186 |
+
stationary distribution is unique.
|
1187 |
+
|
1188 |
+
Parameters
|
1189 |
+
==========
|
1190 |
+
|
1191 |
+
condition_set : bool
|
1192 |
+
If the chain has a symbolic size or transition matrix,
|
1193 |
+
it will return a ``Lambda`` if ``False`` and return a
|
1194 |
+
``ConditionSet`` if ``True``.
|
1195 |
+
|
1196 |
+
Examples
|
1197 |
+
========
|
1198 |
+
|
1199 |
+
>>> from sympy.stats import DiscreteMarkovChain
|
1200 |
+
>>> from sympy import Matrix, S
|
1201 |
+
|
1202 |
+
An irreducible Markov Chain
|
1203 |
+
|
1204 |
+
>>> T = Matrix([[S(1)/2, S(1)/2, 0],
|
1205 |
+
... [S(4)/5, S(1)/5, 0],
|
1206 |
+
... [1, 0, 0]])
|
1207 |
+
>>> X = DiscreteMarkovChain('X', trans_probs=T)
|
1208 |
+
>>> X.stationary_distribution()
|
1209 |
+
Matrix([[8/13, 5/13, 0]])
|
1210 |
+
|
1211 |
+
A reducible Markov Chain
|
1212 |
+
|
1213 |
+
>>> T = Matrix([[S(1)/2, S(1)/2, 0],
|
1214 |
+
... [S(4)/5, S(1)/5, 0],
|
1215 |
+
... [0, 0, 1]])
|
1216 |
+
>>> X = DiscreteMarkovChain('X', trans_probs=T)
|
1217 |
+
>>> X.stationary_distribution()
|
1218 |
+
Matrix([[8/13 - 8*tau0/13, 5/13 - 5*tau0/13, tau0]])
|
1219 |
+
|
1220 |
+
>>> Y = DiscreteMarkovChain('Y')
|
1221 |
+
>>> Y.stationary_distribution()
|
1222 |
+
Lambda((wm, _T), Eq(wm*_T, wm))
|
1223 |
+
|
1224 |
+
>>> Y.stationary_distribution(condition_set=True)
|
1225 |
+
ConditionSet(wm, Eq(wm*_T, wm))
|
1226 |
+
|
1227 |
+
References
|
1228 |
+
==========
|
1229 |
+
|
1230 |
+
.. [1] https://www.probabilitycourse.com/chapter11/11_2_6_stationary_and_limiting_distributions.php
|
1231 |
+
.. [2] https://web.archive.org/web/20210508104430/https://galton.uchicago.edu/~yibi/teaching/stat317/2014/Lectures/Lecture4_6up.pdf
|
1232 |
+
|
1233 |
+
See Also
|
1234 |
+
========
|
1235 |
+
|
1236 |
+
sympy.stats.DiscreteMarkovChain.limiting_distribution
|
1237 |
+
"""
|
1238 |
+
trans_probs = self.transition_probabilities
|
1239 |
+
n = self.number_of_states
|
1240 |
+
|
1241 |
+
if n == 0:
|
1242 |
+
return ImmutableMatrix(Matrix([[]]))
|
1243 |
+
|
1244 |
+
# symbolic matrix version
|
1245 |
+
if isinstance(trans_probs, MatrixSymbol):
|
1246 |
+
wm = MatrixSymbol('wm', 1, n)
|
1247 |
+
if condition_set:
|
1248 |
+
return ConditionSet(wm, Eq(wm * trans_probs, wm))
|
1249 |
+
else:
|
1250 |
+
return Lambda((wm, trans_probs), Eq(wm * trans_probs, wm))
|
1251 |
+
|
1252 |
+
# numeric matrix version
|
1253 |
+
a = Matrix(trans_probs - Identity(n)).T
|
1254 |
+
a[0, 0:n] = ones(1, n) # type: ignore
|
1255 |
+
b = zeros(n, 1)
|
1256 |
+
b[0, 0] = 1
|
1257 |
+
|
1258 |
+
soln = list(linsolve((a, b)))[0]
|
1259 |
+
return ImmutableMatrix([soln])
|
1260 |
+
|
1261 |
+
def fixed_row_vector(self):
|
1262 |
+
"""
|
1263 |
+
A wrapper for ``stationary_distribution()``.
|
1264 |
+
"""
|
1265 |
+
return self.stationary_distribution()
|
1266 |
+
|
1267 |
+
@property
|
1268 |
+
def limiting_distribution(self):
|
1269 |
+
"""
|
1270 |
+
The fixed row vector is the limiting
|
1271 |
+
distribution of a discrete Markov chain.
|
1272 |
+
"""
|
1273 |
+
return self.fixed_row_vector()
|
1274 |
+
|
1275 |
+
def decompose(self) -> tTuple[tList[Basic], ImmutableMatrix, ImmutableMatrix, ImmutableMatrix]:
|
1276 |
+
"""
|
1277 |
+
Decomposes the transition matrix into submatrices with
|
1278 |
+
special properties.
|
1279 |
+
|
1280 |
+
The transition matrix can be decomposed into 4 submatrices:
|
1281 |
+
- A - the submatrix from recurrent states to recurrent states.
|
1282 |
+
- B - the submatrix from transient to recurrent states.
|
1283 |
+
- C - the submatrix from transient to transient states.
|
1284 |
+
- O - the submatrix of zeros for recurrent to transient states.
|
1285 |
+
|
1286 |
+
Returns
|
1287 |
+
=======
|
1288 |
+
|
1289 |
+
states, A, B, C
|
1290 |
+
``states`` - a list of state names with the first being
|
1291 |
+
the recurrent states and the last being
|
1292 |
+
the transient states in the order
|
1293 |
+
of the row names of A and then the row names of C.
|
1294 |
+
``A`` - the submatrix from recurrent states to recurrent states.
|
1295 |
+
``B`` - the submatrix from transient to recurrent states.
|
1296 |
+
``C`` - the submatrix from transient to transient states.
|
1297 |
+
|
1298 |
+
Examples
|
1299 |
+
========
|
1300 |
+
|
1301 |
+
>>> from sympy.stats import DiscreteMarkovChain
|
1302 |
+
>>> from sympy import Matrix, S
|
1303 |
+
|
1304 |
+
One can decompose this chain for example:
|
1305 |
+
|
1306 |
+
>>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0],
|
1307 |
+
... [S(2)/5, S(1)/5, S(2)/5, 0, 0],
|
1308 |
+
... [0, 0, 1, 0, 0],
|
1309 |
+
... [0, 0, S(1)/2, S(1)/2, 0],
|
1310 |
+
... [S(1)/2, 0, 0, 0, S(1)/2]])
|
1311 |
+
>>> X = DiscreteMarkovChain('X', trans_probs=T)
|
1312 |
+
>>> states, A, B, C = X.decompose()
|
1313 |
+
>>> states
|
1314 |
+
[2, 0, 1, 3, 4]
|
1315 |
+
|
1316 |
+
>>> A # recurrent to recurrent
|
1317 |
+
Matrix([[1]])
|
1318 |
+
|
1319 |
+
>>> B # transient to recurrent
|
1320 |
+
Matrix([
|
1321 |
+
[ 0],
|
1322 |
+
[2/5],
|
1323 |
+
[1/2],
|
1324 |
+
[ 0]])
|
1325 |
+
|
1326 |
+
>>> C # transient to transient
|
1327 |
+
Matrix([
|
1328 |
+
[1/2, 1/2, 0, 0],
|
1329 |
+
[2/5, 1/5, 0, 0],
|
1330 |
+
[ 0, 0, 1/2, 0],
|
1331 |
+
[1/2, 0, 0, 1/2]])
|
1332 |
+
|
1333 |
+
This means that state 2 is the only absorbing state
|
1334 |
+
(since A is a 1x1 matrix). B is a 4x1 matrix since
|
1335 |
+
the 4 remaining transient states all merge into reccurent
|
1336 |
+
state 2. And C is the 4x4 matrix that shows how the
|
1337 |
+
transient states 0, 1, 3, 4 all interact.
|
1338 |
+
|
1339 |
+
See Also
|
1340 |
+
========
|
1341 |
+
|
1342 |
+
sympy.stats.DiscreteMarkovChain.communication_classes
|
1343 |
+
sympy.stats.DiscreteMarkovChain.canonical_form
|
1344 |
+
|
1345 |
+
References
|
1346 |
+
==========
|
1347 |
+
|
1348 |
+
.. [1] https://en.wikipedia.org/wiki/Absorbing_Markov_chain
|
1349 |
+
.. [2] https://people.brandeis.edu/~igusa/Math56aS08/Math56a_S08_notes015.pdf
|
1350 |
+
"""
|
1351 |
+
trans_probs = self.transition_probabilities
|
1352 |
+
|
1353 |
+
classes = self.communication_classes()
|
1354 |
+
r_states = []
|
1355 |
+
t_states = []
|
1356 |
+
|
1357 |
+
for states, recurrent, period in classes:
|
1358 |
+
if recurrent:
|
1359 |
+
r_states += states
|
1360 |
+
else:
|
1361 |
+
t_states += states
|
1362 |
+
|
1363 |
+
states = r_states + t_states
|
1364 |
+
indexes = [self.index_of[state] for state in states] # type: ignore
|
1365 |
+
|
1366 |
+
A = Matrix(len(r_states), len(r_states),
|
1367 |
+
lambda i, j: trans_probs[indexes[i], indexes[j]])
|
1368 |
+
|
1369 |
+
B = Matrix(len(t_states), len(r_states),
|
1370 |
+
lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[j]])
|
1371 |
+
|
1372 |
+
C = Matrix(len(t_states), len(t_states),
|
1373 |
+
lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[len(r_states) + j]])
|
1374 |
+
|
1375 |
+
return states, A.as_immutable(), B.as_immutable(), C.as_immutable()
|
1376 |
+
|
1377 |
+
def canonical_form(self) -> tTuple[tList[Basic], ImmutableMatrix]:
|
1378 |
+
"""
|
1379 |
+
Reorders the one-step transition matrix
|
1380 |
+
so that recurrent states appear first and transient
|
1381 |
+
states appear last. Other representations include inserting
|
1382 |
+
transient states first and recurrent states last.
|
1383 |
+
|
1384 |
+
Returns
|
1385 |
+
=======
|
1386 |
+
|
1387 |
+
states, P_new
|
1388 |
+
``states`` is the list that describes the order of the
|
1389 |
+
new states in the matrix
|
1390 |
+
so that the ith element in ``states`` is the state of the
|
1391 |
+
ith row of A.
|
1392 |
+
``P_new`` is the new transition matrix in canonical form.
|
1393 |
+
|
1394 |
+
Examples
|
1395 |
+
========
|
1396 |
+
|
1397 |
+
>>> from sympy.stats import DiscreteMarkovChain
|
1398 |
+
>>> from sympy import Matrix, S
|
1399 |
+
|
1400 |
+
You can convert your chain into canonical form:
|
1401 |
+
|
1402 |
+
>>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0],
|
1403 |
+
... [S(2)/5, S(1)/5, S(2)/5, 0, 0],
|
1404 |
+
... [0, 0, 1, 0, 0],
|
1405 |
+
... [0, 0, S(1)/2, S(1)/2, 0],
|
1406 |
+
... [S(1)/2, 0, 0, 0, S(1)/2]])
|
1407 |
+
>>> X = DiscreteMarkovChain('X', list(range(1, 6)), trans_probs=T)
|
1408 |
+
>>> states, new_matrix = X.canonical_form()
|
1409 |
+
>>> states
|
1410 |
+
[3, 1, 2, 4, 5]
|
1411 |
+
|
1412 |
+
>>> new_matrix
|
1413 |
+
Matrix([
|
1414 |
+
[ 1, 0, 0, 0, 0],
|
1415 |
+
[ 0, 1/2, 1/2, 0, 0],
|
1416 |
+
[2/5, 2/5, 1/5, 0, 0],
|
1417 |
+
[1/2, 0, 0, 1/2, 0],
|
1418 |
+
[ 0, 1/2, 0, 0, 1/2]])
|
1419 |
+
|
1420 |
+
The new states are [3, 1, 2, 4, 5] and you can
|
1421 |
+
create a new chain with this and its canonical
|
1422 |
+
form will remain the same (since it is already
|
1423 |
+
in canonical form).
|
1424 |
+
|
1425 |
+
>>> X = DiscreteMarkovChain('X', states, new_matrix)
|
1426 |
+
>>> states, new_matrix = X.canonical_form()
|
1427 |
+
>>> states
|
1428 |
+
[3, 1, 2, 4, 5]
|
1429 |
+
|
1430 |
+
>>> new_matrix
|
1431 |
+
Matrix([
|
1432 |
+
[ 1, 0, 0, 0, 0],
|
1433 |
+
[ 0, 1/2, 1/2, 0, 0],
|
1434 |
+
[2/5, 2/5, 1/5, 0, 0],
|
1435 |
+
[1/2, 0, 0, 1/2, 0],
|
1436 |
+
[ 0, 1/2, 0, 0, 1/2]])
|
1437 |
+
|
1438 |
+
This is not limited to absorbing chains:
|
1439 |
+
|
1440 |
+
>>> T = Matrix([[0, 5, 5, 0, 0],
|
1441 |
+
... [0, 0, 0, 10, 0],
|
1442 |
+
... [5, 0, 5, 0, 0],
|
1443 |
+
... [0, 10, 0, 0, 0],
|
1444 |
+
... [0, 3, 0, 3, 4]])/10
|
1445 |
+
>>> X = DiscreteMarkovChain('X', trans_probs=T)
|
1446 |
+
>>> states, new_matrix = X.canonical_form()
|
1447 |
+
>>> states
|
1448 |
+
[1, 3, 0, 2, 4]
|
1449 |
+
|
1450 |
+
>>> new_matrix
|
1451 |
+
Matrix([
|
1452 |
+
[ 0, 1, 0, 0, 0],
|
1453 |
+
[ 1, 0, 0, 0, 0],
|
1454 |
+
[ 1/2, 0, 0, 1/2, 0],
|
1455 |
+
[ 0, 0, 1/2, 1/2, 0],
|
1456 |
+
[3/10, 3/10, 0, 0, 2/5]])
|
1457 |
+
|
1458 |
+
See Also
|
1459 |
+
========
|
1460 |
+
|
1461 |
+
sympy.stats.DiscreteMarkovChain.communication_classes
|
1462 |
+
sympy.stats.DiscreteMarkovChain.decompose
|
1463 |
+
|
1464 |
+
References
|
1465 |
+
==========
|
1466 |
+
|
1467 |
+
.. [1] https://onlinelibrary.wiley.com/doi/pdf/10.1002/9780470316887.app1
|
1468 |
+
.. [2] http://www.columbia.edu/~ww2040/6711F12/lect1023big.pdf
|
1469 |
+
"""
|
1470 |
+
states, A, B, C = self.decompose()
|
1471 |
+
O = zeros(A.shape[0], C.shape[1])
|
1472 |
+
return states, BlockMatrix([[A, O], [B, C]]).as_explicit()
|
1473 |
+
|
1474 |
+
def sample(self):
|
1475 |
+
"""
|
1476 |
+
Returns
|
1477 |
+
=======
|
1478 |
+
|
1479 |
+
sample: iterator object
|
1480 |
+
iterator object containing the sample
|
1481 |
+
|
1482 |
+
"""
|
1483 |
+
if not isinstance(self.transition_probabilities, (Matrix, ImmutableMatrix)):
|
1484 |
+
raise ValueError("Transition Matrix must be provided for sampling")
|
1485 |
+
Tlist = self.transition_probabilities.tolist()
|
1486 |
+
samps = [random.choice(list(self.state_space))]
|
1487 |
+
yield samps[0]
|
1488 |
+
time = 1
|
1489 |
+
densities = {}
|
1490 |
+
for state in self.state_space:
|
1491 |
+
states = list(self.state_space)
|
1492 |
+
densities[state] = {states[i]: Tlist[state][i]
|
1493 |
+
for i in range(len(states))}
|
1494 |
+
while time < S.Infinity:
|
1495 |
+
samps.append((next(sample_iter(FiniteRV("_", densities[samps[time - 1]])))))
|
1496 |
+
yield samps[time]
|
1497 |
+
time += 1
|
1498 |
+
|
1499 |
+
class ContinuousMarkovChain(ContinuousTimeStochasticProcess, MarkovProcess):
|
1500 |
+
"""
|
1501 |
+
Represents continuous time Markov chain.
|
1502 |
+
|
1503 |
+
Parameters
|
1504 |
+
==========
|
1505 |
+
|
1506 |
+
sym : Symbol/str
|
1507 |
+
state_space : Set
|
1508 |
+
Optional, by default, S.Reals
|
1509 |
+
gen_mat : Matrix/ImmutableMatrix/MatrixSymbol
|
1510 |
+
Optional, by default, None
|
1511 |
+
|
1512 |
+
Examples
|
1513 |
+
========
|
1514 |
+
|
1515 |
+
>>> from sympy.stats import ContinuousMarkovChain, P
|
1516 |
+
>>> from sympy import Matrix, S, Eq, Gt
|
1517 |
+
>>> G = Matrix([[-S(1), S(1)], [S(1), -S(1)]])
|
1518 |
+
>>> C = ContinuousMarkovChain('C', state_space=[0, 1], gen_mat=G)
|
1519 |
+
>>> C.limiting_distribution()
|
1520 |
+
Matrix([[1/2, 1/2]])
|
1521 |
+
>>> C.state_space
|
1522 |
+
{0, 1}
|
1523 |
+
>>> C.generator_matrix
|
1524 |
+
Matrix([
|
1525 |
+
[-1, 1],
|
1526 |
+
[ 1, -1]])
|
1527 |
+
|
1528 |
+
Probability queries are supported
|
1529 |
+
|
1530 |
+
>>> P(Eq(C(1.96), 0), Eq(C(0.78), 1)).round(5)
|
1531 |
+
0.45279
|
1532 |
+
>>> P(Gt(C(1.7), 0), Eq(C(0.82), 1)).round(5)
|
1533 |
+
0.58602
|
1534 |
+
|
1535 |
+
Probability of expressions with multiple RandomIndexedSymbols
|
1536 |
+
can also be calculated provided there is only 1 RandomIndexedSymbol
|
1537 |
+
in the given condition. It is always better to use Rational instead
|
1538 |
+
of floating point numbers for the probabilities in the
|
1539 |
+
generator matrix to avoid errors.
|
1540 |
+
|
1541 |
+
>>> from sympy import Gt, Le, Rational
|
1542 |
+
>>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]])
|
1543 |
+
>>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
|
1544 |
+
>>> P(Eq(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5)
|
1545 |
+
0.37933
|
1546 |
+
>>> P(Gt(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5)
|
1547 |
+
0.34211
|
1548 |
+
>>> P(Le(C(1.57), C(3.14)), Eq(C(1.22), 1)).round(4)
|
1549 |
+
0.7143
|
1550 |
+
|
1551 |
+
Symbolic probability queries are also supported
|
1552 |
+
|
1553 |
+
>>> from sympy import symbols
|
1554 |
+
>>> a,b,c,d = symbols('a b c d')
|
1555 |
+
>>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]])
|
1556 |
+
>>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
|
1557 |
+
>>> query = P(Eq(C(a), b), Eq(C(c), d))
|
1558 |
+
>>> query.subs({a:3.65, b:2, c:1.78, d:1}).evalf().round(10)
|
1559 |
+
0.4002723175
|
1560 |
+
>>> P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10)
|
1561 |
+
0.4002723175
|
1562 |
+
>>> query_gt = P(Gt(C(a), b), Eq(C(c), d))
|
1563 |
+
>>> query_gt.subs({a:43.2, b:0, c:3.29, d:2}).evalf().round(10)
|
1564 |
+
0.6832579186
|
1565 |
+
>>> P(Gt(C(43.2), 0), Eq(C(3.29), 2)).round(10)
|
1566 |
+
0.6832579186
|
1567 |
+
|
1568 |
+
References
|
1569 |
+
==========
|
1570 |
+
|
1571 |
+
.. [1] https://en.wikipedia.org/wiki/Markov_chain#Continuous-time_Markov_chain
|
1572 |
+
.. [2] https://u.math.biu.ac.il/~amirgi/CTMCnotes.pdf
|
1573 |
+
"""
|
1574 |
+
index_set = S.Reals
|
1575 |
+
|
1576 |
+
def __new__(cls, sym, state_space=None, gen_mat=None):
|
1577 |
+
sym = _symbol_converter(sym)
|
1578 |
+
state_space, gen_mat = MarkovProcess._sanity_checks(state_space, gen_mat)
|
1579 |
+
obj = Basic.__new__(cls, sym, state_space, gen_mat)
|
1580 |
+
indices = {}
|
1581 |
+
if isinstance(obj.number_of_states, Integer):
|
1582 |
+
for index, state in enumerate(obj.state_space):
|
1583 |
+
indices[state] = index
|
1584 |
+
obj.index_of = indices
|
1585 |
+
return obj
|
1586 |
+
|
1587 |
+
@property
|
1588 |
+
def generator_matrix(self):
|
1589 |
+
return self.args[2]
|
1590 |
+
|
1591 |
+
@cacheit
|
1592 |
+
def transition_probabilities(self, gen_mat=None):
|
1593 |
+
t = Dummy('t')
|
1594 |
+
if isinstance(gen_mat, (Matrix, ImmutableMatrix)) and \
|
1595 |
+
gen_mat.is_diagonalizable():
|
1596 |
+
# for faster computation use diagonalized generator matrix
|
1597 |
+
Q, D = gen_mat.diagonalize()
|
1598 |
+
return Lambda(t, Q*exp(t*D)*Q.inv())
|
1599 |
+
if gen_mat != None:
|
1600 |
+
return Lambda(t, exp(t*gen_mat))
|
1601 |
+
|
1602 |
+
def limiting_distribution(self):
|
1603 |
+
gen_mat = self.generator_matrix
|
1604 |
+
if gen_mat is None:
|
1605 |
+
return None
|
1606 |
+
if isinstance(gen_mat, MatrixSymbol):
|
1607 |
+
wm = MatrixSymbol('wm', 1, gen_mat.shape[0])
|
1608 |
+
return Lambda((wm, gen_mat), Eq(wm*gen_mat, wm))
|
1609 |
+
w = IndexedBase('w')
|
1610 |
+
wi = [w[i] for i in range(gen_mat.shape[0])]
|
1611 |
+
wm = Matrix([wi])
|
1612 |
+
eqs = (wm*gen_mat).tolist()[0]
|
1613 |
+
eqs.append(sum(wi) - 1)
|
1614 |
+
soln = list(linsolve(eqs, wi))[0]
|
1615 |
+
return ImmutableMatrix([soln])
|
1616 |
+
|
1617 |
+
|
1618 |
+
class BernoulliProcess(DiscreteTimeStochasticProcess):
|
1619 |
+
"""
|
1620 |
+
The Bernoulli process consists of repeated
|
1621 |
+
independent Bernoulli process trials with the same parameter `p`.
|
1622 |
+
It's assumed that the probability `p` applies to every
|
1623 |
+
trial and that the outcomes of each trial
|
1624 |
+
are independent of all the rest. Therefore Bernoulli Process
|
1625 |
+
is Discrete State and Discrete Time Stochastic Process.
|
1626 |
+
|
1627 |
+
Parameters
|
1628 |
+
==========
|
1629 |
+
|
1630 |
+
sym : Symbol/str
|
1631 |
+
success : Integer/str
|
1632 |
+
The event which is considered to be success. Default: 1.
|
1633 |
+
failure: Integer/str
|
1634 |
+
The event which is considered to be failure. Default: 0.
|
1635 |
+
p : Real Number between 0 and 1
|
1636 |
+
Represents the probability of getting success.
|
1637 |
+
|
1638 |
+
Examples
|
1639 |
+
========
|
1640 |
+
|
1641 |
+
>>> from sympy.stats import BernoulliProcess, P, E
|
1642 |
+
>>> from sympy import Eq, Gt
|
1643 |
+
>>> B = BernoulliProcess("B", p=0.7, success=1, failure=0)
|
1644 |
+
>>> B.state_space
|
1645 |
+
{0, 1}
|
1646 |
+
>>> (B.p).round(2)
|
1647 |
+
0.70
|
1648 |
+
>>> B.success
|
1649 |
+
1
|
1650 |
+
>>> B.failure
|
1651 |
+
0
|
1652 |
+
>>> X = B[1] + B[2] + B[3]
|
1653 |
+
>>> P(Eq(X, 0)).round(2)
|
1654 |
+
0.03
|
1655 |
+
>>> P(Eq(X, 2)).round(2)
|
1656 |
+
0.44
|
1657 |
+
>>> P(Eq(X, 4)).round(2)
|
1658 |
+
0
|
1659 |
+
>>> P(Gt(X, 1)).round(2)
|
1660 |
+
0.78
|
1661 |
+
>>> P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2)
|
1662 |
+
0.04
|
1663 |
+
>>> B.joint_distribution(B[1], B[2])
|
1664 |
+
JointDistributionHandmade(Lambda((B[1], B[2]), Piecewise((0.7, Eq(B[1], 1)),
|
1665 |
+
(0.3, Eq(B[1], 0)), (0, True))*Piecewise((0.7, Eq(B[2], 1)), (0.3, Eq(B[2], 0)),
|
1666 |
+
(0, True))))
|
1667 |
+
>>> E(2*B[1] + B[2]).round(2)
|
1668 |
+
2.10
|
1669 |
+
>>> P(B[1] < 1).round(2)
|
1670 |
+
0.30
|
1671 |
+
|
1672 |
+
References
|
1673 |
+
==========
|
1674 |
+
|
1675 |
+
.. [1] https://en.wikipedia.org/wiki/Bernoulli_process
|
1676 |
+
.. [2] https://mathcs.clarku.edu/~djoyce/ma217/bernoulli.pdf
|
1677 |
+
|
1678 |
+
"""
|
1679 |
+
|
1680 |
+
index_set = S.Naturals0
|
1681 |
+
|
1682 |
+
def __new__(cls, sym, p, success=1, failure=0):
|
1683 |
+
_value_check(p >= 0 and p <= 1, 'Value of p must be between 0 and 1.')
|
1684 |
+
sym = _symbol_converter(sym)
|
1685 |
+
p = _sympify(p)
|
1686 |
+
success = _sym_sympify(success)
|
1687 |
+
failure = _sym_sympify(failure)
|
1688 |
+
return Basic.__new__(cls, sym, p, success, failure)
|
1689 |
+
|
1690 |
+
@property
|
1691 |
+
def symbol(self):
|
1692 |
+
return self.args[0]
|
1693 |
+
|
1694 |
+
@property
|
1695 |
+
def p(self):
|
1696 |
+
return self.args[1]
|
1697 |
+
|
1698 |
+
@property
|
1699 |
+
def success(self):
|
1700 |
+
return self.args[2]
|
1701 |
+
|
1702 |
+
@property
|
1703 |
+
def failure(self):
|
1704 |
+
return self.args[3]
|
1705 |
+
|
1706 |
+
@property
|
1707 |
+
def state_space(self):
|
1708 |
+
return _set_converter([self.success, self.failure])
|
1709 |
+
|
1710 |
+
def distribution(self, key=None):
|
1711 |
+
if key is None:
|
1712 |
+
self._deprecation_warn_distribution()
|
1713 |
+
return BernoulliDistribution(self.p)
|
1714 |
+
return BernoulliDistribution(self.p, self.success, self.failure)
|
1715 |
+
|
1716 |
+
def simple_rv(self, rv):
|
1717 |
+
return Bernoulli(rv.name, p=self.p,
|
1718 |
+
succ=self.success, fail=self.failure)
|
1719 |
+
|
1720 |
+
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
|
1721 |
+
"""
|
1722 |
+
Computes expectation.
|
1723 |
+
|
1724 |
+
Parameters
|
1725 |
+
==========
|
1726 |
+
|
1727 |
+
expr : RandomIndexedSymbol, Relational, Logic
|
1728 |
+
Condition for which expectation has to be computed. Must
|
1729 |
+
contain a RandomIndexedSymbol of the process.
|
1730 |
+
condition : Relational, Logic
|
1731 |
+
The given conditions under which computations should be done.
|
1732 |
+
|
1733 |
+
Returns
|
1734 |
+
=======
|
1735 |
+
|
1736 |
+
Expectation of the RandomIndexedSymbol.
|
1737 |
+
|
1738 |
+
"""
|
1739 |
+
|
1740 |
+
return _SubstituteRV._expectation(expr, condition, evaluate, **kwargs)
|
1741 |
+
|
1742 |
+
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
|
1743 |
+
"""
|
1744 |
+
Computes probability.
|
1745 |
+
|
1746 |
+
Parameters
|
1747 |
+
==========
|
1748 |
+
|
1749 |
+
condition : Relational
|
1750 |
+
Condition for which probability has to be computed. Must
|
1751 |
+
contain a RandomIndexedSymbol of the process.
|
1752 |
+
given_condition : Relational, Logic
|
1753 |
+
The given conditions under which computations should be done.
|
1754 |
+
|
1755 |
+
Returns
|
1756 |
+
=======
|
1757 |
+
|
1758 |
+
Probability of the condition.
|
1759 |
+
|
1760 |
+
"""
|
1761 |
+
|
1762 |
+
return _SubstituteRV._probability(condition, given_condition, evaluate, **kwargs)
|
1763 |
+
|
1764 |
+
def density(self, x):
|
1765 |
+
return Piecewise((self.p, Eq(x, self.success)),
|
1766 |
+
(1 - self.p, Eq(x, self.failure)),
|
1767 |
+
(S.Zero, True))
|
1768 |
+
|
1769 |
+
class _SubstituteRV:
|
1770 |
+
"""
|
1771 |
+
Internal class to handle the queries of expectation and probability
|
1772 |
+
by substitution.
|
1773 |
+
"""
|
1774 |
+
|
1775 |
+
@staticmethod
|
1776 |
+
def _rvindexed_subs(expr, condition=None):
|
1777 |
+
"""
|
1778 |
+
Substitutes the RandomIndexedSymbol with the RandomSymbol with
|
1779 |
+
same name, distribution and probability as RandomIndexedSymbol.
|
1780 |
+
|
1781 |
+
Parameters
|
1782 |
+
==========
|
1783 |
+
|
1784 |
+
expr: RandomIndexedSymbol, Relational, Logic
|
1785 |
+
Condition for which expectation has to be computed. Must
|
1786 |
+
contain a RandomIndexedSymbol of the process.
|
1787 |
+
condition: Relational, Logic
|
1788 |
+
The given conditions under which computations should be done.
|
1789 |
+
|
1790 |
+
"""
|
1791 |
+
|
1792 |
+
rvs_expr = random_symbols(expr)
|
1793 |
+
if len(rvs_expr) != 0:
|
1794 |
+
swapdict_expr = {}
|
1795 |
+
for rv in rvs_expr:
|
1796 |
+
if isinstance(rv, RandomIndexedSymbol):
|
1797 |
+
newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv
|
1798 |
+
swapdict_expr[rv] = newrv
|
1799 |
+
expr = expr.subs(swapdict_expr)
|
1800 |
+
rvs_cond = random_symbols(condition)
|
1801 |
+
if len(rvs_cond)!=0:
|
1802 |
+
swapdict_cond = {}
|
1803 |
+
for rv in rvs_cond:
|
1804 |
+
if isinstance(rv, RandomIndexedSymbol):
|
1805 |
+
newrv = rv.pspace.process.simple_rv(rv)
|
1806 |
+
swapdict_cond[rv] = newrv
|
1807 |
+
condition = condition.subs(swapdict_cond)
|
1808 |
+
return expr, condition
|
1809 |
+
|
1810 |
+
@classmethod
|
1811 |
+
def _expectation(self, expr, condition=None, evaluate=True, **kwargs):
|
1812 |
+
"""
|
1813 |
+
Internal method for computing expectation of indexed RV.
|
1814 |
+
|
1815 |
+
Parameters
|
1816 |
+
==========
|
1817 |
+
|
1818 |
+
expr: RandomIndexedSymbol, Relational, Logic
|
1819 |
+
Condition for which expectation has to be computed. Must
|
1820 |
+
contain a RandomIndexedSymbol of the process.
|
1821 |
+
condition: Relational, Logic
|
1822 |
+
The given conditions under which computations should be done.
|
1823 |
+
|
1824 |
+
Returns
|
1825 |
+
=======
|
1826 |
+
|
1827 |
+
Expectation of the RandomIndexedSymbol.
|
1828 |
+
|
1829 |
+
"""
|
1830 |
+
new_expr, new_condition = self._rvindexed_subs(expr, condition)
|
1831 |
+
|
1832 |
+
if not is_random(new_expr):
|
1833 |
+
return new_expr
|
1834 |
+
new_pspace = pspace(new_expr)
|
1835 |
+
if new_condition is not None:
|
1836 |
+
new_expr = given(new_expr, new_condition)
|
1837 |
+
if new_expr.is_Add: # As E is Linear
|
1838 |
+
return Add(*[new_pspace.compute_expectation(
|
1839 |
+
expr=arg, evaluate=evaluate, **kwargs)
|
1840 |
+
for arg in new_expr.args])
|
1841 |
+
return new_pspace.compute_expectation(
|
1842 |
+
new_expr, evaluate=evaluate, **kwargs)
|
1843 |
+
|
1844 |
+
@classmethod
|
1845 |
+
def _probability(self, condition, given_condition=None, evaluate=True, **kwargs):
|
1846 |
+
"""
|
1847 |
+
Internal method for computing probability of indexed RV
|
1848 |
+
|
1849 |
+
Parameters
|
1850 |
+
==========
|
1851 |
+
|
1852 |
+
condition: Relational
|
1853 |
+
Condition for which probability has to be computed. Must
|
1854 |
+
contain a RandomIndexedSymbol of the process.
|
1855 |
+
given_condition: Relational/And
|
1856 |
+
The given conditions under which computations should be done.
|
1857 |
+
|
1858 |
+
Returns
|
1859 |
+
=======
|
1860 |
+
|
1861 |
+
Probability of the condition.
|
1862 |
+
|
1863 |
+
"""
|
1864 |
+
new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition)
|
1865 |
+
|
1866 |
+
if isinstance(new_givencondition, RandomSymbol):
|
1867 |
+
condrv = random_symbols(new_condition)
|
1868 |
+
if len(condrv) == 1 and condrv[0] == new_givencondition:
|
1869 |
+
return BernoulliDistribution(self._probability(new_condition), 0, 1)
|
1870 |
+
|
1871 |
+
if any(dependent(rv, new_givencondition) for rv in condrv):
|
1872 |
+
return Probability(new_condition, new_givencondition)
|
1873 |
+
else:
|
1874 |
+
return self._probability(new_condition)
|
1875 |
+
|
1876 |
+
if new_givencondition is not None and \
|
1877 |
+
not isinstance(new_givencondition, (Relational, Boolean)):
|
1878 |
+
raise ValueError("%s is not a relational or combination of relationals"
|
1879 |
+
% (new_givencondition))
|
1880 |
+
if new_givencondition == False or new_condition == False:
|
1881 |
+
return S.Zero
|
1882 |
+
if new_condition == True:
|
1883 |
+
return S.One
|
1884 |
+
if not isinstance(new_condition, (Relational, Boolean)):
|
1885 |
+
raise ValueError("%s is not a relational or combination of relationals"
|
1886 |
+
% (new_condition))
|
1887 |
+
|
1888 |
+
if new_givencondition is not None: # If there is a condition
|
1889 |
+
# Recompute on new conditional expr
|
1890 |
+
return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs)
|
1891 |
+
result = pspace(new_condition).probability(new_condition, **kwargs)
|
1892 |
+
if evaluate and hasattr(result, 'doit'):
|
1893 |
+
return result.doit()
|
1894 |
+
else:
|
1895 |
+
return result
|
1896 |
+
|
1897 |
+
def get_timerv_swaps(expr, condition):
|
1898 |
+
"""
|
1899 |
+
Finds the appropriate interval for each time stamp in expr by parsing
|
1900 |
+
the given condition and returns intervals for each timestamp and
|
1901 |
+
dictionary that maps variable time-stamped Random Indexed Symbol to its
|
1902 |
+
corresponding Random Indexed variable with fixed time stamp.
|
1903 |
+
|
1904 |
+
Parameters
|
1905 |
+
==========
|
1906 |
+
|
1907 |
+
expr: SymPy Expression
|
1908 |
+
Expression containing Random Indexed Symbols with variable time stamps
|
1909 |
+
condition: Relational/Boolean Expression
|
1910 |
+
Expression containing time bounds of variable time stamps in expr
|
1911 |
+
|
1912 |
+
Examples
|
1913 |
+
========
|
1914 |
+
|
1915 |
+
>>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess
|
1916 |
+
>>> from sympy import symbols, Contains, Interval
|
1917 |
+
>>> x, t, d = symbols('x t d', positive=True)
|
1918 |
+
>>> X = PoissonProcess("X", 3)
|
1919 |
+
>>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1)))
|
1920 |
+
([Interval.Lopen(0, 1)], {X(t): X(1)})
|
1921 |
+
>>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1))
|
1922 |
+
... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP
|
1923 |
+
([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)})
|
1924 |
+
|
1925 |
+
Returns
|
1926 |
+
=======
|
1927 |
+
|
1928 |
+
intervals: list
|
1929 |
+
List of Intervals/FiniteSet on which each time stamp is defined
|
1930 |
+
rv_swap: dict
|
1931 |
+
Dictionary mapping variable time Random Indexed Symbol to constant time
|
1932 |
+
Random Indexed Variable
|
1933 |
+
|
1934 |
+
"""
|
1935 |
+
|
1936 |
+
if not isinstance(condition, (Relational, Boolean)):
|
1937 |
+
raise ValueError("%s is not a relational or combination of relationals"
|
1938 |
+
% (condition))
|
1939 |
+
expr_syms = list(expr.atoms(RandomIndexedSymbol))
|
1940 |
+
if isinstance(condition, (And, Or)):
|
1941 |
+
given_cond_args = condition.args
|
1942 |
+
else: # single condition
|
1943 |
+
given_cond_args = (condition, )
|
1944 |
+
rv_swap = {}
|
1945 |
+
intervals = []
|
1946 |
+
for expr_sym in expr_syms:
|
1947 |
+
for arg in given_cond_args:
|
1948 |
+
if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol):
|
1949 |
+
intv = _set_converter(arg.args[1])
|
1950 |
+
diff_key = intv._sup - intv._inf
|
1951 |
+
if diff_key == oo:
|
1952 |
+
raise ValueError("%s should have finite bounds" % str(expr_sym.name))
|
1953 |
+
elif diff_key == S.Zero: # has singleton set
|
1954 |
+
diff_key = intv._sup
|
1955 |
+
rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key})
|
1956 |
+
intervals.append(intv)
|
1957 |
+
return intervals, rv_swap
|
1958 |
+
|
1959 |
+
|
1960 |
+
class CountingProcess(ContinuousTimeStochasticProcess):
|
1961 |
+
"""
|
1962 |
+
This class handles the common methods of the Counting Processes
|
1963 |
+
such as Poisson, Wiener and Gamma Processes
|
1964 |
+
"""
|
1965 |
+
index_set = _set_converter(Interval(0, oo))
|
1966 |
+
|
1967 |
+
@property
|
1968 |
+
def symbol(self):
|
1969 |
+
return self.args[0]
|
1970 |
+
|
1971 |
+
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
|
1972 |
+
"""
|
1973 |
+
Computes expectation
|
1974 |
+
|
1975 |
+
Parameters
|
1976 |
+
==========
|
1977 |
+
|
1978 |
+
expr: RandomIndexedSymbol, Relational, Logic
|
1979 |
+
Condition for which expectation has to be computed. Must
|
1980 |
+
contain a RandomIndexedSymbol of the process.
|
1981 |
+
condition: Relational, Boolean
|
1982 |
+
The given conditions under which computations should be done, i.e,
|
1983 |
+
the intervals on which each variable time stamp in expr is defined
|
1984 |
+
|
1985 |
+
Returns
|
1986 |
+
=======
|
1987 |
+
|
1988 |
+
Expectation of the given expr
|
1989 |
+
|
1990 |
+
"""
|
1991 |
+
if condition is not None:
|
1992 |
+
intervals, rv_swap = get_timerv_swaps(expr, condition)
|
1993 |
+
# they are independent when they have non-overlapping intervals
|
1994 |
+
if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
|
1995 |
+
for intv_comb in itertools.combinations(intervals, 2)):
|
1996 |
+
if expr.is_Add:
|
1997 |
+
return Add.fromiter(self.expectation(arg, condition)
|
1998 |
+
for arg in expr.args)
|
1999 |
+
expr = expr.subs(rv_swap)
|
2000 |
+
else:
|
2001 |
+
return Expectation(expr, condition)
|
2002 |
+
|
2003 |
+
return _SubstituteRV._expectation(expr, evaluate=evaluate, **kwargs)
|
2004 |
+
|
2005 |
+
def _solve_argwith_tworvs(self, arg):
|
2006 |
+
if arg.args[0].key >= arg.args[1].key or isinstance(arg, Eq):
|
2007 |
+
diff_key = abs(arg.args[0].key - arg.args[1].key)
|
2008 |
+
rv = arg.args[0]
|
2009 |
+
arg = arg.__class__(rv.pspace.process(diff_key), 0)
|
2010 |
+
else:
|
2011 |
+
diff_key = arg.args[1].key - arg.args[0].key
|
2012 |
+
rv = arg.args[1]
|
2013 |
+
arg = arg.__class__(rv.pspace.process(diff_key), 0)
|
2014 |
+
return arg
|
2015 |
+
|
2016 |
+
def _solve_numerical(self, condition, given_condition=None):
|
2017 |
+
if isinstance(condition, And):
|
2018 |
+
args_list = list(condition.args)
|
2019 |
+
else:
|
2020 |
+
args_list = [condition]
|
2021 |
+
if given_condition is not None:
|
2022 |
+
if isinstance(given_condition, And):
|
2023 |
+
args_list.extend(list(given_condition.args))
|
2024 |
+
else:
|
2025 |
+
args_list.extend([given_condition])
|
2026 |
+
# sort the args based on timestamp to get the independent increments in
|
2027 |
+
# each segment using all the condition args as well as given_condition args
|
2028 |
+
args_list = sorted(args_list, key=lambda x: x.args[0].key)
|
2029 |
+
result = []
|
2030 |
+
cond_args = list(condition.args) if isinstance(condition, And) else [condition]
|
2031 |
+
if args_list[0] in cond_args and not (is_random(args_list[0].args[0])
|
2032 |
+
and is_random(args_list[0].args[1])):
|
2033 |
+
result.append(_SubstituteRV._probability(args_list[0]))
|
2034 |
+
|
2035 |
+
if is_random(args_list[0].args[0]) and is_random(args_list[0].args[1]):
|
2036 |
+
arg = self._solve_argwith_tworvs(args_list[0])
|
2037 |
+
result.append(_SubstituteRV._probability(arg))
|
2038 |
+
|
2039 |
+
for i in range(len(args_list) - 1):
|
2040 |
+
curr, nex = args_list[i], args_list[i + 1]
|
2041 |
+
diff_key = nex.args[0].key - curr.args[0].key
|
2042 |
+
working_set = curr.args[0].pspace.process.state_space
|
2043 |
+
if curr.args[1] > nex.args[1]: #impossible condition so return 0
|
2044 |
+
result.append(0)
|
2045 |
+
break
|
2046 |
+
if isinstance(curr, Eq):
|
2047 |
+
working_set = Intersection(working_set, Interval.Lopen(curr.args[1], oo))
|
2048 |
+
else:
|
2049 |
+
working_set = Intersection(working_set, curr.as_set())
|
2050 |
+
if isinstance(nex, Eq):
|
2051 |
+
working_set = Intersection(working_set, Interval(-oo, nex.args[1]))
|
2052 |
+
else:
|
2053 |
+
working_set = Intersection(working_set, nex.as_set())
|
2054 |
+
if working_set == EmptySet:
|
2055 |
+
rv = Eq(curr.args[0].pspace.process(diff_key), 0)
|
2056 |
+
result.append(_SubstituteRV._probability(rv))
|
2057 |
+
else:
|
2058 |
+
if working_set.is_finite_set:
|
2059 |
+
if isinstance(curr, Eq) and isinstance(nex, Eq):
|
2060 |
+
rv = Eq(curr.args[0].pspace.process(diff_key), len(working_set))
|
2061 |
+
result.append(_SubstituteRV._probability(rv))
|
2062 |
+
elif isinstance(curr, Eq) ^ isinstance(nex, Eq):
|
2063 |
+
result.append(Add.fromiter(_SubstituteRV._probability(Eq(
|
2064 |
+
curr.args[0].pspace.process(diff_key), x))
|
2065 |
+
for x in range(len(working_set))))
|
2066 |
+
else:
|
2067 |
+
n = len(working_set)
|
2068 |
+
result.append(Add.fromiter((n - x)*_SubstituteRV._probability(Eq(
|
2069 |
+
curr.args[0].pspace.process(diff_key), x)) for x in range(n)))
|
2070 |
+
else:
|
2071 |
+
result.append(_SubstituteRV._probability(
|
2072 |
+
curr.args[0].pspace.process(diff_key) <= working_set._sup - working_set._inf))
|
2073 |
+
return Mul.fromiter(result)
|
2074 |
+
|
2075 |
+
|
2076 |
+
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
|
2077 |
+
"""
|
2078 |
+
Computes probability.
|
2079 |
+
|
2080 |
+
Parameters
|
2081 |
+
==========
|
2082 |
+
|
2083 |
+
condition: Relational
|
2084 |
+
Condition for which probability has to be computed. Must
|
2085 |
+
contain a RandomIndexedSymbol of the process.
|
2086 |
+
given_condition: Relational, Boolean
|
2087 |
+
The given conditions under which computations should be done, i.e,
|
2088 |
+
the intervals on which each variable time stamp in expr is defined
|
2089 |
+
|
2090 |
+
Returns
|
2091 |
+
=======
|
2092 |
+
|
2093 |
+
Probability of the condition
|
2094 |
+
|
2095 |
+
"""
|
2096 |
+
check_numeric = True
|
2097 |
+
if isinstance(condition, (And, Or)):
|
2098 |
+
cond_args = condition.args
|
2099 |
+
else:
|
2100 |
+
cond_args = (condition, )
|
2101 |
+
# check that condition args are numeric or not
|
2102 |
+
if not all(arg.args[0].key.is_number for arg in cond_args):
|
2103 |
+
check_numeric = False
|
2104 |
+
if given_condition is not None:
|
2105 |
+
check_given_numeric = True
|
2106 |
+
if isinstance(given_condition, (And, Or)):
|
2107 |
+
given_cond_args = given_condition.args
|
2108 |
+
else:
|
2109 |
+
given_cond_args = (given_condition, )
|
2110 |
+
# check that given condition args are numeric or not
|
2111 |
+
if given_condition.has(Contains):
|
2112 |
+
check_given_numeric = False
|
2113 |
+
# Handle numerical queries
|
2114 |
+
if check_numeric and check_given_numeric:
|
2115 |
+
res = []
|
2116 |
+
if isinstance(condition, Or):
|
2117 |
+
res.append(Add.fromiter(self._solve_numerical(arg, given_condition)
|
2118 |
+
for arg in condition.args))
|
2119 |
+
if isinstance(given_condition, Or):
|
2120 |
+
res.append(Add.fromiter(self._solve_numerical(condition, arg)
|
2121 |
+
for arg in given_condition.args))
|
2122 |
+
if res:
|
2123 |
+
return Add.fromiter(res)
|
2124 |
+
return self._solve_numerical(condition, given_condition)
|
2125 |
+
|
2126 |
+
# No numeric queries, go by Contains?... then check that all the
|
2127 |
+
# given condition are in form of `Contains`
|
2128 |
+
if not all(arg.has(Contains) for arg in given_cond_args):
|
2129 |
+
raise ValueError("If given condition is passed with `Contains`, then "
|
2130 |
+
"please pass the evaluated condition with its corresponding information "
|
2131 |
+
"in terms of intervals of each time stamp to be passed in given condition.")
|
2132 |
+
|
2133 |
+
intervals, rv_swap = get_timerv_swaps(condition, given_condition)
|
2134 |
+
# they are independent when they have non-overlapping intervals
|
2135 |
+
if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
|
2136 |
+
for intv_comb in itertools.combinations(intervals, 2)):
|
2137 |
+
if isinstance(condition, And):
|
2138 |
+
return Mul.fromiter(self.probability(arg, given_condition)
|
2139 |
+
for arg in condition.args)
|
2140 |
+
elif isinstance(condition, Or):
|
2141 |
+
return Add.fromiter(self.probability(arg, given_condition)
|
2142 |
+
for arg in condition.args)
|
2143 |
+
condition = condition.subs(rv_swap)
|
2144 |
+
else:
|
2145 |
+
return Probability(condition, given_condition)
|
2146 |
+
if check_numeric:
|
2147 |
+
return self._solve_numerical(condition)
|
2148 |
+
return _SubstituteRV._probability(condition, evaluate=evaluate, **kwargs)
|
2149 |
+
|
2150 |
+
class PoissonProcess(CountingProcess):
|
2151 |
+
"""
|
2152 |
+
The Poisson process is a counting process. It is usually used in scenarios
|
2153 |
+
where we are counting the occurrences of certain events that appear
|
2154 |
+
to happen at a certain rate, but completely at random.
|
2155 |
+
|
2156 |
+
Parameters
|
2157 |
+
==========
|
2158 |
+
|
2159 |
+
sym : Symbol/str
|
2160 |
+
lamda : Positive number
|
2161 |
+
Rate of the process, ``lambda > 0``
|
2162 |
+
|
2163 |
+
Examples
|
2164 |
+
========
|
2165 |
+
|
2166 |
+
>>> from sympy.stats import PoissonProcess, P, E
|
2167 |
+
>>> from sympy import symbols, Eq, Ne, Contains, Interval
|
2168 |
+
>>> X = PoissonProcess("X", lamda=3)
|
2169 |
+
>>> X.state_space
|
2170 |
+
Naturals0
|
2171 |
+
>>> X.lamda
|
2172 |
+
3
|
2173 |
+
>>> t1, t2 = symbols('t1 t2', positive=True)
|
2174 |
+
>>> P(X(t1) < 4)
|
2175 |
+
(9*t1**3/2 + 9*t1**2/2 + 3*t1 + 1)*exp(-3*t1)
|
2176 |
+
>>> P(Eq(X(t1), 2) | Ne(X(t1), 4), Contains(t1, Interval.Ropen(2, 4)))
|
2177 |
+
1 - 36*exp(-6)
|
2178 |
+
>>> P(Eq(X(t1), 2) & Eq(X(t2), 3), Contains(t1, Interval.Lopen(0, 2))
|
2179 |
+
... & Contains(t2, Interval.Lopen(2, 4)))
|
2180 |
+
648*exp(-12)
|
2181 |
+
>>> E(X(t1))
|
2182 |
+
3*t1
|
2183 |
+
>>> E(X(t1)**2 + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
|
2184 |
+
... & Contains(t2, Interval.Lopen(1, 2)))
|
2185 |
+
18
|
2186 |
+
>>> P(X(3) < 1, Eq(X(1), 0))
|
2187 |
+
exp(-6)
|
2188 |
+
>>> P(Eq(X(4), 3), Eq(X(2), 3))
|
2189 |
+
exp(-6)
|
2190 |
+
>>> P(X(2) <= 3, X(1) > 1)
|
2191 |
+
5*exp(-3)
|
2192 |
+
|
2193 |
+
Merging two Poisson Processes
|
2194 |
+
|
2195 |
+
>>> Y = PoissonProcess("Y", lamda=4)
|
2196 |
+
>>> Z = X + Y
|
2197 |
+
>>> Z.lamda
|
2198 |
+
7
|
2199 |
+
|
2200 |
+
Splitting a Poisson Process into two independent Poisson Processes
|
2201 |
+
|
2202 |
+
>>> N, M = Z.split(l1=2, l2=5)
|
2203 |
+
>>> N.lamda, M.lamda
|
2204 |
+
(2, 5)
|
2205 |
+
|
2206 |
+
References
|
2207 |
+
==========
|
2208 |
+
|
2209 |
+
.. [1] https://www.probabilitycourse.com/chapter11/11_0_0_intro.php
|
2210 |
+
.. [2] https://en.wikipedia.org/wiki/Poisson_point_process
|
2211 |
+
|
2212 |
+
"""
|
2213 |
+
|
2214 |
+
def __new__(cls, sym, lamda):
|
2215 |
+
_value_check(lamda > 0, 'lamda should be a positive number.')
|
2216 |
+
sym = _symbol_converter(sym)
|
2217 |
+
lamda = _sympify(lamda)
|
2218 |
+
return Basic.__new__(cls, sym, lamda)
|
2219 |
+
|
2220 |
+
@property
|
2221 |
+
def lamda(self):
|
2222 |
+
return self.args[1]
|
2223 |
+
|
2224 |
+
@property
|
2225 |
+
def state_space(self):
|
2226 |
+
return S.Naturals0
|
2227 |
+
|
2228 |
+
def distribution(self, key):
|
2229 |
+
if isinstance(key, RandomIndexedSymbol):
|
2230 |
+
self._deprecation_warn_distribution()
|
2231 |
+
return PoissonDistribution(self.lamda*key.key)
|
2232 |
+
return PoissonDistribution(self.lamda*key)
|
2233 |
+
|
2234 |
+
def density(self, x):
|
2235 |
+
return (self.lamda*x.key)**x / factorial(x) * exp(-(self.lamda*x.key))
|
2236 |
+
|
2237 |
+
def simple_rv(self, rv):
|
2238 |
+
return Poisson(rv.name, lamda=self.lamda*rv.key)
|
2239 |
+
|
2240 |
+
def __add__(self, other):
|
2241 |
+
if not isinstance(other, PoissonProcess):
|
2242 |
+
raise ValueError("Only instances of Poisson Process can be merged")
|
2243 |
+
return PoissonProcess(Dummy(self.symbol.name + other.symbol.name),
|
2244 |
+
self.lamda + other.lamda)
|
2245 |
+
|
2246 |
+
def split(self, l1, l2):
|
2247 |
+
if _sympify(l1 + l2) != self.lamda:
|
2248 |
+
raise ValueError("Sum of l1 and l2 should be %s" % str(self.lamda))
|
2249 |
+
return PoissonProcess(Dummy("l1"), l1), PoissonProcess(Dummy("l2"), l2)
|
2250 |
+
|
2251 |
+
class WienerProcess(CountingProcess):
|
2252 |
+
"""
|
2253 |
+
The Wiener process is a real valued continuous-time stochastic process.
|
2254 |
+
In physics it is used to study Brownian motion and it is often also called
|
2255 |
+
Brownian motion due to its historical connection with physical process of the
|
2256 |
+
same name originally observed by Scottish botanist Robert Brown.
|
2257 |
+
|
2258 |
+
Parameters
|
2259 |
+
==========
|
2260 |
+
|
2261 |
+
sym : Symbol/str
|
2262 |
+
|
2263 |
+
Examples
|
2264 |
+
========
|
2265 |
+
|
2266 |
+
>>> from sympy.stats import WienerProcess, P, E
|
2267 |
+
>>> from sympy import symbols, Contains, Interval
|
2268 |
+
>>> X = WienerProcess("X")
|
2269 |
+
>>> X.state_space
|
2270 |
+
Reals
|
2271 |
+
>>> t1, t2 = symbols('t1 t2', positive=True)
|
2272 |
+
>>> P(X(t1) < 7).simplify()
|
2273 |
+
erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2
|
2274 |
+
>>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify()
|
2275 |
+
-erf(1)/2 + erf(2)/2 + 1
|
2276 |
+
>>> E(X(t1))
|
2277 |
+
0
|
2278 |
+
>>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
|
2279 |
+
... & Contains(t2, Interval.Lopen(1, 2)))
|
2280 |
+
0
|
2281 |
+
|
2282 |
+
References
|
2283 |
+
==========
|
2284 |
+
|
2285 |
+
.. [1] https://www.probabilitycourse.com/chapter11/11_4_0_brownian_motion_wiener_process.php
|
2286 |
+
.. [2] https://en.wikipedia.org/wiki/Wiener_process
|
2287 |
+
|
2288 |
+
"""
|
2289 |
+
def __new__(cls, sym):
|
2290 |
+
sym = _symbol_converter(sym)
|
2291 |
+
return Basic.__new__(cls, sym)
|
2292 |
+
|
2293 |
+
@property
|
2294 |
+
def state_space(self):
|
2295 |
+
return S.Reals
|
2296 |
+
|
2297 |
+
def distribution(self, key):
|
2298 |
+
if isinstance(key, RandomIndexedSymbol):
|
2299 |
+
self._deprecation_warn_distribution()
|
2300 |
+
return NormalDistribution(0, sqrt(key.key))
|
2301 |
+
return NormalDistribution(0, sqrt(key))
|
2302 |
+
|
2303 |
+
def density(self, x):
|
2304 |
+
return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key))
|
2305 |
+
|
2306 |
+
def simple_rv(self, rv):
|
2307 |
+
return Normal(rv.name, 0, sqrt(rv.key))
|
2308 |
+
|
2309 |
+
|
2310 |
+
class GammaProcess(CountingProcess):
|
2311 |
+
r"""
|
2312 |
+
A Gamma process is a random process with independent gamma distributed
|
2313 |
+
increments. It is a pure-jump increasing Levy process.
|
2314 |
+
|
2315 |
+
Parameters
|
2316 |
+
==========
|
2317 |
+
|
2318 |
+
sym : Symbol/str
|
2319 |
+
lamda : Positive number
|
2320 |
+
Jump size of the process, ``lamda > 0``
|
2321 |
+
gamma : Positive number
|
2322 |
+
Rate of jump arrivals, `\gamma > 0`
|
2323 |
+
|
2324 |
+
Examples
|
2325 |
+
========
|
2326 |
+
|
2327 |
+
>>> from sympy.stats import GammaProcess, E, P, variance
|
2328 |
+
>>> from sympy import symbols, Contains, Interval, Not
|
2329 |
+
>>> t, d, x, l, g = symbols('t d x l g', positive=True)
|
2330 |
+
>>> X = GammaProcess("X", l, g)
|
2331 |
+
>>> E(X(t))
|
2332 |
+
g*t/l
|
2333 |
+
>>> variance(X(t)).simplify()
|
2334 |
+
g*t/l**2
|
2335 |
+
>>> X = GammaProcess('X', 1, 2)
|
2336 |
+
>>> P(X(t) < 1).simplify()
|
2337 |
+
lowergamma(2*t, 1)/gamma(2*t)
|
2338 |
+
>>> P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) &
|
2339 |
+
... Contains(d, Interval.Lopen(7, 8))).simplify()
|
2340 |
+
-4*exp(-3) + 472*exp(-8)/3 + 1
|
2341 |
+
>>> E(X(2) + x*E(X(5)))
|
2342 |
+
10*x + 4
|
2343 |
+
|
2344 |
+
References
|
2345 |
+
==========
|
2346 |
+
|
2347 |
+
.. [1] https://en.wikipedia.org/wiki/Gamma_process
|
2348 |
+
|
2349 |
+
"""
|
2350 |
+
def __new__(cls, sym, lamda, gamma):
|
2351 |
+
_value_check(lamda > 0, 'lamda should be a positive number')
|
2352 |
+
_value_check(gamma > 0, 'gamma should be a positive number')
|
2353 |
+
sym = _symbol_converter(sym)
|
2354 |
+
gamma = _sympify(gamma)
|
2355 |
+
lamda = _sympify(lamda)
|
2356 |
+
return Basic.__new__(cls, sym, lamda, gamma)
|
2357 |
+
|
2358 |
+
@property
|
2359 |
+
def lamda(self):
|
2360 |
+
return self.args[1]
|
2361 |
+
|
2362 |
+
@property
|
2363 |
+
def gamma(self):
|
2364 |
+
return self.args[2]
|
2365 |
+
|
2366 |
+
@property
|
2367 |
+
def state_space(self):
|
2368 |
+
return _set_converter(Interval(0, oo))
|
2369 |
+
|
2370 |
+
def distribution(self, key):
|
2371 |
+
if isinstance(key, RandomIndexedSymbol):
|
2372 |
+
self._deprecation_warn_distribution()
|
2373 |
+
return GammaDistribution(self.gamma*key.key, 1/self.lamda)
|
2374 |
+
return GammaDistribution(self.gamma*key, 1/self.lamda)
|
2375 |
+
|
2376 |
+
def density(self, x):
|
2377 |
+
k = self.gamma*x.key
|
2378 |
+
theta = 1/self.lamda
|
2379 |
+
return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k)
|
2380 |
+
|
2381 |
+
def simple_rv(self, rv):
|
2382 |
+
return Gamma(rv.name, self.gamma*rv.key, 1/self.lamda)
|
env-llmeval/lib/python3.10/site-packages/sympy/stats/symbolic_multivariate_probability.py
ADDED
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import itertools
|
2 |
+
|
3 |
+
from sympy.core.add import Add
|
4 |
+
from sympy.core.expr import Expr
|
5 |
+
from sympy.core.function import expand as _expand
|
6 |
+
from sympy.core.mul import Mul
|
7 |
+
from sympy.core.singleton import S
|
8 |
+
from sympy.matrices.common import ShapeError
|
9 |
+
from sympy.matrices.expressions.matexpr import MatrixExpr
|
10 |
+
from sympy.matrices.expressions.matmul import MatMul
|
11 |
+
from sympy.matrices.expressions.special import ZeroMatrix
|
12 |
+
from sympy.stats.rv import RandomSymbol, is_random
|
13 |
+
from sympy.core.sympify import _sympify
|
14 |
+
from sympy.stats.symbolic_probability import Variance, Covariance, Expectation
|
15 |
+
|
16 |
+
|
17 |
+
class ExpectationMatrix(Expectation, MatrixExpr):
|
18 |
+
"""
|
19 |
+
Expectation of a random matrix expression.
|
20 |
+
|
21 |
+
Examples
|
22 |
+
========
|
23 |
+
|
24 |
+
>>> from sympy.stats import ExpectationMatrix, Normal
|
25 |
+
>>> from sympy.stats.rv import RandomMatrixSymbol
|
26 |
+
>>> from sympy import symbols, MatrixSymbol, Matrix
|
27 |
+
>>> k = symbols("k")
|
28 |
+
>>> A, B = MatrixSymbol("A", k, k), MatrixSymbol("B", k, k)
|
29 |
+
>>> X, Y = RandomMatrixSymbol("X", k, 1), RandomMatrixSymbol("Y", k, 1)
|
30 |
+
>>> ExpectationMatrix(X)
|
31 |
+
ExpectationMatrix(X)
|
32 |
+
>>> ExpectationMatrix(A*X).shape
|
33 |
+
(k, 1)
|
34 |
+
|
35 |
+
To expand the expectation in its expression, use ``expand()``:
|
36 |
+
|
37 |
+
>>> ExpectationMatrix(A*X + B*Y).expand()
|
38 |
+
A*ExpectationMatrix(X) + B*ExpectationMatrix(Y)
|
39 |
+
>>> ExpectationMatrix((X + Y)*(X - Y).T).expand()
|
40 |
+
ExpectationMatrix(X*X.T) - ExpectationMatrix(X*Y.T) + ExpectationMatrix(Y*X.T) - ExpectationMatrix(Y*Y.T)
|
41 |
+
|
42 |
+
To evaluate the ``ExpectationMatrix``, use ``doit()``:
|
43 |
+
|
44 |
+
>>> N11, N12 = Normal('N11', 11, 1), Normal('N12', 12, 1)
|
45 |
+
>>> N21, N22 = Normal('N21', 21, 1), Normal('N22', 22, 1)
|
46 |
+
>>> M11, M12 = Normal('M11', 1, 1), Normal('M12', 2, 1)
|
47 |
+
>>> M21, M22 = Normal('M21', 3, 1), Normal('M22', 4, 1)
|
48 |
+
>>> x1 = Matrix([[N11, N12], [N21, N22]])
|
49 |
+
>>> x2 = Matrix([[M11, M12], [M21, M22]])
|
50 |
+
>>> ExpectationMatrix(x1 + x2).doit()
|
51 |
+
Matrix([
|
52 |
+
[12, 14],
|
53 |
+
[24, 26]])
|
54 |
+
|
55 |
+
"""
|
56 |
+
def __new__(cls, expr, condition=None):
|
57 |
+
expr = _sympify(expr)
|
58 |
+
if condition is None:
|
59 |
+
if not is_random(expr):
|
60 |
+
return expr
|
61 |
+
obj = Expr.__new__(cls, expr)
|
62 |
+
else:
|
63 |
+
condition = _sympify(condition)
|
64 |
+
obj = Expr.__new__(cls, expr, condition)
|
65 |
+
|
66 |
+
obj._shape = expr.shape
|
67 |
+
obj._condition = condition
|
68 |
+
return obj
|
69 |
+
|
70 |
+
@property
|
71 |
+
def shape(self):
|
72 |
+
return self._shape
|
73 |
+
|
74 |
+
def expand(self, **hints):
|
75 |
+
expr = self.args[0]
|
76 |
+
condition = self._condition
|
77 |
+
if not is_random(expr):
|
78 |
+
return expr
|
79 |
+
|
80 |
+
if isinstance(expr, Add):
|
81 |
+
return Add.fromiter(Expectation(a, condition=condition).expand()
|
82 |
+
for a in expr.args)
|
83 |
+
|
84 |
+
expand_expr = _expand(expr)
|
85 |
+
if isinstance(expand_expr, Add):
|
86 |
+
return Add.fromiter(Expectation(a, condition=condition).expand()
|
87 |
+
for a in expand_expr.args)
|
88 |
+
|
89 |
+
elif isinstance(expr, (Mul, MatMul)):
|
90 |
+
rv = []
|
91 |
+
nonrv = []
|
92 |
+
postnon = []
|
93 |
+
|
94 |
+
for a in expr.args:
|
95 |
+
if is_random(a):
|
96 |
+
if rv:
|
97 |
+
rv.extend(postnon)
|
98 |
+
else:
|
99 |
+
nonrv.extend(postnon)
|
100 |
+
postnon = []
|
101 |
+
rv.append(a)
|
102 |
+
elif a.is_Matrix:
|
103 |
+
postnon.append(a)
|
104 |
+
else:
|
105 |
+
nonrv.append(a)
|
106 |
+
|
107 |
+
# In order to avoid infinite-looping (MatMul may call .doit() again),
|
108 |
+
# do not rebuild
|
109 |
+
if len(nonrv) == 0:
|
110 |
+
return self
|
111 |
+
return Mul.fromiter(nonrv)*Expectation(Mul.fromiter(rv),
|
112 |
+
condition=condition)*Mul.fromiter(postnon)
|
113 |
+
|
114 |
+
return self
|
115 |
+
|
116 |
+
class VarianceMatrix(Variance, MatrixExpr):
|
117 |
+
"""
|
118 |
+
Variance of a random matrix probability expression. Also known as
|
119 |
+
Covariance matrix, auto-covariance matrix, dispersion matrix,
|
120 |
+
or variance-covariance matrix.
|
121 |
+
|
122 |
+
Examples
|
123 |
+
========
|
124 |
+
|
125 |
+
>>> from sympy.stats import VarianceMatrix
|
126 |
+
>>> from sympy.stats.rv import RandomMatrixSymbol
|
127 |
+
>>> from sympy import symbols, MatrixSymbol
|
128 |
+
>>> k = symbols("k")
|
129 |
+
>>> A, B = MatrixSymbol("A", k, k), MatrixSymbol("B", k, k)
|
130 |
+
>>> X, Y = RandomMatrixSymbol("X", k, 1), RandomMatrixSymbol("Y", k, 1)
|
131 |
+
>>> VarianceMatrix(X)
|
132 |
+
VarianceMatrix(X)
|
133 |
+
>>> VarianceMatrix(X).shape
|
134 |
+
(k, k)
|
135 |
+
|
136 |
+
To expand the variance in its expression, use ``expand()``:
|
137 |
+
|
138 |
+
>>> VarianceMatrix(A*X).expand()
|
139 |
+
A*VarianceMatrix(X)*A.T
|
140 |
+
>>> VarianceMatrix(A*X + B*Y).expand()
|
141 |
+
2*A*CrossCovarianceMatrix(X, Y)*B.T + A*VarianceMatrix(X)*A.T + B*VarianceMatrix(Y)*B.T
|
142 |
+
"""
|
143 |
+
def __new__(cls, arg, condition=None):
|
144 |
+
arg = _sympify(arg)
|
145 |
+
|
146 |
+
if 1 not in arg.shape:
|
147 |
+
raise ShapeError("Expression is not a vector")
|
148 |
+
|
149 |
+
shape = (arg.shape[0], arg.shape[0]) if arg.shape[1] == 1 else (arg.shape[1], arg.shape[1])
|
150 |
+
|
151 |
+
if condition:
|
152 |
+
obj = Expr.__new__(cls, arg, condition)
|
153 |
+
else:
|
154 |
+
obj = Expr.__new__(cls, arg)
|
155 |
+
|
156 |
+
obj._shape = shape
|
157 |
+
obj._condition = condition
|
158 |
+
return obj
|
159 |
+
|
160 |
+
@property
|
161 |
+
def shape(self):
|
162 |
+
return self._shape
|
163 |
+
|
164 |
+
def expand(self, **hints):
|
165 |
+
arg = self.args[0]
|
166 |
+
condition = self._condition
|
167 |
+
|
168 |
+
if not is_random(arg):
|
169 |
+
return ZeroMatrix(*self.shape)
|
170 |
+
|
171 |
+
if isinstance(arg, RandomSymbol):
|
172 |
+
return self
|
173 |
+
elif isinstance(arg, Add):
|
174 |
+
rv = []
|
175 |
+
for a in arg.args:
|
176 |
+
if is_random(a):
|
177 |
+
rv.append(a)
|
178 |
+
variances = Add(*(Variance(xv, condition).expand() for xv in rv))
|
179 |
+
map_to_covar = lambda x: 2*Covariance(*x, condition=condition).expand()
|
180 |
+
covariances = Add(*map(map_to_covar, itertools.combinations(rv, 2)))
|
181 |
+
return variances + covariances
|
182 |
+
elif isinstance(arg, (Mul, MatMul)):
|
183 |
+
nonrv = []
|
184 |
+
rv = []
|
185 |
+
for a in arg.args:
|
186 |
+
if is_random(a):
|
187 |
+
rv.append(a)
|
188 |
+
else:
|
189 |
+
nonrv.append(a)
|
190 |
+
if len(rv) == 0:
|
191 |
+
return ZeroMatrix(*self.shape)
|
192 |
+
# Avoid possible infinite loops with MatMul:
|
193 |
+
if len(nonrv) == 0:
|
194 |
+
return self
|
195 |
+
# Variance of many multiple matrix products is not implemented:
|
196 |
+
if len(rv) > 1:
|
197 |
+
return self
|
198 |
+
return Mul.fromiter(nonrv)*Variance(Mul.fromiter(rv),
|
199 |
+
condition)*(Mul.fromiter(nonrv)).transpose()
|
200 |
+
|
201 |
+
# this expression contains a RandomSymbol somehow:
|
202 |
+
return self
|
203 |
+
|
204 |
+
class CrossCovarianceMatrix(Covariance, MatrixExpr):
|
205 |
+
"""
|
206 |
+
Covariance of a random matrix probability expression.
|
207 |
+
|
208 |
+
Examples
|
209 |
+
========
|
210 |
+
|
211 |
+
>>> from sympy.stats import CrossCovarianceMatrix
|
212 |
+
>>> from sympy.stats.rv import RandomMatrixSymbol
|
213 |
+
>>> from sympy import symbols, MatrixSymbol
|
214 |
+
>>> k = symbols("k")
|
215 |
+
>>> A, B = MatrixSymbol("A", k, k), MatrixSymbol("B", k, k)
|
216 |
+
>>> C, D = MatrixSymbol("C", k, k), MatrixSymbol("D", k, k)
|
217 |
+
>>> X, Y = RandomMatrixSymbol("X", k, 1), RandomMatrixSymbol("Y", k, 1)
|
218 |
+
>>> Z, W = RandomMatrixSymbol("Z", k, 1), RandomMatrixSymbol("W", k, 1)
|
219 |
+
>>> CrossCovarianceMatrix(X, Y)
|
220 |
+
CrossCovarianceMatrix(X, Y)
|
221 |
+
>>> CrossCovarianceMatrix(X, Y).shape
|
222 |
+
(k, k)
|
223 |
+
|
224 |
+
To expand the covariance in its expression, use ``expand()``:
|
225 |
+
|
226 |
+
>>> CrossCovarianceMatrix(X + Y, Z).expand()
|
227 |
+
CrossCovarianceMatrix(X, Z) + CrossCovarianceMatrix(Y, Z)
|
228 |
+
>>> CrossCovarianceMatrix(A*X, Y).expand()
|
229 |
+
A*CrossCovarianceMatrix(X, Y)
|
230 |
+
>>> CrossCovarianceMatrix(A*X, B.T*Y).expand()
|
231 |
+
A*CrossCovarianceMatrix(X, Y)*B
|
232 |
+
>>> CrossCovarianceMatrix(A*X + B*Y, C.T*Z + D.T*W).expand()
|
233 |
+
A*CrossCovarianceMatrix(X, W)*D + A*CrossCovarianceMatrix(X, Z)*C + B*CrossCovarianceMatrix(Y, W)*D + B*CrossCovarianceMatrix(Y, Z)*C
|
234 |
+
|
235 |
+
"""
|
236 |
+
def __new__(cls, arg1, arg2, condition=None):
|
237 |
+
arg1 = _sympify(arg1)
|
238 |
+
arg2 = _sympify(arg2)
|
239 |
+
|
240 |
+
if (1 not in arg1.shape) or (1 not in arg2.shape) or (arg1.shape[1] != arg2.shape[1]):
|
241 |
+
raise ShapeError("Expression is not a vector")
|
242 |
+
|
243 |
+
shape = (arg1.shape[0], arg2.shape[0]) if arg1.shape[1] == 1 and arg2.shape[1] == 1 \
|
244 |
+
else (1, 1)
|
245 |
+
|
246 |
+
if condition:
|
247 |
+
obj = Expr.__new__(cls, arg1, arg2, condition)
|
248 |
+
else:
|
249 |
+
obj = Expr.__new__(cls, arg1, arg2)
|
250 |
+
|
251 |
+
obj._shape = shape
|
252 |
+
obj._condition = condition
|
253 |
+
return obj
|
254 |
+
|
255 |
+
@property
|
256 |
+
def shape(self):
|
257 |
+
return self._shape
|
258 |
+
|
259 |
+
def expand(self, **hints):
|
260 |
+
arg1 = self.args[0]
|
261 |
+
arg2 = self.args[1]
|
262 |
+
condition = self._condition
|
263 |
+
|
264 |
+
if arg1 == arg2:
|
265 |
+
return VarianceMatrix(arg1, condition).expand()
|
266 |
+
|
267 |
+
if not is_random(arg1) or not is_random(arg2):
|
268 |
+
return ZeroMatrix(*self.shape)
|
269 |
+
|
270 |
+
if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol):
|
271 |
+
return CrossCovarianceMatrix(arg1, arg2, condition)
|
272 |
+
|
273 |
+
coeff_rv_list1 = self._expand_single_argument(arg1.expand())
|
274 |
+
coeff_rv_list2 = self._expand_single_argument(arg2.expand())
|
275 |
+
|
276 |
+
addends = [a*CrossCovarianceMatrix(r1, r2, condition=condition)*b.transpose()
|
277 |
+
for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2]
|
278 |
+
return Add.fromiter(addends)
|
279 |
+
|
280 |
+
@classmethod
|
281 |
+
def _expand_single_argument(cls, expr):
|
282 |
+
# return (coefficient, random_symbol) pairs:
|
283 |
+
if isinstance(expr, RandomSymbol):
|
284 |
+
return [(S.One, expr)]
|
285 |
+
elif isinstance(expr, Add):
|
286 |
+
outval = []
|
287 |
+
for a in expr.args:
|
288 |
+
if isinstance(a, (Mul, MatMul)):
|
289 |
+
outval.append(cls._get_mul_nonrv_rv_tuple(a))
|
290 |
+
elif is_random(a):
|
291 |
+
outval.append((S.One, a))
|
292 |
+
|
293 |
+
return outval
|
294 |
+
elif isinstance(expr, (Mul, MatMul)):
|
295 |
+
return [cls._get_mul_nonrv_rv_tuple(expr)]
|
296 |
+
elif is_random(expr):
|
297 |
+
return [(S.One, expr)]
|
298 |
+
|
299 |
+
@classmethod
|
300 |
+
def _get_mul_nonrv_rv_tuple(cls, m):
|
301 |
+
rv = []
|
302 |
+
nonrv = []
|
303 |
+
for a in m.args:
|
304 |
+
if is_random(a):
|
305 |
+
rv.append(a)
|
306 |
+
else:
|
307 |
+
nonrv.append(a)
|
308 |
+
return (Mul.fromiter(nonrv), Mul.fromiter(rv))
|