Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step80/zero/18.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/18.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/18.mlp.dense_4h_to_h.weight/fp32.pt +3 -0
- ckpts/universal/global_step80/zero/20.input_layernorm.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/20.input_layernorm.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/22.mlp.dense_4h_to_h.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step80/zero/22.mlp.dense_4h_to_h.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step80/zero/3.post_attention_layernorm.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_deltafunctions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_failing_integrals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_lineintegrals.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_manual.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_meijerint.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_prde.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_quadrature.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_rationaltools.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_rde.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_singularityfunctions.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_trigonometry.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__init__.py +202 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/compound_rv.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/crv.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/crv_types.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/drv_types.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/error_prop.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/frv.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/frv_types.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv_types.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix_models.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/rv.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process_types.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_multivariate_probability.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/compound_rv.py +223 -0
- venv/lib/python3.10/site-packages/sympy/stats/crv.py +570 -0
- venv/lib/python3.10/site-packages/sympy/stats/crv_types.py +0 -0
- venv/lib/python3.10/site-packages/sympy/stats/drv.py +350 -0
- venv/lib/python3.10/site-packages/sympy/stats/drv_types.py +835 -0
- venv/lib/python3.10/site-packages/sympy/stats/error_prop.py +100 -0
- venv/lib/python3.10/site-packages/sympy/stats/frv.py +512 -0
- venv/lib/python3.10/site-packages/sympy/stats/frv_types.py +870 -0
- venv/lib/python3.10/site-packages/sympy/stats/joint_rv.py +426 -0
- venv/lib/python3.10/site-packages/sympy/stats/joint_rv_types.py +946 -0
- venv/lib/python3.10/site-packages/sympy/stats/matrix_distributions.py +610 -0
- venv/lib/python3.10/site-packages/sympy/stats/random_matrix.py +30 -0
- venv/lib/python3.10/site-packages/sympy/stats/random_matrix_models.py +457 -0
- venv/lib/python3.10/site-packages/sympy/stats/rv.py +1792 -0
- venv/lib/python3.10/site-packages/sympy/stats/rv_interface.py +519 -0
ckpts/universal/global_step80/zero/18.mlp.dense_4h_to_h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:175f191b8c7cc6115692bde56dc7c9e22924ad639e20c839427c8a2617c99c20
|
3 |
+
size 33555612
|
ckpts/universal/global_step80/zero/18.mlp.dense_4h_to_h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:87b94c4442ab0d21bb06f719b66772cb00996b1bda6c695c1a344f1290da1353
|
3 |
+
size 33555627
|
ckpts/universal/global_step80/zero/18.mlp.dense_4h_to_h.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:492bc29e64bea810c751a186153489871fe93e3d646018cd153e29c3e561445d
|
3 |
+
size 33555533
|
ckpts/universal/global_step80/zero/20.input_layernorm.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e1b074fced662f4d5015cdf1941a7555f15b2a01225f952d5eb86cdf75b24093
|
3 |
+
size 9372
|
ckpts/universal/global_step80/zero/20.input_layernorm.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f86b29c6332f1056cb30ba0c34d84ff35f141794d4fff5f0f5d1267fc9de7873
|
3 |
+
size 9387
|
ckpts/universal/global_step80/zero/22.mlp.dense_4h_to_h.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:227728043f5b430c5e468dc26f97f7cb1c65cb4e2a9a0281c75412ce8c3f6125
|
3 |
+
size 33555612
|
ckpts/universal/global_step80/zero/22.mlp.dense_4h_to_h.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:1d03a0ff087b9919bb9c72635a43f9bcf431a3681633b6a676568c761933c9c6
|
3 |
+
size 33555627
|
ckpts/universal/global_step80/zero/3.post_attention_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:da1196c99bfa9cbcf4c6c4978a40245d9dc2a6d0226e90cb01bae1d2581979aa
|
3 |
+
size 9293
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (189 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_deltafunctions.cpython-310.pyc
ADDED
Binary file (3.15 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_failing_integrals.cpython-310.pyc
ADDED
Binary file (9.91 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_lineintegrals.cpython-310.pyc
ADDED
Binary file (834 Bytes). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_manual.cpython-310.pyc
ADDED
Binary file (33.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_meijerint.cpython-310.pyc
ADDED
Binary file (27.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_prde.cpython-310.pyc
ADDED
Binary file (13.5 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_quadrature.cpython-310.pyc
ADDED
Binary file (22.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_rationaltools.cpython-310.pyc
ADDED
Binary file (6.46 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_rde.cpython-310.pyc
ADDED
Binary file (8.71 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_singularityfunctions.cpython-310.pyc
ADDED
Binary file (1.15 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/integrals/tests/__pycache__/test_trigonometry.cpython-310.pyc
ADDED
Binary file (3.67 kB). View file
|
|
venv/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)
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/compound_rv.cpython-310.pyc
ADDED
Binary file (8.3 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/crv.cpython-310.pyc
ADDED
Binary file (20.5 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/crv_types.cpython-310.pyc
ADDED
Binary file (127 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/drv_types.cpython-310.pyc
ADDED
Binary file (21.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/error_prop.cpython-310.pyc
ADDED
Binary file (3.41 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/frv.cpython-310.pyc
ADDED
Binary file (23.2 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/frv_types.cpython-310.pyc
ADDED
Binary file (27.6 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv_types.cpython-310.pyc
ADDED
Binary file (31.5 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix.cpython-310.pyc
ADDED
Binary file (1.44 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix_models.cpython-310.pyc
ADDED
Binary file (16.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/rv.cpython-310.pyc
ADDED
Binary file (55.9 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process.cpython-310.pyc
ADDED
Binary file (2.73 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process_types.cpython-310.pyc
ADDED
Binary file (77.8 kB). View file
|
|
venv/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_multivariate_probability.cpython-310.pyc
ADDED
Binary file (9.5 kB). View file
|
|
venv/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
|
venv/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
|
venv/lib/python3.10/site-packages/sympy/stats/crv_types.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
venv/lib/python3.10/site-packages/sympy/stats/drv.py
ADDED
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 = Dummy("p", real=True)
|
348 |
+
return Lambda(p, self.distribution.quantile(p, **kwargs))
|
349 |
+
else:
|
350 |
+
raise NotImplementedError()
|
venv/lib/python3.10/site-packages/sympy/stats/drv_types.py
ADDED
@@ -0,0 +1,835 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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)
|
venv/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
|
venv/lib/python3.10/site-packages/sympy/stats/frv.py
ADDED
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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)
|
venv/lib/python3.10/site-packages/sympy/stats/frv_types.py
ADDED
@@ -0,0 +1,870 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
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)
|
venv/lib/python3.10/site-packages/sympy/stats/joint_rv.py
ADDED
@@ -0,0 +1,426 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Joint Random Variables Module
|
3 |
+
|
4 |
+
See Also
|
5 |
+
========
|
6 |
+
sympy.stats.rv
|
7 |
+
sympy.stats.frv
|
8 |
+
sympy.stats.crv
|
9 |
+
sympy.stats.drv
|
10 |
+
"""
|
11 |
+
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)
|
venv/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])
|
venv/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)
|
venv/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)
|
venv/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()
|
venv/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()
|
venv/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
|