ZTWHHH commited on
Commit
b551bd3
·
verified ·
1 Parent(s): d2bd0c8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc +0 -0
  3. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/abstract_nodes.cpython-310.pyc +0 -0
  4. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc +0 -0
  5. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-310.pyc +0 -0
  6. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/cnodes.cpython-310.pyc +0 -0
  7. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/cxxnodes.cpython-310.pyc +0 -0
  8. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/fnodes.cpython-310.pyc +0 -0
  9. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/matrix_nodes.cpython-310.pyc +0 -0
  10. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-310.pyc +0 -0
  11. mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/pyutils.cpython-310.pyc +0 -0
  12. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-310.pyc +3 -0
  13. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_adjoint.cpython-310.pyc +0 -0
  14. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_blockmatrix.cpython-310.pyc +0 -0
  15. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_companion.cpython-310.pyc +0 -0
  16. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_determinant.cpython-310.pyc +0 -0
  17. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_funcmatrix.cpython-310.pyc +0 -0
  18. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_hadamard.cpython-310.pyc +0 -0
  19. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_kronecker.cpython-310.pyc +0 -0
  20. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_matmul.cpython-310.pyc +0 -0
  21. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_matpow.cpython-310.pyc +0 -0
  22. mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_sets.cpython-310.pyc +0 -0
  23. mplug_owl2/lib/python3.10/site-packages/sympy/stats/__init__.py +202 -0
  24. mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/drv.cpython-310.pyc +0 -0
  25. mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/frv_types.cpython-310.pyc +0 -0
  26. mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/matrix_distributions.cpython-310.pyc +0 -0
  27. mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix_models.cpython-310.pyc +0 -0
  28. mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/rv_interface.cpython-310.pyc +0 -0
  29. mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process.cpython-310.pyc +0 -0
  30. mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_probability.cpython-310.pyc +0 -0
  31. mplug_owl2/lib/python3.10/site-packages/sympy/stats/compound_rv.py +223 -0
  32. mplug_owl2/lib/python3.10/site-packages/sympy/stats/crv.py +570 -0
  33. mplug_owl2/lib/python3.10/site-packages/sympy/stats/crv_types.py +0 -0
  34. mplug_owl2/lib/python3.10/site-packages/sympy/stats/drv.py +350 -0
  35. mplug_owl2/lib/python3.10/site-packages/sympy/stats/drv_types.py +835 -0
  36. mplug_owl2/lib/python3.10/site-packages/sympy/stats/error_prop.py +100 -0
  37. mplug_owl2/lib/python3.10/site-packages/sympy/stats/frv.py +512 -0
  38. mplug_owl2/lib/python3.10/site-packages/sympy/stats/frv_types.py +870 -0
  39. mplug_owl2/lib/python3.10/site-packages/sympy/stats/joint_rv.py +426 -0
  40. mplug_owl2/lib/python3.10/site-packages/sympy/stats/joint_rv_types.py +945 -0
  41. mplug_owl2/lib/python3.10/site-packages/sympy/stats/matrix_distributions.py +610 -0
  42. mplug_owl2/lib/python3.10/site-packages/sympy/stats/random_matrix.py +30 -0
  43. mplug_owl2/lib/python3.10/site-packages/sympy/stats/random_matrix_models.py +457 -0
  44. mplug_owl2/lib/python3.10/site-packages/sympy/stats/rv.py +1798 -0
  45. mplug_owl2/lib/python3.10/site-packages/sympy/stats/rv_interface.py +519 -0
  46. mplug_owl2/lib/python3.10/site-packages/sympy/stats/stochastic_process.py +66 -0
  47. mplug_owl2/lib/python3.10/site-packages/sympy/stats/stochastic_process_types.py +2383 -0
  48. mplug_owl2/lib/python3.10/site-packages/sympy/stats/symbolic_multivariate_probability.py +308 -0
  49. mplug_owl2/lib/python3.10/site-packages/sympy/stats/symbolic_probability.py +698 -0
  50. mplug_owl2/lib/python3.10/site-packages/sympy/stats/tests/__init__.py +0 -0
.gitattributes CHANGED
@@ -702,3 +702,4 @@ mplug_owl2/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/
702
  mplug_owl2/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexparser.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
703
  mplug_owl2/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
704
  mplug_owl2/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
702
  mplug_owl2/lib/python3.10/site-packages/sympy/parsing/latex/_antlr/__pycache__/latexparser.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
703
  mplug_owl2/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
704
  mplug_owl2/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
705
+ mplug_owl2/lib/python3.10/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/abstract_nodes.cpython-310.pyc ADDED
Binary file (941 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc ADDED
Binary file (6.32 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-310.pyc ADDED
Binary file (14.1 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/cnodes.cpython-310.pyc ADDED
Binary file (4.89 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/cxxnodes.cpython-310.pyc ADDED
Binary file (692 Bytes). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/fnodes.cpython-310.pyc ADDED
Binary file (21.2 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/matrix_nodes.cpython-310.pyc ADDED
Binary file (2.76 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-310.pyc ADDED
Binary file (3.84 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/codegen/__pycache__/pyutils.cpython-310.pyc ADDED
Binary file (1.16 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/__pycache__/matrixbase.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:558dad26977758351f7e1f20dc612d13fbfa427de301ebefff68eaae2f52163d
3
+ size 164797
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_adjoint.cpython-310.pyc ADDED
Binary file (1.3 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_blockmatrix.cpython-310.pyc ADDED
Binary file (16.9 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_companion.cpython-310.pyc ADDED
Binary file (2.37 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_determinant.cpython-310.pyc ADDED
Binary file (2.89 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_funcmatrix.cpython-310.pyc ADDED
Binary file (3.71 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_hadamard.cpython-310.pyc ADDED
Binary file (5.59 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_kronecker.cpython-310.pyc ADDED
Binary file (5.83 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_matmul.cpython-310.pyc ADDED
Binary file (8.06 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_matpow.cpython-310.pyc ADDED
Binary file (8.64 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/matrices/expressions/tests/__pycache__/test_sets.cpython-310.pyc ADDED
Binary file (2.33 kB). View file
 
mplug_owl2/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', 'Davis', '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, Davis, 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)
mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/drv.cpython-310.pyc ADDED
Binary file (13.7 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/frv_types.cpython-310.pyc ADDED
Binary file (27.4 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/matrix_distributions.cpython-310.pyc ADDED
Binary file (19 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix_models.cpython-310.pyc ADDED
Binary file (16.9 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/rv_interface.cpython-310.pyc ADDED
Binary file (14 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process.cpython-310.pyc ADDED
Binary file (2.72 kB). View file
 
mplug_owl2/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_probability.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
mplug_owl2/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
mplug_owl2/lib/python3.10/site-packages/sympy/stats/crv.py ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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):
535
+ if len(gs.args) == 2 and gs.args[0] is S.Reals:
536
+ gs = gs.args[1]
537
+ if not gs.is_FiniteSet:
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
mplug_owl2/lib/python3.10/site-packages/sympy/stats/crv_types.py ADDED
The diff for this file is too large to render. See raw diff
 
mplug_owl2/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()
mplug_owl2/lib/python3.10/site-packages/sympy/stats/drv_types.py ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
mplug_owl2/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
mplug_owl2/lib/python3.10/site-packages/sympy/stats/frv.py ADDED
@@ -0,0 +1,512 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
mplug_owl2/lib/python3.10/site-packages/sympy/stats/frv_types.py ADDED
@@ -0,0 +1,870 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Finite Discrete Random Variables - Prebuilt variable types
3
+
4
+ Contains
5
+ ========
6
+ FiniteRV
7
+ DiscreteUniform
8
+ Die
9
+ Bernoulli
10
+ Coin
11
+ Binomial
12
+ BetaBinomial
13
+ Hypergeometric
14
+ Rademacher
15
+ IdealSoliton
16
+ RobustSoliton
17
+ """
18
+
19
+
20
+ from sympy.core.cache import cacheit
21
+ from sympy.core.function import Lambda
22
+ from sympy.core.numbers import (Integer, Rational)
23
+ from sympy.core.relational import (Eq, Ge, Gt, Le, Lt)
24
+ from sympy.core.singleton import S
25
+ from sympy.core.symbol import (Dummy, Symbol)
26
+ from sympy.core.sympify import sympify
27
+ from sympy.functions.combinatorial.factorials import binomial
28
+ from sympy.functions.elementary.exponential import log
29
+ from sympy.functions.elementary.piecewise import Piecewise
30
+ from sympy.logic.boolalg import Or
31
+ from sympy.sets.contains import Contains
32
+ from sympy.sets.fancysets import Range
33
+ from sympy.sets.sets import (Intersection, Interval)
34
+ from sympy.functions.special.beta_functions import beta as beta_fn
35
+ from sympy.stats.frv import (SingleFiniteDistribution,
36
+ SingleFinitePSpace)
37
+ from sympy.stats.rv import _value_check, Density, is_random
38
+ from sympy.utilities.iterables import multiset
39
+ from sympy.utilities.misc import filldedent
40
+
41
+
42
+ __all__ = ['FiniteRV',
43
+ 'DiscreteUniform',
44
+ 'Die',
45
+ 'Bernoulli',
46
+ 'Coin',
47
+ 'Binomial',
48
+ 'BetaBinomial',
49
+ 'Hypergeometric',
50
+ 'Rademacher',
51
+ 'IdealSoliton',
52
+ 'RobustSoliton',
53
+ ]
54
+
55
+ def rv(name, cls, *args, **kwargs):
56
+ args = list(map(sympify, args))
57
+ dist = cls(*args)
58
+ if kwargs.pop('check', True):
59
+ dist.check(*args)
60
+ pspace = SingleFinitePSpace(name, dist)
61
+ if any(is_random(arg) for arg in args):
62
+ from sympy.stats.compound_rv import CompoundPSpace, CompoundDistribution
63
+ pspace = CompoundPSpace(name, CompoundDistribution(dist))
64
+ return pspace.value
65
+
66
+ class FiniteDistributionHandmade(SingleFiniteDistribution):
67
+
68
+ @property
69
+ def dict(self):
70
+ return self.args[0]
71
+
72
+ def pmf(self, x):
73
+ x = Symbol('x')
74
+ return Lambda(x, Piecewise(*(
75
+ [(v, Eq(k, x)) for k, v in self.dict.items()] + [(S.Zero, True)])))
76
+
77
+ @property
78
+ def set(self):
79
+ return set(self.dict.keys())
80
+
81
+ @staticmethod
82
+ def check(density):
83
+ for p in density.values():
84
+ _value_check((p >= 0, p <= 1),
85
+ "Probability at a point must be between 0 and 1.")
86
+ val = sum(density.values())
87
+ _value_check(Eq(val, 1) != S.false, "Total Probability must be 1.")
88
+
89
+ def FiniteRV(name, density, **kwargs):
90
+ r"""
91
+ Create a Finite Random Variable given a dict representing the density.
92
+
93
+ Parameters
94
+ ==========
95
+
96
+ name : Symbol
97
+ Represents name of the random variable.
98
+ density : dict
99
+ Dictionary containing the pdf of finite distribution
100
+ check : bool
101
+ If True, it will check whether the given density
102
+ integrates to 1 over the given set. If False, it
103
+ will not perform this check. Default is False.
104
+
105
+ Examples
106
+ ========
107
+
108
+ >>> from sympy.stats import FiniteRV, P, E
109
+
110
+ >>> density = {0: .1, 1: .2, 2: .3, 3: .4}
111
+ >>> X = FiniteRV('X', density)
112
+
113
+ >>> E(X)
114
+ 2.00000000000000
115
+ >>> P(X >= 2)
116
+ 0.700000000000000
117
+
118
+ Returns
119
+ =======
120
+
121
+ RandomSymbol
122
+
123
+ """
124
+ # have a default of False while `rv` should have a default of True
125
+ kwargs['check'] = kwargs.pop('check', False)
126
+ return rv(name, FiniteDistributionHandmade, density, **kwargs)
127
+
128
+ class DiscreteUniformDistribution(SingleFiniteDistribution):
129
+
130
+ @staticmethod
131
+ def check(*args):
132
+ # not using _value_check since there is a
133
+ # suggestion for the user
134
+ if len(set(args)) != len(args):
135
+ weights = multiset(args)
136
+ n = Integer(len(args))
137
+ for k in weights:
138
+ weights[k] /= n
139
+ raise ValueError(filldedent("""
140
+ Repeated args detected but set expected. For a
141
+ distribution having different weights for each
142
+ item use the following:""") + (
143
+ '\nS("FiniteRV(%s, %s)")' % ("'X'", weights)))
144
+
145
+ @property
146
+ def p(self):
147
+ return Rational(1, len(self.args))
148
+
149
+ @property # type: ignore
150
+ @cacheit
151
+ def dict(self):
152
+ return dict.fromkeys(self.set, self.p)
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(m))
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)
mplug_owl2/lib/python3.10/site-packages/sympy/stats/joint_rv.py ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
mplug_owl2/lib/python3.10/site-packages/sympy/stats/joint_rv_types.py ADDED
@@ -0,0 +1,945 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.jstor.org/stable/24780825
637
+ """
638
+ return multivariate_rv(MultivariateEwensDistribution, syms, n, theta)
639
+
640
+ #-------------------------------------------------------------------------------
641
+ # Generalized Multivariate Log Gamma distribution ------------------------------
642
+
643
+ class GeneralizedMultivariateLogGammaDistribution(JointDistribution):
644
+
645
+ _argnames = ('delta', 'v', 'lamda', 'mu')
646
+ is_Continuous=True
647
+
648
+ def check(self, delta, v, l, mu):
649
+ _value_check((delta >= 0, delta <= 1), "delta must be in range [0, 1].")
650
+ _value_check((v > 0), "v must be positive")
651
+ for lk in l:
652
+ _value_check((lk > 0), "lamda must be a positive vector.")
653
+ for muk in mu:
654
+ _value_check((muk > 0), "mu must be a positive vector.")
655
+ _value_check(len(l) > 1,"the distribution should have at least"
656
+ " two random variables.")
657
+
658
+ @property
659
+ def set(self):
660
+ return S.Reals**len(self.lamda)
661
+
662
+ def pdf(self, *y):
663
+ d, v, l, mu = self.delta, self.v, self.lamda, self.mu
664
+ n = Symbol('n', negative=False, integer=True)
665
+ k = len(l)
666
+ sterm1 = Pow((1 - d), n)/\
667
+ ((gamma(v + n)**(k - 1))*gamma(v)*gamma(n + 1))
668
+ sterm2 = Mul.fromiter(mui*li**(-v - n) for mui, li in zip(mu, l))
669
+ term1 = sterm1 * sterm2
670
+ sterm3 = (v + n) * sum(mui * yi for mui, yi in zip(mu, y))
671
+ sterm4 = sum(exp(mui * yi)/li for (mui, yi, li) in zip(mu, y, l))
672
+ term2 = exp(sterm3 - sterm4)
673
+ return Pow(d, v) * Sum(term1 * term2, (n, 0, S.Infinity))
674
+
675
+ def GeneralizedMultivariateLogGamma(syms, delta, v, lamda, mu):
676
+ """
677
+ Creates a joint random variable with generalized multivariate log gamma
678
+ distribution.
679
+
680
+ The joint pdf can be found at [1].
681
+
682
+ Parameters
683
+ ==========
684
+
685
+ syms : list/tuple/set of symbols for identifying each component
686
+ delta : A constant in range $[0, 1]$
687
+ v : Positive real number
688
+ lamda : List of positive real numbers
689
+ mu : List of positive real numbers
690
+
691
+ Returns
692
+ =======
693
+
694
+ RandomSymbol
695
+
696
+ Examples
697
+ ========
698
+
699
+ >>> from sympy.stats import density
700
+ >>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGamma
701
+ >>> from sympy import symbols, S
702
+ >>> v = 1
703
+ >>> l, mu = [1, 1, 1], [1, 1, 1]
704
+ >>> d = S.Half
705
+ >>> y = symbols('y_1:4', positive=True)
706
+ >>> Gd = GeneralizedMultivariateLogGamma('G', d, v, l, mu)
707
+ >>> density(Gd)(y[0], y[1], y[2])
708
+ Sum(exp((n + 1)*(y_1 + y_2 + y_3) - exp(y_1) - exp(y_2) -
709
+ exp(y_3))/(2**n*gamma(n + 1)**3), (n, 0, oo))/2
710
+
711
+ References
712
+ ==========
713
+
714
+ .. [1] https://en.wikipedia.org/wiki/Generalized_multivariate_log-gamma_distribution
715
+ .. [2] https://www.researchgate.net/publication/234137346_On_a_multivariate_log-gamma_distribution_and_the_use_of_the_distribution_in_the_Bayesian_analysis
716
+
717
+ Note
718
+ ====
719
+
720
+ If the GeneralizedMultivariateLogGamma is too long to type use,
721
+
722
+ >>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGamma as GMVLG
723
+ >>> Gd = GMVLG('G', d, v, l, mu)
724
+
725
+ If you want to pass the matrix omega instead of the constant delta, then use
726
+ ``GeneralizedMultivariateLogGammaOmega``.
727
+
728
+ """
729
+ return multivariate_rv(GeneralizedMultivariateLogGammaDistribution,
730
+ syms, delta, v, lamda, mu)
731
+
732
+ def GeneralizedMultivariateLogGammaOmega(syms, omega, v, lamda, mu):
733
+ """
734
+ Extends GeneralizedMultivariateLogGamma.
735
+
736
+ Parameters
737
+ ==========
738
+
739
+ syms : list/tuple/set of symbols
740
+ For identifying each component
741
+ omega : A square matrix
742
+ Every element of square matrix must be absolute value of
743
+ square root of correlation coefficient
744
+ v : Positive real number
745
+ lamda : List of positive real numbers
746
+ mu : List of positive real numbers
747
+
748
+ Returns
749
+ =======
750
+
751
+ RandomSymbol
752
+
753
+ Examples
754
+ ========
755
+
756
+ >>> from sympy.stats import density
757
+ >>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega
758
+ >>> from sympy import Matrix, symbols, S
759
+ >>> omega = Matrix([[1, S.Half, S.Half], [S.Half, 1, S.Half], [S.Half, S.Half, 1]])
760
+ >>> v = 1
761
+ >>> l, mu = [1, 1, 1], [1, 1, 1]
762
+ >>> G = GeneralizedMultivariateLogGammaOmega('G', omega, v, l, mu)
763
+ >>> y = symbols('y_1:4', positive=True)
764
+ >>> density(G)(y[0], y[1], y[2])
765
+ sqrt(2)*Sum((1 - sqrt(2)/2)**n*exp((n + 1)*(y_1 + y_2 + y_3) - exp(y_1) -
766
+ exp(y_2) - exp(y_3))/gamma(n + 1)**3, (n, 0, oo))/2
767
+
768
+ References
769
+ ==========
770
+
771
+ .. [1] https://en.wikipedia.org/wiki/Generalized_multivariate_log-gamma_distribution
772
+ .. [2] https://www.researchgate.net/publication/234137346_On_a_multivariate_log-gamma_distribution_and_the_use_of_the_distribution_in_the_Bayesian_analysis
773
+
774
+ Notes
775
+ =====
776
+
777
+ If the GeneralizedMultivariateLogGammaOmega is too long to type use,
778
+
779
+ >>> from sympy.stats.joint_rv_types import GeneralizedMultivariateLogGammaOmega as GMVLGO
780
+ >>> G = GMVLGO('G', omega, v, l, mu)
781
+
782
+ """
783
+ _value_check((omega.is_square, isinstance(omega, Matrix)), "omega must be a"
784
+ " square matrix")
785
+ for val in omega.values():
786
+ _value_check((val >= 0, val <= 1),
787
+ "all values in matrix must be between 0 and 1(both inclusive).")
788
+ _value_check(omega.diagonal().equals(ones(1, omega.shape[0])),
789
+ "all the elements of diagonal should be 1.")
790
+ _value_check((omega.shape[0] == len(lamda), len(lamda) == len(mu)),
791
+ "lamda, mu should be of same length and omega should "
792
+ " be of shape (length of lamda, length of mu)")
793
+ _value_check(len(lamda) > 1,"the distribution should have at least"
794
+ " two random variables.")
795
+ delta = Pow(Rational(omega.det()), Rational(1, len(lamda) - 1))
796
+ return GeneralizedMultivariateLogGamma(syms, delta, v, lamda, mu)
797
+
798
+
799
+ #-------------------------------------------------------------------------------
800
+ # Multinomial distribution -----------------------------------------------------
801
+
802
+ class MultinomialDistribution(JointDistribution):
803
+
804
+ _argnames = ('n', 'p')
805
+ is_Continuous=False
806
+ is_Discrete = True
807
+
808
+ @staticmethod
809
+ def check(n, p):
810
+ _value_check(n > 0,
811
+ "number of trials must be a positive integer")
812
+ for p_k in p:
813
+ _value_check((p_k >= 0, p_k <= 1),
814
+ "probability must be in range [0, 1]")
815
+ _value_check(Eq(sum(p), 1),
816
+ "probabilities must sum to 1")
817
+
818
+ @property
819
+ def set(self):
820
+ return Intersection(S.Naturals0, Interval(0, self.n))**len(self.p)
821
+
822
+ def pdf(self, *x):
823
+ n, p = self.n, self.p
824
+ term_1 = factorial(n)/Mul.fromiter(factorial(x_k) for x_k in x)
825
+ term_2 = Mul.fromiter(p_k**x_k for p_k, x_k in zip(p, x))
826
+ return Piecewise((term_1 * term_2, Eq(sum(x), n)), (0, True))
827
+
828
+ def Multinomial(syms, n, *p):
829
+ """
830
+ Creates a discrete random variable with Multinomial Distribution.
831
+
832
+ The density of the said distribution can be found at [1].
833
+
834
+ Parameters
835
+ ==========
836
+
837
+ n : Positive integer
838
+ Represents number of trials
839
+ p : List of event probabilities
840
+ Must be in the range of $[0, 1]$.
841
+
842
+ Returns
843
+ =======
844
+
845
+ RandomSymbol
846
+
847
+ Examples
848
+ ========
849
+
850
+ >>> from sympy.stats import density, Multinomial, marginal_distribution
851
+ >>> from sympy import symbols
852
+ >>> x1, x2, x3 = symbols('x1, x2, x3', nonnegative=True, integer=True)
853
+ >>> p1, p2, p3 = symbols('p1, p2, p3', positive=True)
854
+ >>> M = Multinomial('M', 3, p1, p2, p3)
855
+ >>> density(M)(x1, x2, x3)
856
+ Piecewise((6*p1**x1*p2**x2*p3**x3/(factorial(x1)*factorial(x2)*factorial(x3)),
857
+ Eq(x1 + x2 + x3, 3)), (0, True))
858
+ >>> marginal_distribution(M, M[0])(x1).subs(x1, 1)
859
+ 3*p1*p2**2 + 6*p1*p2*p3 + 3*p1*p3**2
860
+
861
+ References
862
+ ==========
863
+
864
+ .. [1] https://en.wikipedia.org/wiki/Multinomial_distribution
865
+ .. [2] https://mathworld.wolfram.com/MultinomialDistribution.html
866
+
867
+ """
868
+ if not isinstance(p[0], list):
869
+ p = (list(p), )
870
+ return multivariate_rv(MultinomialDistribution, syms, n, p[0])
871
+
872
+ #-------------------------------------------------------------------------------
873
+ # Negative Multinomial Distribution --------------------------------------------
874
+
875
+ class NegativeMultinomialDistribution(JointDistribution):
876
+
877
+ _argnames = ('k0', 'p')
878
+ is_Continuous=False
879
+ is_Discrete = True
880
+
881
+ @staticmethod
882
+ def check(k0, p):
883
+ _value_check(k0 > 0,
884
+ "number of failures must be a positive integer")
885
+ for p_k in p:
886
+ _value_check((p_k >= 0, p_k <= 1),
887
+ "probability must be in range [0, 1].")
888
+ _value_check(sum(p) <= 1,
889
+ "success probabilities must not be greater than 1.")
890
+
891
+ @property
892
+ def set(self):
893
+ return Range(0, S.Infinity)**len(self.p)
894
+
895
+ def pdf(self, *k):
896
+ k0, p = self.k0, self.p
897
+ term_1 = (gamma(k0 + sum(k))*(1 - sum(p))**k0)/gamma(k0)
898
+ term_2 = Mul.fromiter(pi**ki/factorial(ki) for pi, ki in zip(p, k))
899
+ return term_1 * term_2
900
+
901
+ def NegativeMultinomial(syms, k0, *p):
902
+ """
903
+ Creates a discrete random variable with Negative Multinomial Distribution.
904
+
905
+ The density of the said distribution can be found at [1].
906
+
907
+ Parameters
908
+ ==========
909
+
910
+ k0 : positive integer
911
+ Represents number of failures before the experiment is stopped
912
+ p : List of event probabilities
913
+ Must be in the range of $[0, 1]$
914
+
915
+ Returns
916
+ =======
917
+
918
+ RandomSymbol
919
+
920
+ Examples
921
+ ========
922
+
923
+ >>> from sympy.stats import density, NegativeMultinomial, marginal_distribution
924
+ >>> from sympy import symbols
925
+ >>> x1, x2, x3 = symbols('x1, x2, x3', nonnegative=True, integer=True)
926
+ >>> p1, p2, p3 = symbols('p1, p2, p3', positive=True)
927
+ >>> N = NegativeMultinomial('M', 3, p1, p2, p3)
928
+ >>> N_c = NegativeMultinomial('M', 3, 0.1, 0.1, 0.1)
929
+ >>> density(N)(x1, x2, x3)
930
+ p1**x1*p2**x2*p3**x3*(-p1 - p2 - p3 + 1)**3*gamma(x1 + x2 +
931
+ x3 + 3)/(2*factorial(x1)*factorial(x2)*factorial(x3))
932
+ >>> marginal_distribution(N_c, N_c[0])(1).evalf().round(2)
933
+ 0.25
934
+
935
+
936
+ References
937
+ ==========
938
+
939
+ .. [1] https://en.wikipedia.org/wiki/Negative_multinomial_distribution
940
+ .. [2] https://mathworld.wolfram.com/NegativeBinomialDistribution.html
941
+
942
+ """
943
+ if not isinstance(p[0], list):
944
+ p = (list(p), )
945
+ return multivariate_rv(NegativeMultinomialDistribution, syms, k0, p[0])
mplug_owl2/lib/python3.10/site-packages/sympy/stats/matrix_distributions.py ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
mplug_owl2/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)
mplug_owl2/lib/python3.10/site-packages/sympy/stats/random_matrix_models.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
mplug_owl2/lib/python3.10/site-packages/sympy/stats/rv.py ADDED
@@ -0,0 +1,1798 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ __doctest_requires__ = {('sample',): ['scipy']}
48
+
49
+
50
+ x = Symbol('x')
51
+
52
+
53
+ @singledispatch
54
+ def is_random(x):
55
+ return False
56
+
57
+
58
+ @is_random.register(Basic)
59
+ def _(x):
60
+ atoms = x.free_symbols
61
+ return any(is_random(i) for i in atoms)
62
+
63
+
64
+ class RandomDomain(Basic):
65
+ """
66
+ Represents a set of variables and the values which they can take.
67
+
68
+ See Also
69
+ ========
70
+
71
+ sympy.stats.crv.ContinuousDomain
72
+ sympy.stats.frv.FiniteDomain
73
+ """
74
+
75
+ is_ProductDomain = False
76
+ is_Finite = False
77
+ is_Continuous = False
78
+ is_Discrete = False
79
+
80
+ def __new__(cls, symbols, *args):
81
+ symbols = FiniteSet(*symbols)
82
+ return Basic.__new__(cls, symbols, *args)
83
+
84
+ @property
85
+ def symbols(self):
86
+ return self.args[0]
87
+
88
+ @property
89
+ def set(self):
90
+ return self.args[1]
91
+
92
+ def __contains__(self, other):
93
+ raise NotImplementedError()
94
+
95
+ def compute_expectation(self, expr):
96
+ raise NotImplementedError()
97
+
98
+
99
+ class SingleDomain(RandomDomain):
100
+ """
101
+ A single variable and its domain.
102
+
103
+ See Also
104
+ ========
105
+
106
+ sympy.stats.crv.SingleContinuousDomain
107
+ sympy.stats.frv.SingleFiniteDomain
108
+ """
109
+ def __new__(cls, symbol, set):
110
+ assert symbol.is_Symbol
111
+ return Basic.__new__(cls, symbol, set)
112
+
113
+ @property
114
+ def symbol(self):
115
+ return self.args[0]
116
+
117
+ @property
118
+ def symbols(self):
119
+ return FiniteSet(self.symbol)
120
+
121
+ def __contains__(self, other):
122
+ if len(other) != 1:
123
+ return False
124
+ sym, val = tuple(other)[0]
125
+ return self.symbol == sym and val in self.set
126
+
127
+
128
+ class MatrixDomain(RandomDomain):
129
+ """
130
+ A Random Matrix variable and its domain.
131
+
132
+ """
133
+ def __new__(cls, symbol, set):
134
+ symbol, set = _symbol_converter(symbol), _sympify(set)
135
+ return Basic.__new__(cls, symbol, set)
136
+
137
+ @property
138
+ def symbol(self):
139
+ return self.args[0]
140
+
141
+ @property
142
+ def symbols(self):
143
+ return FiniteSet(self.symbol)
144
+
145
+
146
+ class ConditionalDomain(RandomDomain):
147
+ """
148
+ A RandomDomain with an attached condition.
149
+
150
+ See Also
151
+ ========
152
+
153
+ sympy.stats.crv.ConditionalContinuousDomain
154
+ sympy.stats.frv.ConditionalFiniteDomain
155
+ """
156
+ def __new__(cls, fulldomain, condition):
157
+ condition = condition.xreplace({rs: rs.symbol
158
+ for rs in random_symbols(condition)})
159
+ return Basic.__new__(cls, fulldomain, condition)
160
+
161
+ @property
162
+ def symbols(self):
163
+ return self.fulldomain.symbols
164
+
165
+ @property
166
+ def fulldomain(self):
167
+ return self.args[0]
168
+
169
+ @property
170
+ def condition(self):
171
+ return self.args[1]
172
+
173
+ @property
174
+ def set(self):
175
+ raise NotImplementedError("Set of Conditional Domain not Implemented")
176
+
177
+ def as_boolean(self):
178
+ return And(self.fulldomain.as_boolean(), self.condition)
179
+
180
+
181
+ class PSpace(Basic):
182
+ """
183
+ A Probability Space.
184
+
185
+ Explanation
186
+ ===========
187
+
188
+ Probability Spaces encode processes that equal different values
189
+ probabilistically. These underly Random Symbols which occur in SymPy
190
+ expressions and contain the mechanics to evaluate statistical statements.
191
+
192
+ See Also
193
+ ========
194
+
195
+ sympy.stats.crv.ContinuousPSpace
196
+ sympy.stats.frv.FinitePSpace
197
+ """
198
+
199
+ is_Finite = None # type: bool
200
+ is_Continuous = None # type: bool
201
+ is_Discrete = None # type: bool
202
+ is_real = None # type: bool
203
+
204
+ @property
205
+ def domain(self):
206
+ return self.args[0]
207
+
208
+ @property
209
+ def density(self):
210
+ return self.args[1]
211
+
212
+ @property
213
+ def values(self):
214
+ return frozenset(RandomSymbol(sym, self) for sym in self.symbols)
215
+
216
+ @property
217
+ def symbols(self):
218
+ return self.domain.symbols
219
+
220
+ def where(self, condition):
221
+ raise NotImplementedError()
222
+
223
+ def compute_density(self, expr):
224
+ raise NotImplementedError()
225
+
226
+ def sample(self, size=(), library='scipy', seed=None):
227
+ raise NotImplementedError()
228
+
229
+ def probability(self, condition):
230
+ raise NotImplementedError()
231
+
232
+ def compute_expectation(self, expr):
233
+ raise NotImplementedError()
234
+
235
+
236
+ class SinglePSpace(PSpace):
237
+ """
238
+ Represents the probabilities of a set of random events that can be
239
+ attributed to a single variable/symbol.
240
+ """
241
+ def __new__(cls, s, distribution):
242
+ s = _symbol_converter(s)
243
+ return Basic.__new__(cls, s, distribution)
244
+
245
+ @property
246
+ def value(self):
247
+ return RandomSymbol(self.symbol, self)
248
+
249
+ @property
250
+ def symbol(self):
251
+ return self.args[0]
252
+
253
+ @property
254
+ def distribution(self):
255
+ return self.args[1]
256
+
257
+ @property
258
+ def pdf(self):
259
+ return self.distribution.pdf(self.symbol)
260
+
261
+
262
+ class RandomSymbol(Expr):
263
+ """
264
+ Random Symbols represent ProbabilitySpaces in SymPy Expressions.
265
+ In principle they can take on any value that their symbol can take on
266
+ within the associated PSpace with probability determined by the PSpace
267
+ Density.
268
+
269
+ Explanation
270
+ ===========
271
+
272
+ Random Symbols contain pspace and symbol properties.
273
+ The pspace property points to the represented Probability Space
274
+ The symbol is a standard SymPy Symbol that is used in that probability space
275
+ for example in defining a density.
276
+
277
+ You can form normal SymPy expressions using RandomSymbols and operate on
278
+ those expressions with the Functions
279
+
280
+ E - Expectation of a random expression
281
+ P - Probability of a condition
282
+ density - Probability Density of an expression
283
+ given - A new random expression (with new random symbols) given a condition
284
+
285
+ An object of the RandomSymbol type should almost never be created by the
286
+ user. They tend to be created instead by the PSpace class's value method.
287
+ Traditionally a user does not even do this but instead calls one of the
288
+ convenience functions Normal, Exponential, Coin, Die, FiniteRV, etc....
289
+ """
290
+
291
+ def __new__(cls, symbol, pspace=None):
292
+ from sympy.stats.joint_rv import JointRandomSymbol
293
+ if pspace is None:
294
+ # Allow single arg, representing pspace == PSpace()
295
+ pspace = PSpace()
296
+ symbol = _symbol_converter(symbol)
297
+ if not isinstance(pspace, PSpace):
298
+ raise TypeError("pspace variable should be of type PSpace")
299
+ if cls == JointRandomSymbol and isinstance(pspace, SinglePSpace):
300
+ cls = RandomSymbol
301
+ return Basic.__new__(cls, symbol, pspace)
302
+
303
+ is_finite = True
304
+ is_symbol = True
305
+ is_Atom = True
306
+
307
+ _diff_wrt = True
308
+
309
+ pspace = property(lambda self: self.args[1])
310
+ symbol = property(lambda self: self.args[0])
311
+ name = property(lambda self: self.symbol.name)
312
+
313
+ def _eval_is_positive(self):
314
+ return self.symbol.is_positive
315
+
316
+ def _eval_is_integer(self):
317
+ return self.symbol.is_integer
318
+
319
+ def _eval_is_real(self):
320
+ return self.symbol.is_real or self.pspace.is_real
321
+
322
+ @property
323
+ def is_commutative(self):
324
+ return self.symbol.is_commutative
325
+
326
+ @property
327
+ def free_symbols(self):
328
+ return {self}
329
+
330
+ class RandomIndexedSymbol(RandomSymbol):
331
+
332
+ def __new__(cls, idx_obj, pspace=None):
333
+ if pspace is None:
334
+ # Allow single arg, representing pspace == PSpace()
335
+ pspace = PSpace()
336
+ if not isinstance(idx_obj, (Indexed, Function)):
337
+ raise TypeError("An Function or Indexed object is expected not %s"%(idx_obj))
338
+ return Basic.__new__(cls, idx_obj, pspace)
339
+
340
+ symbol = property(lambda self: self.args[0])
341
+ name = property(lambda self: str(self.args[0]))
342
+
343
+ @property
344
+ def key(self):
345
+ if isinstance(self.symbol, Indexed):
346
+ return self.symbol.args[1]
347
+ elif isinstance(self.symbol, Function):
348
+ return self.symbol.args[0]
349
+
350
+ @property
351
+ def free_symbols(self):
352
+ if self.key.free_symbols:
353
+ free_syms = self.key.free_symbols
354
+ free_syms.add(self)
355
+ return free_syms
356
+ return {self}
357
+
358
+ @property
359
+ def pspace(self):
360
+ return self.args[1]
361
+
362
+ class RandomMatrixSymbol(RandomSymbol, MatrixSymbol): # type: ignore
363
+ def __new__(cls, symbol, n, m, pspace=None):
364
+ n, m = _sympify(n), _sympify(m)
365
+ symbol = _symbol_converter(symbol)
366
+ if pspace is None:
367
+ # Allow single arg, representing pspace == PSpace()
368
+ pspace = PSpace()
369
+ return Basic.__new__(cls, symbol, n, m, pspace)
370
+
371
+ symbol = property(lambda self: self.args[0])
372
+ pspace = property(lambda self: self.args[3])
373
+
374
+
375
+ class ProductPSpace(PSpace):
376
+ """
377
+ Abstract class for representing probability spaces with multiple random
378
+ variables.
379
+
380
+ See Also
381
+ ========
382
+
383
+ sympy.stats.rv.IndependentProductPSpace
384
+ sympy.stats.joint_rv.JointPSpace
385
+ """
386
+ pass
387
+
388
+ class IndependentProductPSpace(ProductPSpace):
389
+ """
390
+ A probability space resulting from the merger of two independent probability
391
+ spaces.
392
+
393
+ Often created using the function, pspace.
394
+ """
395
+
396
+ def __new__(cls, *spaces):
397
+ rs_space_dict = {}
398
+ for space in spaces:
399
+ for value in space.values:
400
+ rs_space_dict[value] = space
401
+
402
+ symbols = FiniteSet(*[val.symbol for val in rs_space_dict.keys()])
403
+
404
+ # Overlapping symbols
405
+ from sympy.stats.joint_rv import MarginalDistribution
406
+ from sympy.stats.compound_rv import CompoundDistribution
407
+ if len(symbols) < sum(len(space.symbols) for space in spaces if not
408
+ isinstance(space.distribution, (
409
+ CompoundDistribution, MarginalDistribution))):
410
+ raise ValueError("Overlapping Random Variables")
411
+
412
+ if all(space.is_Finite for space in spaces):
413
+ from sympy.stats.frv import ProductFinitePSpace
414
+ cls = ProductFinitePSpace
415
+
416
+ obj = Basic.__new__(cls, *FiniteSet(*spaces))
417
+
418
+ return obj
419
+
420
+ @property
421
+ def pdf(self):
422
+ p = Mul(*[space.pdf for space in self.spaces])
423
+ return p.subs({rv: rv.symbol for rv in self.values})
424
+
425
+ @property
426
+ def rs_space_dict(self):
427
+ d = {}
428
+ for space in self.spaces:
429
+ for value in space.values:
430
+ d[value] = space
431
+ return d
432
+
433
+ @property
434
+ def symbols(self):
435
+ return FiniteSet(*[val.symbol for val in self.rs_space_dict.keys()])
436
+
437
+ @property
438
+ def spaces(self):
439
+ return FiniteSet(*self.args)
440
+
441
+ @property
442
+ def values(self):
443
+ return sumsets(space.values for space in self.spaces)
444
+
445
+ def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
446
+ rvs = rvs or self.values
447
+ rvs = frozenset(rvs)
448
+ for space in self.spaces:
449
+ expr = space.compute_expectation(expr, rvs & space.values, evaluate=False, **kwargs)
450
+ if evaluate and hasattr(expr, 'doit'):
451
+ return expr.doit(**kwargs)
452
+ return expr
453
+
454
+ @property
455
+ def domain(self):
456
+ return ProductDomain(*[space.domain for space in self.spaces])
457
+
458
+ @property
459
+ def density(self):
460
+ raise NotImplementedError("Density not available for ProductSpaces")
461
+
462
+ def sample(self, size=(), library='scipy', seed=None):
463
+ return {k: v for space in self.spaces
464
+ for k, v in space.sample(size=size, library=library, seed=seed).items()}
465
+
466
+
467
+ def probability(self, condition, **kwargs):
468
+ cond_inv = False
469
+ if isinstance(condition, Ne):
470
+ condition = Eq(condition.args[0], condition.args[1])
471
+ cond_inv = True
472
+ elif isinstance(condition, And): # they are independent
473
+ return Mul(*[self.probability(arg) for arg in condition.args])
474
+ elif isinstance(condition, Or): # they are independent
475
+ return Add(*[self.probability(arg) for arg in condition.args])
476
+ expr = condition.lhs - condition.rhs
477
+ rvs = random_symbols(expr)
478
+ dens = self.compute_density(expr)
479
+ if any(pspace(rv).is_Continuous for rv in rvs):
480
+ from sympy.stats.crv import SingleContinuousPSpace
481
+ from sympy.stats.crv_types import ContinuousDistributionHandmade
482
+ if expr in self.values:
483
+ # Marginalize all other random symbols out of the density
484
+ randomsymbols = tuple(set(self.values) - frozenset([expr]))
485
+ symbols = tuple(rs.symbol for rs in randomsymbols)
486
+ pdf = self.domain.integrate(self.pdf, symbols, **kwargs)
487
+ return Lambda(expr.symbol, pdf)
488
+ dens = ContinuousDistributionHandmade(dens)
489
+ z = Dummy('z', real=True)
490
+ space = SingleContinuousPSpace(z, dens)
491
+ result = space.probability(condition.__class__(space.value, 0))
492
+ else:
493
+ from sympy.stats.drv import SingleDiscretePSpace
494
+ from sympy.stats.drv_types import DiscreteDistributionHandmade
495
+ dens = DiscreteDistributionHandmade(dens)
496
+ z = Dummy('z', integer=True)
497
+ space = SingleDiscretePSpace(z, dens)
498
+ result = space.probability(condition.__class__(space.value, 0))
499
+ return result if not cond_inv else S.One - result
500
+
501
+ def compute_density(self, expr, **kwargs):
502
+ rvs = random_symbols(expr)
503
+ if any(pspace(rv).is_Continuous for rv in rvs):
504
+ z = Dummy('z', real=True)
505
+ expr = self.compute_expectation(DiracDelta(expr - z),
506
+ **kwargs)
507
+ else:
508
+ z = Dummy('z', integer=True)
509
+ expr = self.compute_expectation(KroneckerDelta(expr, z),
510
+ **kwargs)
511
+ return Lambda(z, expr)
512
+
513
+ def compute_cdf(self, expr, **kwargs):
514
+ raise ValueError("CDF not well defined on multivariate expressions")
515
+
516
+ def conditional_space(self, condition, normalize=True, **kwargs):
517
+ rvs = random_symbols(condition)
518
+ condition = condition.xreplace({rv: rv.symbol for rv in self.values})
519
+ pspaces = [pspace(rv) for rv in rvs]
520
+ if any(ps.is_Continuous for ps in pspaces):
521
+ from sympy.stats.crv import (ConditionalContinuousDomain,
522
+ ContinuousPSpace)
523
+ space = ContinuousPSpace
524
+ domain = ConditionalContinuousDomain(self.domain, condition)
525
+ elif any(ps.is_Discrete for ps in pspaces):
526
+ from sympy.stats.drv import (ConditionalDiscreteDomain,
527
+ DiscretePSpace)
528
+ space = DiscretePSpace
529
+ domain = ConditionalDiscreteDomain(self.domain, condition)
530
+ elif all(ps.is_Finite for ps in pspaces):
531
+ from sympy.stats.frv import FinitePSpace
532
+ return FinitePSpace.conditional_space(self, condition)
533
+ if normalize:
534
+ replacement = {rv: Dummy(str(rv)) for rv in self.symbols}
535
+ norm = domain.compute_expectation(self.pdf, **kwargs)
536
+ pdf = self.pdf / norm.xreplace(replacement)
537
+ # XXX: Converting symbols from set to tuple. The order matters to
538
+ # Lambda though so we shouldn't be starting with a set here...
539
+ density = Lambda(tuple(domain.symbols), pdf)
540
+
541
+ return space(domain, density)
542
+
543
+ class ProductDomain(RandomDomain):
544
+ """
545
+ A domain resulting from the merger of two independent domains.
546
+
547
+ See Also
548
+ ========
549
+ sympy.stats.crv.ProductContinuousDomain
550
+ sympy.stats.frv.ProductFiniteDomain
551
+ """
552
+ is_ProductDomain = True
553
+
554
+ def __new__(cls, *domains):
555
+ # Flatten any product of products
556
+ domains2 = []
557
+ for domain in domains:
558
+ if not domain.is_ProductDomain:
559
+ domains2.append(domain)
560
+ else:
561
+ domains2.extend(domain.domains)
562
+ domains2 = FiniteSet(*domains2)
563
+
564
+ if all(domain.is_Finite for domain in domains2):
565
+ from sympy.stats.frv import ProductFiniteDomain
566
+ cls = ProductFiniteDomain
567
+ if all(domain.is_Continuous for domain in domains2):
568
+ from sympy.stats.crv import ProductContinuousDomain
569
+ cls = ProductContinuousDomain
570
+ if all(domain.is_Discrete for domain in domains2):
571
+ from sympy.stats.drv import ProductDiscreteDomain
572
+ cls = ProductDiscreteDomain
573
+
574
+ return Basic.__new__(cls, *domains2)
575
+
576
+ @property
577
+ def sym_domain_dict(self):
578
+ return {symbol: domain for domain in self.domains
579
+ for symbol in domain.symbols}
580
+
581
+ @property
582
+ def symbols(self):
583
+ return FiniteSet(*[sym for domain in self.domains
584
+ for sym in domain.symbols])
585
+
586
+ @property
587
+ def domains(self):
588
+ return self.args
589
+
590
+ @property
591
+ def set(self):
592
+ return ProductSet(*(domain.set for domain in self.domains))
593
+
594
+ def __contains__(self, other):
595
+ # Split event into each subdomain
596
+ for domain in self.domains:
597
+ # Collect the parts of this event which associate to this domain
598
+ elem = frozenset([item for item in other
599
+ if sympify(domain.symbols.contains(item[0]))
600
+ is S.true])
601
+ # Test this sub-event
602
+ if elem not in domain:
603
+ return False
604
+ # All subevents passed
605
+ return True
606
+
607
+ def as_boolean(self):
608
+ return And(*[domain.as_boolean() for domain in self.domains])
609
+
610
+
611
+ def random_symbols(expr):
612
+ """
613
+ Returns all RandomSymbols within a SymPy Expression.
614
+ """
615
+ atoms = getattr(expr, 'atoms', None)
616
+ if atoms is not None:
617
+ comp = lambda rv: rv.symbol.name
618
+ l = list(atoms(RandomSymbol))
619
+ return sorted(l, key=comp)
620
+ else:
621
+ return []
622
+
623
+
624
+ def pspace(expr):
625
+ """
626
+ Returns the underlying Probability Space of a random expression.
627
+
628
+ For internal use.
629
+
630
+ Examples
631
+ ========
632
+
633
+ >>> from sympy.stats import pspace, Normal
634
+ >>> X = Normal('X', 0, 1)
635
+ >>> pspace(2*X + 1) == X.pspace
636
+ True
637
+ """
638
+ expr = sympify(expr)
639
+ if isinstance(expr, RandomSymbol) and expr.pspace is not None:
640
+ return expr.pspace
641
+ if expr.has(RandomMatrixSymbol):
642
+ rm = list(expr.atoms(RandomMatrixSymbol))[0]
643
+ return rm.pspace
644
+
645
+ rvs = random_symbols(expr)
646
+ if not rvs:
647
+ raise ValueError("Expression containing Random Variable expected, not %s" % (expr))
648
+ # If only one space present
649
+ if all(rv.pspace == rvs[0].pspace for rv in rvs):
650
+ return rvs[0].pspace
651
+ from sympy.stats.compound_rv import CompoundPSpace
652
+ from sympy.stats.stochastic_process import StochasticPSpace
653
+ for rv in rvs:
654
+ if isinstance(rv.pspace, (CompoundPSpace, StochasticPSpace)):
655
+ return rv.pspace
656
+ # Otherwise make a product space
657
+ return IndependentProductPSpace(*[rv.pspace for rv in rvs])
658
+
659
+
660
+ def sumsets(sets):
661
+ """
662
+ Union of sets
663
+ """
664
+ return frozenset().union(*sets)
665
+
666
+
667
+ def rs_swap(a, b):
668
+ """
669
+ Build a dictionary to swap RandomSymbols based on their underlying symbol.
670
+
671
+ i.e.
672
+ if ``X = ('x', pspace1)``
673
+ and ``Y = ('x', pspace2)``
674
+ then ``X`` and ``Y`` match and the key, value pair
675
+ ``{X:Y}`` will appear in the result
676
+
677
+ Inputs: collections a and b of random variables which share common symbols
678
+ Output: dict mapping RVs in a to RVs in b
679
+ """
680
+ d = {}
681
+ for rsa in a:
682
+ d[rsa] = [rsb for rsb in b if rsa.symbol == rsb.symbol][0]
683
+ return d
684
+
685
+
686
+ def given(expr, condition=None, **kwargs):
687
+ r""" Conditional Random Expression.
688
+
689
+ Explanation
690
+ ===========
691
+
692
+ From a random expression and a condition on that expression creates a new
693
+ probability space from the condition and returns the same expression on that
694
+ conditional probability space.
695
+
696
+ Examples
697
+ ========
698
+
699
+ >>> from sympy.stats import given, density, Die
700
+ >>> X = Die('X', 6)
701
+ >>> Y = given(X, X > 3)
702
+ >>> density(Y).dict
703
+ {4: 1/3, 5: 1/3, 6: 1/3}
704
+
705
+ Following convention, if the condition is a random symbol then that symbol
706
+ is considered fixed.
707
+
708
+ >>> from sympy.stats import Normal
709
+ >>> from sympy import pprint
710
+ >>> from sympy.abc import z
711
+
712
+ >>> X = Normal('X', 0, 1)
713
+ >>> Y = Normal('Y', 0, 1)
714
+ >>> pprint(density(X + Y, Y)(z), use_unicode=False)
715
+ 2
716
+ -(-Y + z)
717
+ -----------
718
+ ___ 2
719
+ \/ 2 *e
720
+ ------------------
721
+ ____
722
+ 2*\/ pi
723
+ """
724
+
725
+ if not is_random(condition) or pspace_independent(expr, condition):
726
+ return expr
727
+
728
+ if isinstance(condition, RandomSymbol):
729
+ condition = Eq(condition, condition.symbol)
730
+
731
+ condsymbols = random_symbols(condition)
732
+ if (isinstance(condition, Eq) and len(condsymbols) == 1 and
733
+ not isinstance(pspace(expr).domain, ConditionalDomain)):
734
+ rv = tuple(condsymbols)[0]
735
+
736
+ results = solveset(condition, rv)
737
+ if isinstance(results, Intersection) and S.Reals in results.args:
738
+ results = list(results.args[1])
739
+
740
+ sums = 0
741
+ for res in results:
742
+ temp = expr.subs(rv, res)
743
+ if temp == True:
744
+ return True
745
+ if temp != False:
746
+ # XXX: This seems nonsensical but preserves existing behaviour
747
+ # after the change that Relational is no longer a subclass of
748
+ # Expr. Here expr is sometimes Relational and sometimes Expr
749
+ # but we are trying to add them with +=. This needs to be
750
+ # fixed somehow.
751
+ if sums == 0 and isinstance(expr, Relational):
752
+ sums = expr.subs(rv, res)
753
+ else:
754
+ sums += expr.subs(rv, res)
755
+ if sums == 0:
756
+ return False
757
+ return sums
758
+
759
+ # Get full probability space of both the expression and the condition
760
+ fullspace = pspace(Tuple(expr, condition))
761
+ # Build new space given the condition
762
+ space = fullspace.conditional_space(condition, **kwargs)
763
+ # Dictionary to swap out RandomSymbols in expr with new RandomSymbols
764
+ # That point to the new conditional space
765
+ swapdict = rs_swap(fullspace.values, space.values)
766
+ # Swap random variables in the expression
767
+ expr = expr.xreplace(swapdict)
768
+ return expr
769
+
770
+
771
+ def expectation(expr, condition=None, numsamples=None, evaluate=True, **kwargs):
772
+ """
773
+ Returns the expected value of a random expression.
774
+
775
+ Parameters
776
+ ==========
777
+
778
+ expr : Expr containing RandomSymbols
779
+ The expression of which you want to compute the expectation value
780
+ given : Expr containing RandomSymbols
781
+ A conditional expression. E(X, X>0) is expectation of X given X > 0
782
+ numsamples : int
783
+ Enables sampling and approximates the expectation with this many samples
784
+ evalf : Bool (defaults to True)
785
+ If sampling return a number rather than a complex expression
786
+ evaluate : Bool (defaults to True)
787
+ In case of continuous systems return unevaluated integral
788
+
789
+ Examples
790
+ ========
791
+
792
+ >>> from sympy.stats import E, Die
793
+ >>> X = Die('X', 6)
794
+ >>> E(X)
795
+ 7/2
796
+ >>> E(2*X + 1)
797
+ 8
798
+
799
+ >>> E(X, X > 3) # Expectation of X given that it is above 3
800
+ 5
801
+ """
802
+
803
+ if not is_random(expr): # expr isn't random?
804
+ return expr
805
+ kwargs['numsamples'] = numsamples
806
+ from sympy.stats.symbolic_probability import Expectation
807
+ if evaluate:
808
+ return Expectation(expr, condition).doit(**kwargs)
809
+ return Expectation(expr, condition)
810
+
811
+
812
+ def probability(condition, given_condition=None, numsamples=None,
813
+ evaluate=True, **kwargs):
814
+ """
815
+ Probability that a condition is true, optionally given a second condition.
816
+
817
+ Parameters
818
+ ==========
819
+
820
+ condition : Combination of Relationals containing RandomSymbols
821
+ The condition of which you want to compute the probability
822
+ given_condition : Combination of Relationals containing RandomSymbols
823
+ A conditional expression. P(X > 1, X > 0) is expectation of X > 1
824
+ given X > 0
825
+ numsamples : int
826
+ Enables sampling and approximates the probability with this many samples
827
+ evaluate : Bool (defaults to True)
828
+ In case of continuous systems return unevaluated integral
829
+
830
+ Examples
831
+ ========
832
+
833
+ >>> from sympy.stats import P, Die
834
+ >>> from sympy import Eq
835
+ >>> X, Y = Die('X', 6), Die('Y', 6)
836
+ >>> P(X > 3)
837
+ 1/2
838
+ >>> P(Eq(X, 5), X > 2) # Probability that X == 5 given that X > 2
839
+ 1/4
840
+ >>> P(X > Y)
841
+ 5/12
842
+ """
843
+
844
+ kwargs['numsamples'] = numsamples
845
+ from sympy.stats.symbolic_probability import Probability
846
+ if evaluate:
847
+ return Probability(condition, given_condition).doit(**kwargs)
848
+ return Probability(condition, given_condition)
849
+
850
+
851
+ class Density(Basic):
852
+ expr = property(lambda self: self.args[0])
853
+
854
+ def __new__(cls, expr, condition = None):
855
+ expr = _sympify(expr)
856
+ if condition is None:
857
+ obj = Basic.__new__(cls, expr)
858
+ else:
859
+ condition = _sympify(condition)
860
+ obj = Basic.__new__(cls, expr, condition)
861
+ return obj
862
+
863
+ @property
864
+ def condition(self):
865
+ if len(self.args) > 1:
866
+ return self.args[1]
867
+ else:
868
+ return None
869
+
870
+ def doit(self, evaluate=True, **kwargs):
871
+ from sympy.stats.random_matrix import RandomMatrixPSpace
872
+ from sympy.stats.joint_rv import JointPSpace
873
+ from sympy.stats.matrix_distributions import MatrixPSpace
874
+ from sympy.stats.compound_rv import CompoundPSpace
875
+ from sympy.stats.frv import SingleFiniteDistribution
876
+ expr, condition = self.expr, self.condition
877
+
878
+ if isinstance(expr, SingleFiniteDistribution):
879
+ return expr.dict
880
+ if condition is not None:
881
+ # Recompute on new conditional expr
882
+ expr = given(expr, condition, **kwargs)
883
+ if not random_symbols(expr):
884
+ return Lambda(x, DiracDelta(x - expr))
885
+ if isinstance(expr, RandomSymbol):
886
+ if isinstance(expr.pspace, (SinglePSpace, JointPSpace, MatrixPSpace)) and \
887
+ hasattr(expr.pspace, 'distribution'):
888
+ return expr.pspace.distribution
889
+ elif isinstance(expr.pspace, RandomMatrixPSpace):
890
+ return expr.pspace.model
891
+ if isinstance(pspace(expr), CompoundPSpace):
892
+ kwargs['compound_evaluate'] = evaluate
893
+ result = pspace(expr).compute_density(expr, **kwargs)
894
+
895
+ if evaluate and hasattr(result, 'doit'):
896
+ return result.doit()
897
+ else:
898
+ return result
899
+
900
+
901
+ def density(expr, condition=None, evaluate=True, numsamples=None, **kwargs):
902
+ """
903
+ Probability density of a random expression, optionally given a second
904
+ condition.
905
+
906
+ Explanation
907
+ ===========
908
+
909
+ This density will take on different forms for different types of
910
+ probability spaces. Discrete variables produce Dicts. Continuous
911
+ variables produce Lambdas.
912
+
913
+ Parameters
914
+ ==========
915
+
916
+ expr : Expr containing RandomSymbols
917
+ The expression of which you want to compute the density value
918
+ condition : Relational containing RandomSymbols
919
+ A conditional expression. density(X > 1, X > 0) is density of X > 1
920
+ given X > 0
921
+ numsamples : int
922
+ Enables sampling and approximates the density with this many samples
923
+
924
+ Examples
925
+ ========
926
+
927
+ >>> from sympy.stats import density, Die, Normal
928
+ >>> from sympy import Symbol
929
+
930
+ >>> x = Symbol('x')
931
+ >>> D = Die('D', 6)
932
+ >>> X = Normal(x, 0, 1)
933
+
934
+ >>> density(D).dict
935
+ {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
936
+ >>> density(2*D).dict
937
+ {2: 1/6, 4: 1/6, 6: 1/6, 8: 1/6, 10: 1/6, 12: 1/6}
938
+ >>> density(X)(x)
939
+ sqrt(2)*exp(-x**2/2)/(2*sqrt(pi))
940
+ """
941
+
942
+ if numsamples:
943
+ return sampling_density(expr, condition, numsamples=numsamples,
944
+ **kwargs)
945
+
946
+ return Density(expr, condition).doit(evaluate=evaluate, **kwargs)
947
+
948
+
949
+ def cdf(expr, condition=None, evaluate=True, **kwargs):
950
+ """
951
+ Cumulative Distribution Function of a random expression.
952
+
953
+ optionally given a second condition.
954
+
955
+ Explanation
956
+ ===========
957
+
958
+ This density will take on different forms for different types of
959
+ probability spaces.
960
+ Discrete variables produce Dicts.
961
+ Continuous variables produce Lambdas.
962
+
963
+ Examples
964
+ ========
965
+
966
+ >>> from sympy.stats import density, Die, Normal, cdf
967
+
968
+ >>> D = Die('D', 6)
969
+ >>> X = Normal('X', 0, 1)
970
+
971
+ >>> density(D).dict
972
+ {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
973
+ >>> cdf(D)
974
+ {1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1}
975
+ >>> cdf(3*D, D > 2)
976
+ {9: 1/4, 12: 1/2, 15: 3/4, 18: 1}
977
+
978
+ >>> cdf(X)
979
+ Lambda(_z, erf(sqrt(2)*_z/2)/2 + 1/2)
980
+ """
981
+ if condition is not None: # If there is a condition
982
+ # Recompute on new conditional expr
983
+ return cdf(given(expr, condition, **kwargs), **kwargs)
984
+
985
+ # Otherwise pass work off to the ProbabilitySpace
986
+ result = pspace(expr).compute_cdf(expr, **kwargs)
987
+
988
+ if evaluate and hasattr(result, 'doit'):
989
+ return result.doit()
990
+ else:
991
+ return result
992
+
993
+
994
+ def characteristic_function(expr, condition=None, evaluate=True, **kwargs):
995
+ """
996
+ Characteristic function of a random expression, optionally given a second condition.
997
+
998
+ Returns a Lambda.
999
+
1000
+ Examples
1001
+ ========
1002
+
1003
+ >>> from sympy.stats import Normal, DiscreteUniform, Poisson, characteristic_function
1004
+
1005
+ >>> X = Normal('X', 0, 1)
1006
+ >>> characteristic_function(X)
1007
+ Lambda(_t, exp(-_t**2/2))
1008
+
1009
+ >>> Y = DiscreteUniform('Y', [1, 2, 7])
1010
+ >>> characteristic_function(Y)
1011
+ Lambda(_t, exp(7*_t*I)/3 + exp(2*_t*I)/3 + exp(_t*I)/3)
1012
+
1013
+ >>> Z = Poisson('Z', 2)
1014
+ >>> characteristic_function(Z)
1015
+ Lambda(_t, exp(2*exp(_t*I) - 2))
1016
+ """
1017
+ if condition is not None:
1018
+ return characteristic_function(given(expr, condition, **kwargs), **kwargs)
1019
+
1020
+ result = pspace(expr).compute_characteristic_function(expr, **kwargs)
1021
+
1022
+ if evaluate and hasattr(result, 'doit'):
1023
+ return result.doit()
1024
+ else:
1025
+ return result
1026
+
1027
+ def moment_generating_function(expr, condition=None, evaluate=True, **kwargs):
1028
+ if condition is not None:
1029
+ return moment_generating_function(given(expr, condition, **kwargs), **kwargs)
1030
+
1031
+ result = pspace(expr).compute_moment_generating_function(expr, **kwargs)
1032
+
1033
+ if evaluate and hasattr(result, 'doit'):
1034
+ return result.doit()
1035
+ else:
1036
+ return result
1037
+
1038
+ def where(condition, given_condition=None, **kwargs):
1039
+ """
1040
+ Returns the domain where a condition is True.
1041
+
1042
+ Examples
1043
+ ========
1044
+
1045
+ >>> from sympy.stats import where, Die, Normal
1046
+ >>> from sympy import And
1047
+
1048
+ >>> D1, D2 = Die('a', 6), Die('b', 6)
1049
+ >>> a, b = D1.symbol, D2.symbol
1050
+ >>> X = Normal('x', 0, 1)
1051
+
1052
+ >>> where(X**2<1)
1053
+ Domain: (-1 < x) & (x < 1)
1054
+
1055
+ >>> where(X**2<1).set
1056
+ Interval.open(-1, 1)
1057
+
1058
+ >>> where(And(D1<=D2, D2<3))
1059
+ Domain: (Eq(a, 1) & Eq(b, 1)) | (Eq(a, 1) & Eq(b, 2)) | (Eq(a, 2) & Eq(b, 2))
1060
+ """
1061
+ if given_condition is not None: # If there is a condition
1062
+ # Recompute on new conditional expr
1063
+ return where(given(condition, given_condition, **kwargs), **kwargs)
1064
+
1065
+ # Otherwise pass work off to the ProbabilitySpace
1066
+ return pspace(condition).where(condition, **kwargs)
1067
+
1068
+
1069
+ @doctest_depends_on(modules=('scipy',))
1070
+ def sample(expr, condition=None, size=(), library='scipy',
1071
+ numsamples=1, seed=None, **kwargs):
1072
+ """
1073
+ A realization of the random expression.
1074
+
1075
+ Parameters
1076
+ ==========
1077
+
1078
+ expr : Expression of random variables
1079
+ Expression from which sample is extracted
1080
+ condition : Expr containing RandomSymbols
1081
+ A conditional expression
1082
+ size : int, tuple
1083
+ Represents size of each sample in numsamples
1084
+ library : str
1085
+ - 'scipy' : Sample using scipy
1086
+ - 'numpy' : Sample using numpy
1087
+ - 'pymc' : Sample using PyMC
1088
+
1089
+ Choose any of the available options to sample from as string,
1090
+ by default is 'scipy'
1091
+ numsamples : int
1092
+ Number of samples, each with size as ``size``.
1093
+
1094
+ .. deprecated:: 1.9
1095
+
1096
+ The ``numsamples`` parameter is deprecated and is only provided for
1097
+ compatibility with v1.8. Use a list comprehension or an additional
1098
+ dimension in ``size`` instead. See
1099
+ :ref:`deprecated-sympy-stats-numsamples` for details.
1100
+
1101
+ seed :
1102
+ An object to be used as seed by the given external library for sampling `expr`.
1103
+ Following is the list of possible types of object for the supported libraries,
1104
+
1105
+ - 'scipy': int, numpy.random.RandomState, numpy.random.Generator
1106
+ - 'numpy': int, numpy.random.RandomState, numpy.random.Generator
1107
+ - 'pymc': int
1108
+
1109
+ Optional, by default None, in which case seed settings
1110
+ related to the given library will be used.
1111
+ No modifications to environment's global seed settings
1112
+ are done by this argument.
1113
+
1114
+ Returns
1115
+ =======
1116
+
1117
+ sample: float/list/numpy.ndarray
1118
+ one sample or a collection of samples of the random expression.
1119
+
1120
+ - sample(X) returns float/numpy.float64/numpy.int64 object.
1121
+ - sample(X, size=int/tuple) returns numpy.ndarray object.
1122
+
1123
+ Examples
1124
+ ========
1125
+
1126
+ >>> from sympy.stats import Die, sample, Normal, Geometric
1127
+ >>> X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) # Finite Random Variable
1128
+ >>> die_roll = sample(X + Y + Z)
1129
+ >>> die_roll # doctest: +SKIP
1130
+ 3
1131
+ >>> N = Normal('N', 3, 4) # Continuous Random Variable
1132
+ >>> samp = sample(N)
1133
+ >>> samp in N.pspace.domain.set
1134
+ True
1135
+ >>> samp = sample(N, N>0)
1136
+ >>> samp > 0
1137
+ True
1138
+ >>> samp_list = sample(N, size=4)
1139
+ >>> [sam in N.pspace.domain.set for sam in samp_list]
1140
+ [True, True, True, True]
1141
+ >>> sample(N, size = (2,3)) # doctest: +SKIP
1142
+ array([[5.42519758, 6.40207856, 4.94991743],
1143
+ [1.85819627, 6.83403519, 1.9412172 ]])
1144
+ >>> G = Geometric('G', 0.5) # Discrete Random Variable
1145
+ >>> samp_list = sample(G, size=3)
1146
+ >>> samp_list # doctest: +SKIP
1147
+ [1, 3, 2]
1148
+ >>> [sam in G.pspace.domain.set for sam in samp_list]
1149
+ [True, True, True]
1150
+ >>> MN = Normal("MN", [3, 4], [[2, 1], [1, 2]]) # Joint Random Variable
1151
+ >>> samp_list = sample(MN, size=4)
1152
+ >>> samp_list # doctest: +SKIP
1153
+ [array([2.85768055, 3.38954165]),
1154
+ array([4.11163337, 4.3176591 ]),
1155
+ array([0.79115232, 1.63232916]),
1156
+ array([4.01747268, 3.96716083])]
1157
+ >>> [tuple(sam) in MN.pspace.domain.set for sam in samp_list]
1158
+ [True, True, True, True]
1159
+
1160
+ .. versionchanged:: 1.7.0
1161
+ sample used to return an iterator containing the samples instead of value.
1162
+
1163
+ .. versionchanged:: 1.9.0
1164
+ sample returns values or array of values instead of an iterator and numsamples is deprecated.
1165
+
1166
+ """
1167
+
1168
+ iterator = sample_iter(expr, condition, size=size, library=library,
1169
+ numsamples=numsamples, seed=seed)
1170
+
1171
+ if numsamples != 1:
1172
+ sympy_deprecation_warning(
1173
+ f"""
1174
+ The numsamples parameter to sympy.stats.sample() is deprecated.
1175
+ Either use a list comprehension, like
1176
+
1177
+ [sample(...) for i in range({numsamples})]
1178
+
1179
+ or add a dimension to size, like
1180
+
1181
+ sample(..., size={(numsamples,) + size})
1182
+ """,
1183
+ deprecated_since_version="1.9",
1184
+ active_deprecations_target="deprecated-sympy-stats-numsamples",
1185
+ )
1186
+ return [next(iterator) for i in range(numsamples)]
1187
+
1188
+ return next(iterator)
1189
+
1190
+
1191
+ def quantile(expr, evaluate=True, **kwargs):
1192
+ r"""
1193
+ Return the :math:`p^{th}` order quantile of a probability distribution.
1194
+
1195
+ Explanation
1196
+ ===========
1197
+
1198
+ Quantile is defined as the value at which the probability of the random
1199
+ variable is less than or equal to the given probability.
1200
+
1201
+ .. math::
1202
+ Q(p) = \inf\{x \in (-\infty, \infty) : p \le F(x)\}
1203
+
1204
+ Examples
1205
+ ========
1206
+
1207
+ >>> from sympy.stats import quantile, Die, Exponential
1208
+ >>> from sympy import Symbol, pprint
1209
+ >>> p = Symbol("p")
1210
+
1211
+ >>> l = Symbol("lambda", positive=True)
1212
+ >>> X = Exponential("x", l)
1213
+ >>> quantile(X)(p)
1214
+ -log(1 - p)/lambda
1215
+
1216
+ >>> D = Die("d", 6)
1217
+ >>> pprint(quantile(D)(p), use_unicode=False)
1218
+ /nan for Or(p > 1, p < 0)
1219
+ |
1220
+ | 1 for p <= 1/6
1221
+ |
1222
+ | 2 for p <= 1/3
1223
+ |
1224
+ < 3 for p <= 1/2
1225
+ |
1226
+ | 4 for p <= 2/3
1227
+ |
1228
+ | 5 for p <= 5/6
1229
+ |
1230
+ \ 6 for p <= 1
1231
+
1232
+ """
1233
+ result = pspace(expr).compute_quantile(expr, **kwargs)
1234
+
1235
+ if evaluate and hasattr(result, 'doit'):
1236
+ return result.doit()
1237
+ else:
1238
+ return result
1239
+
1240
+ def sample_iter(expr, condition=None, size=(), library='scipy',
1241
+ numsamples=S.Infinity, seed=None, **kwargs):
1242
+
1243
+ """
1244
+ Returns an iterator of realizations from the expression given a condition.
1245
+
1246
+ Parameters
1247
+ ==========
1248
+
1249
+ expr: Expr
1250
+ Random expression to be realized
1251
+ condition: Expr, optional
1252
+ A conditional expression
1253
+ size : int, tuple
1254
+ Represents size of each sample in numsamples
1255
+ numsamples: integer, optional
1256
+ Length of the iterator (defaults to infinity)
1257
+ seed :
1258
+ An object to be used as seed by the given external library for sampling `expr`.
1259
+ Following is the list of possible types of object for the supported libraries,
1260
+
1261
+ - 'scipy': int, numpy.random.RandomState, numpy.random.Generator
1262
+ - 'numpy': int, numpy.random.RandomState, numpy.random.Generator
1263
+ - 'pymc': int
1264
+
1265
+ Optional, by default None, in which case seed settings
1266
+ related to the given library will be used.
1267
+ No modifications to environment's global seed settings
1268
+ are done by this argument.
1269
+
1270
+ Examples
1271
+ ========
1272
+
1273
+ >>> from sympy.stats import Normal, sample_iter
1274
+ >>> X = Normal('X', 0, 1)
1275
+ >>> expr = X*X + 3
1276
+ >>> iterator = sample_iter(expr, numsamples=3) # doctest: +SKIP
1277
+ >>> list(iterator) # doctest: +SKIP
1278
+ [12, 4, 7]
1279
+
1280
+ Returns
1281
+ =======
1282
+
1283
+ sample_iter: iterator object
1284
+ iterator object containing the sample/samples of given expr
1285
+
1286
+ See Also
1287
+ ========
1288
+
1289
+ sample
1290
+ sampling_P
1291
+ sampling_E
1292
+
1293
+ """
1294
+ from sympy.stats.joint_rv import JointRandomSymbol
1295
+ if not import_module(library):
1296
+ raise ValueError("Failed to import %s" % library)
1297
+
1298
+ if condition is not None:
1299
+ ps = pspace(Tuple(expr, condition))
1300
+ else:
1301
+ ps = pspace(expr)
1302
+
1303
+ rvs = list(ps.values)
1304
+ if isinstance(expr, JointRandomSymbol):
1305
+ expr = expr.subs({expr: RandomSymbol(expr.symbol, expr.pspace)})
1306
+ else:
1307
+ sub = {}
1308
+ for arg in expr.args:
1309
+ if isinstance(arg, JointRandomSymbol):
1310
+ sub[arg] = RandomSymbol(arg.symbol, arg.pspace)
1311
+ expr = expr.subs(sub)
1312
+
1313
+ def fn_subs(*args):
1314
+ return expr.subs(dict(zip(rvs, args)))
1315
+
1316
+ def given_fn_subs(*args):
1317
+ if condition is not None:
1318
+ return condition.subs(dict(zip(rvs, args)))
1319
+ return False
1320
+
1321
+ if library in ('pymc', 'pymc3'):
1322
+ # Currently unable to lambdify in pymc
1323
+ # TODO : Remove when lambdify accepts 'pymc' as module
1324
+ fn = lambdify(rvs, expr, **kwargs)
1325
+ else:
1326
+ fn = lambdify(rvs, expr, modules=library, **kwargs)
1327
+
1328
+
1329
+ if condition is not None:
1330
+ given_fn = lambdify(rvs, condition, **kwargs)
1331
+
1332
+ def return_generator_infinite():
1333
+ count = 0
1334
+ _size = (1,)+((size,) if isinstance(size, int) else size)
1335
+ while count < numsamples:
1336
+ d = ps.sample(size=_size, library=library, seed=seed) # a dictionary that maps RVs to values
1337
+ args = [d[rv][0] for rv in rvs]
1338
+
1339
+ if condition is not None: # Check that these values satisfy the condition
1340
+ # TODO: Replace the try-except block with only given_fn(*args)
1341
+ # once lambdify works with unevaluated SymPy objects.
1342
+ try:
1343
+ gd = given_fn(*args)
1344
+ except (NameError, TypeError):
1345
+ gd = given_fn_subs(*args)
1346
+ if gd != True and gd != False:
1347
+ raise ValueError(
1348
+ "Conditions must not contain free symbols")
1349
+ if not gd: # If the values don't satisfy then try again
1350
+ continue
1351
+
1352
+ yield fn(*args)
1353
+ count += 1
1354
+
1355
+ def return_generator_finite():
1356
+ faulty = True
1357
+ while faulty:
1358
+ d = ps.sample(size=(numsamples,) + ((size,) if isinstance(size, int) else size),
1359
+ library=library, seed=seed) # a dictionary that maps RVs to values
1360
+
1361
+ faulty = False
1362
+ count = 0
1363
+ while count < numsamples and not faulty:
1364
+ args = [d[rv][count] for rv in rvs]
1365
+ if condition is not None: # Check that these values satisfy the condition
1366
+ # TODO: Replace the try-except block with only given_fn(*args)
1367
+ # once lambdify works with unevaluated SymPy objects.
1368
+ try:
1369
+ gd = given_fn(*args)
1370
+ except (NameError, TypeError):
1371
+ gd = given_fn_subs(*args)
1372
+ if gd != True and gd != False:
1373
+ raise ValueError(
1374
+ "Conditions must not contain free symbols")
1375
+ if not gd: # If the values don't satisfy then try again
1376
+ faulty = True
1377
+
1378
+ count += 1
1379
+
1380
+ count = 0
1381
+ while count < numsamples:
1382
+ args = [d[rv][count] for rv in rvs]
1383
+ # TODO: Replace the try-except block with only fn(*args)
1384
+ # once lambdify works with unevaluated SymPy objects.
1385
+ try:
1386
+ yield fn(*args)
1387
+ except (NameError, TypeError):
1388
+ yield fn_subs(*args)
1389
+ count += 1
1390
+
1391
+ if numsamples is S.Infinity:
1392
+ return return_generator_infinite()
1393
+
1394
+ return return_generator_finite()
1395
+
1396
+ def sample_iter_lambdify(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
+ def sample_iter_subs(expr, condition=None, size=(),
1403
+ numsamples=S.Infinity, seed=None, **kwargs):
1404
+
1405
+ return sample_iter(expr, condition=condition, size=size,
1406
+ numsamples=numsamples, seed=seed, **kwargs)
1407
+
1408
+
1409
+ def sampling_P(condition, given_condition=None, library='scipy', numsamples=1,
1410
+ evalf=True, seed=None, **kwargs):
1411
+ """
1412
+ Sampling version of P.
1413
+
1414
+ See Also
1415
+ ========
1416
+
1417
+ P
1418
+ sampling_E
1419
+ sampling_density
1420
+
1421
+ """
1422
+
1423
+ count_true = 0
1424
+ count_false = 0
1425
+ samples = sample_iter(condition, given_condition, library=library,
1426
+ numsamples=numsamples, seed=seed, **kwargs)
1427
+
1428
+ for sample in samples:
1429
+ if sample:
1430
+ count_true += 1
1431
+ else:
1432
+ count_false += 1
1433
+
1434
+ result = S(count_true) / numsamples
1435
+ if evalf:
1436
+ return result.evalf()
1437
+ else:
1438
+ return result
1439
+
1440
+
1441
+ def sampling_E(expr, given_condition=None, library='scipy', numsamples=1,
1442
+ evalf=True, seed=None, **kwargs):
1443
+ """
1444
+ Sampling version of E.
1445
+
1446
+ See Also
1447
+ ========
1448
+
1449
+ P
1450
+ sampling_P
1451
+ sampling_density
1452
+ """
1453
+ samples = list(sample_iter(expr, given_condition, library=library,
1454
+ numsamples=numsamples, seed=seed, **kwargs))
1455
+ result = Add(*samples) / numsamples
1456
+
1457
+ if evalf:
1458
+ return result.evalf()
1459
+ else:
1460
+ return result
1461
+
1462
+ def sampling_density(expr, given_condition=None, library='scipy',
1463
+ numsamples=1, seed=None, **kwargs):
1464
+ """
1465
+ Sampling version of density.
1466
+
1467
+ See Also
1468
+ ========
1469
+ density
1470
+ sampling_P
1471
+ sampling_E
1472
+ """
1473
+
1474
+ results = {}
1475
+ for result in sample_iter(expr, given_condition, library=library,
1476
+ numsamples=numsamples, seed=seed, **kwargs):
1477
+ results[result] = results.get(result, 0) + 1
1478
+
1479
+ return results
1480
+
1481
+
1482
+ def dependent(a, b):
1483
+ """
1484
+ Dependence of two random expressions.
1485
+
1486
+ Two expressions are independent if knowledge of one does not change
1487
+ computations on the other.
1488
+
1489
+ Examples
1490
+ ========
1491
+
1492
+ >>> from sympy.stats import Normal, dependent, given
1493
+ >>> from sympy import Tuple, Eq
1494
+
1495
+ >>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
1496
+ >>> dependent(X, Y)
1497
+ False
1498
+ >>> dependent(2*X + Y, -Y)
1499
+ True
1500
+ >>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
1501
+ >>> dependent(X, Y)
1502
+ True
1503
+
1504
+ See Also
1505
+ ========
1506
+
1507
+ independent
1508
+ """
1509
+ if pspace_independent(a, b):
1510
+ return False
1511
+
1512
+ z = Symbol('z', real=True)
1513
+ # Dependent if density is unchanged when one is given information about
1514
+ # the other
1515
+ return (density(a, Eq(b, z)) != density(a) or
1516
+ density(b, Eq(a, z)) != density(b))
1517
+
1518
+
1519
+ def independent(a, b):
1520
+ """
1521
+ Independence of two random expressions.
1522
+
1523
+ Two expressions are independent if knowledge of one does not change
1524
+ computations on the other.
1525
+
1526
+ Examples
1527
+ ========
1528
+
1529
+ >>> from sympy.stats import Normal, independent, given
1530
+ >>> from sympy import Tuple, Eq
1531
+
1532
+ >>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
1533
+ >>> independent(X, Y)
1534
+ True
1535
+ >>> independent(2*X + Y, -Y)
1536
+ False
1537
+ >>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
1538
+ >>> independent(X, Y)
1539
+ False
1540
+
1541
+ See Also
1542
+ ========
1543
+
1544
+ dependent
1545
+ """
1546
+ return not dependent(a, b)
1547
+
1548
+
1549
+ def pspace_independent(a, b):
1550
+ """
1551
+ Tests for independence between a and b by checking if their PSpaces have
1552
+ overlapping symbols. This is a sufficient but not necessary condition for
1553
+ independence and is intended to be used internally.
1554
+
1555
+ Notes
1556
+ =====
1557
+
1558
+ pspace_independent(a, b) implies independent(a, b)
1559
+ independent(a, b) does not imply pspace_independent(a, b)
1560
+ """
1561
+ a_symbols = set(pspace(b).symbols)
1562
+ b_symbols = set(pspace(a).symbols)
1563
+
1564
+ if len(set(random_symbols(a)).intersection(random_symbols(b))) != 0:
1565
+ return False
1566
+
1567
+ if len(a_symbols.intersection(b_symbols)) == 0:
1568
+ return True
1569
+ return None
1570
+
1571
+
1572
+ def rv_subs(expr, symbols=None):
1573
+ """
1574
+ Given a random expression replace all random variables with their symbols.
1575
+
1576
+ If symbols keyword is given restrict the swap to only the symbols listed.
1577
+ """
1578
+ if symbols is None:
1579
+ symbols = random_symbols(expr)
1580
+ if not symbols:
1581
+ return expr
1582
+ swapdict = {rv: rv.symbol for rv in symbols}
1583
+ return expr.subs(swapdict)
1584
+
1585
+
1586
+ class NamedArgsMixin:
1587
+ _argnames: tuple[str, ...] = ()
1588
+
1589
+ def __getattr__(self, attr):
1590
+ try:
1591
+ return self.args[self._argnames.index(attr)]
1592
+ except ValueError:
1593
+ raise AttributeError("'%s' object has no attribute '%s'" % (
1594
+ type(self).__name__, attr))
1595
+
1596
+
1597
+ class Distribution(Basic):
1598
+
1599
+ def sample(self, size=(), library='scipy', seed=None):
1600
+ """ A random realization from the distribution """
1601
+
1602
+ module = import_module(library)
1603
+ if library in {'scipy', 'numpy', 'pymc3', 'pymc'} and module is None:
1604
+ raise ValueError("Failed to import %s" % library)
1605
+
1606
+ if library == 'scipy':
1607
+ # scipy does not require map as it can handle using custom distributions.
1608
+ # However, we will still use a map where we can.
1609
+
1610
+ # TODO: do this for drv.py and frv.py if necessary.
1611
+ # TODO: add more distributions here if there are more
1612
+ # See links below referring to sections beginning with "A common parametrization..."
1613
+ # I will remove all these comments if everything is ok.
1614
+
1615
+ from sympy.stats.sampling.sample_scipy import do_sample_scipy
1616
+ import numpy
1617
+ if seed is None or isinstance(seed, int):
1618
+ rand_state = numpy.random.default_rng(seed=seed)
1619
+ else:
1620
+ rand_state = seed
1621
+ samps = do_sample_scipy(self, size, rand_state)
1622
+
1623
+ elif library == 'numpy':
1624
+ from sympy.stats.sampling.sample_numpy import do_sample_numpy
1625
+ import numpy
1626
+ if seed is None or isinstance(seed, int):
1627
+ rand_state = numpy.random.default_rng(seed=seed)
1628
+ else:
1629
+ rand_state = seed
1630
+ _size = None if size == () else size
1631
+ samps = do_sample_numpy(self, _size, rand_state)
1632
+ elif library in ('pymc', 'pymc3'):
1633
+ from sympy.stats.sampling.sample_pymc import do_sample_pymc
1634
+ import logging
1635
+ logging.getLogger("pymc").setLevel(logging.ERROR)
1636
+ try:
1637
+ import pymc
1638
+ except ImportError:
1639
+ import pymc3 as pymc
1640
+
1641
+ with pymc.Model():
1642
+ if do_sample_pymc(self):
1643
+ samps = pymc.sample(draws=prod(size), chains=1, compute_convergence_checks=False,
1644
+ progressbar=False, random_seed=seed, return_inferencedata=False)[:]['X']
1645
+ samps = samps.reshape(size)
1646
+ else:
1647
+ samps = None
1648
+
1649
+ else:
1650
+ raise NotImplementedError("Sampling from %s is not supported yet."
1651
+ % str(library))
1652
+
1653
+ if samps is not None:
1654
+ return samps
1655
+ raise NotImplementedError(
1656
+ "Sampling for %s is not currently implemented from %s"
1657
+ % (self, library))
1658
+
1659
+
1660
+ def _value_check(condition, message):
1661
+ """
1662
+ Raise a ValueError with message if condition is False, else
1663
+ return True if all conditions were True, else False.
1664
+
1665
+ Examples
1666
+ ========
1667
+
1668
+ >>> from sympy.stats.rv import _value_check
1669
+ >>> from sympy.abc import a, b, c
1670
+ >>> from sympy import And, Dummy
1671
+
1672
+ >>> _value_check(2 < 3, '')
1673
+ True
1674
+
1675
+ Here, the condition is not False, but it does not evaluate to True
1676
+ so False is returned (but no error is raised). So checking if the
1677
+ return value is True or False will tell you if all conditions were
1678
+ evaluated.
1679
+
1680
+ >>> _value_check(a < b, '')
1681
+ False
1682
+
1683
+ In this case the condition is False so an error is raised:
1684
+
1685
+ >>> r = Dummy(real=True)
1686
+ >>> _value_check(r < r - 1, 'condition is not true')
1687
+ Traceback (most recent call last):
1688
+ ...
1689
+ ValueError: condition is not true
1690
+
1691
+ If no condition of many conditions must be False, they can be
1692
+ checked by passing them as an iterable:
1693
+
1694
+ >>> _value_check((a < 0, b < 0, c < 0), '')
1695
+ False
1696
+
1697
+ The iterable can be a generator, too:
1698
+
1699
+ >>> _value_check((i < 0 for i in (a, b, c)), '')
1700
+ False
1701
+
1702
+ The following are equivalent to the above but do not pass
1703
+ an iterable:
1704
+
1705
+ >>> all(_value_check(i < 0, '') for i in (a, b, c))
1706
+ False
1707
+ >>> _value_check(And(a < 0, b < 0, c < 0), '')
1708
+ False
1709
+ """
1710
+ if not iterable(condition):
1711
+ condition = [condition]
1712
+ truth = fuzzy_and(condition)
1713
+ if truth == False:
1714
+ raise ValueError(message)
1715
+ return truth == True
1716
+
1717
+ def _symbol_converter(sym):
1718
+ """
1719
+ Casts the parameter to Symbol if it is 'str'
1720
+ otherwise no operation is performed on it.
1721
+
1722
+ Parameters
1723
+ ==========
1724
+
1725
+ sym
1726
+ The parameter to be converted.
1727
+
1728
+ Returns
1729
+ =======
1730
+
1731
+ Symbol
1732
+ the parameter converted to Symbol.
1733
+
1734
+ Raises
1735
+ ======
1736
+
1737
+ TypeError
1738
+ If the parameter is not an instance of both str and
1739
+ Symbol.
1740
+
1741
+ Examples
1742
+ ========
1743
+
1744
+ >>> from sympy import Symbol
1745
+ >>> from sympy.stats.rv import _symbol_converter
1746
+ >>> s = _symbol_converter('s')
1747
+ >>> isinstance(s, Symbol)
1748
+ True
1749
+ >>> _symbol_converter(1)
1750
+ Traceback (most recent call last):
1751
+ ...
1752
+ TypeError: 1 is neither a Symbol nor a string
1753
+ >>> r = Symbol('r')
1754
+ >>> isinstance(r, Symbol)
1755
+ True
1756
+ """
1757
+ if isinstance(sym, str):
1758
+ sym = Symbol(sym)
1759
+ if not isinstance(sym, Symbol):
1760
+ raise TypeError("%s is neither a Symbol nor a string"%(sym))
1761
+ return sym
1762
+
1763
+ def sample_stochastic_process(process):
1764
+ """
1765
+ This function is used to sample from stochastic process.
1766
+
1767
+ Parameters
1768
+ ==========
1769
+
1770
+ process: StochasticProcess
1771
+ Process used to extract the samples. It must be an instance of
1772
+ StochasticProcess
1773
+
1774
+ Examples
1775
+ ========
1776
+
1777
+ >>> from sympy.stats import sample_stochastic_process, DiscreteMarkovChain
1778
+ >>> from sympy import Matrix
1779
+ >>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
1780
+ >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
1781
+ >>> next(sample_stochastic_process(Y)) in Y.state_space
1782
+ True
1783
+ >>> next(sample_stochastic_process(Y)) # doctest: +SKIP
1784
+ 0
1785
+ >>> next(sample_stochastic_process(Y)) # doctest: +SKIP
1786
+ 2
1787
+
1788
+ Returns
1789
+ =======
1790
+
1791
+ sample: iterator object
1792
+ iterator object containing the sample of given process
1793
+
1794
+ """
1795
+ from sympy.stats.stochastic_process_types import StochasticProcess
1796
+ if not isinstance(process, StochasticProcess):
1797
+ raise ValueError("Process must be an instance of Stochastic Process")
1798
+ return process.sample()
mplug_owl2/lib/python3.10/site-packages/sympy/stats/rv_interface.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
mplug_owl2/lib/python3.10/site-packages/sympy/stats/stochastic_process.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.basic import Basic
2
+ from sympy.stats.joint_rv import ProductPSpace
3
+ from sympy.stats.rv import ProductDomain, _symbol_converter, Distribution
4
+
5
+
6
+ class StochasticPSpace(ProductPSpace):
7
+ """
8
+ Represents probability space of stochastic processes
9
+ and their random variables. Contains mechanics to do
10
+ computations for queries of stochastic processes.
11
+
12
+ Explanation
13
+ ===========
14
+
15
+ Initialized by symbol, the specific process and
16
+ distribution(optional) if the random indexed symbols
17
+ of the process follows any specific distribution, like,
18
+ in Bernoulli Process, each random indexed symbol follows
19
+ Bernoulli distribution. For processes with memory, this
20
+ parameter should not be passed.
21
+ """
22
+
23
+ def __new__(cls, sym, process, distribution=None):
24
+ sym = _symbol_converter(sym)
25
+ from sympy.stats.stochastic_process_types import StochasticProcess
26
+ if not isinstance(process, StochasticProcess):
27
+ raise TypeError("`process` must be an instance of StochasticProcess.")
28
+ if distribution is None:
29
+ distribution = Distribution()
30
+ return Basic.__new__(cls, sym, process, distribution)
31
+
32
+ @property
33
+ def process(self):
34
+ """
35
+ The associated stochastic process.
36
+ """
37
+ return self.args[1]
38
+
39
+ @property
40
+ def domain(self):
41
+ return ProductDomain(self.process.index_set,
42
+ self.process.state_space)
43
+
44
+ @property
45
+ def symbol(self):
46
+ return self.args[0]
47
+
48
+ @property
49
+ def distribution(self):
50
+ return self.args[2]
51
+
52
+ def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
53
+ """
54
+ Transfers the task of handling queries to the specific stochastic
55
+ process because every process has their own logic of handling such
56
+ queries.
57
+ """
58
+ return self.process.probability(condition, given_condition, evaluate, **kwargs)
59
+
60
+ def compute_expectation(self, expr, condition=None, evaluate=True, **kwargs):
61
+ """
62
+ Transfers the task of handling queries to the specific stochastic
63
+ process because every process has their own logic of handling such
64
+ queries.
65
+ """
66
+ return self.process.expectation(expr, condition, evaluate, **kwargs)
mplug_owl2/lib/python3.10/site-packages/sympy/stats/stochastic_process_types.py ADDED
@@ -0,0 +1,2383 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import itertools
3
+ from typing import (Sequence as tSequence, Union as tUnion, List as tList,
4
+ Tuple as tTuple, Set as tSet)
5
+ from sympy.concrete.summations import Sum
6
+ from sympy.core.add import Add
7
+ from sympy.core.basic import Basic
8
+ from sympy.core.cache import cacheit
9
+ from sympy.core.containers import Tuple
10
+ from sympy.core.expr import Expr
11
+ from sympy.core.function import (Function, Lambda)
12
+ from sympy.core.mul import Mul
13
+ from sympy.core.intfunc import igcd
14
+ from sympy.core.numbers import (Integer, Rational, oo, pi)
15
+ from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
16
+ from sympy.core.singleton import S
17
+ from sympy.core.symbol import (Dummy, Symbol)
18
+ from sympy.functions.combinatorial.factorials import factorial
19
+ from sympy.functions.elementary.exponential import exp
20
+ from sympy.functions.elementary.integers import ceiling
21
+ from sympy.functions.elementary.miscellaneous import sqrt
22
+ from sympy.functions.elementary.piecewise import Piecewise
23
+ from sympy.functions.special.gamma_functions import gamma
24
+ from sympy.logic.boolalg import (And, Not, Or)
25
+ from sympy.matrices.exceptions import NonSquareMatrixError
26
+ from sympy.matrices.dense import (Matrix, eye, ones, zeros)
27
+ from sympy.matrices.expressions.blockmatrix import BlockMatrix
28
+ from sympy.matrices.expressions.matexpr import MatrixSymbol
29
+ from sympy.matrices.expressions.special import Identity
30
+ from sympy.matrices.immutable import ImmutableMatrix
31
+ from sympy.sets.conditionset import ConditionSet
32
+ from sympy.sets.contains import Contains
33
+ from sympy.sets.fancysets import Range
34
+ from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union)
35
+ from sympy.solvers.solveset import linsolve
36
+ from sympy.tensor.indexed import (Indexed, IndexedBase)
37
+ from sympy.core.relational import Relational
38
+ from sympy.logic.boolalg import Boolean
39
+ from sympy.utilities.exceptions import sympy_deprecation_warning
40
+ from sympy.utilities.iterables import strongly_connected_components
41
+ from sympy.stats.joint_rv import JointDistribution
42
+ from sympy.stats.joint_rv_types import JointDistributionHandmade
43
+ from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol,
44
+ _symbol_converter, _value_check, pspace, given,
45
+ dependent, is_random, sample_iter, Distribution,
46
+ Density)
47
+ from sympy.stats.stochastic_process import StochasticPSpace
48
+ from sympy.stats.symbolic_probability import Probability, Expectation
49
+ from sympy.stats.frv_types import Bernoulli, BernoulliDistribution, FiniteRV
50
+ from sympy.stats.drv_types import Poisson, PoissonDistribution
51
+ from sympy.stats.crv_types import Normal, NormalDistribution, Gamma, GammaDistribution
52
+ from sympy.core.sympify import _sympify, sympify
53
+
54
+ EmptySet = S.EmptySet
55
+
56
+ __all__ = [
57
+ 'StochasticProcess',
58
+ 'DiscreteTimeStochasticProcess',
59
+ 'DiscreteMarkovChain',
60
+ 'TransitionMatrixOf',
61
+ 'StochasticStateSpaceOf',
62
+ 'GeneratorMatrixOf',
63
+ 'ContinuousMarkovChain',
64
+ 'BernoulliProcess',
65
+ 'PoissonProcess',
66
+ 'WienerProcess',
67
+ 'GammaProcess'
68
+ ]
69
+
70
+
71
+ @is_random.register(Indexed)
72
+ def _(x):
73
+ return is_random(x.base)
74
+
75
+ @is_random.register(RandomIndexedSymbol) # type: ignore
76
+ def _(x):
77
+ return True
78
+
79
+ def _set_converter(itr):
80
+ """
81
+ Helper function for converting list/tuple/set to Set.
82
+ If parameter is not an instance of list/tuple/set then
83
+ no operation is performed.
84
+
85
+ Returns
86
+ =======
87
+
88
+ Set
89
+ The argument converted to Set.
90
+
91
+
92
+ Raises
93
+ ======
94
+
95
+ TypeError
96
+ If the argument is not an instance of list/tuple/set.
97
+ """
98
+ if isinstance(itr, (list, tuple, set)):
99
+ itr = FiniteSet(*itr)
100
+ if not isinstance(itr, Set):
101
+ raise TypeError("%s is not an instance of list/tuple/set."%(itr))
102
+ return itr
103
+
104
+ def _state_converter(itr: tSequence) -> tUnion[Tuple, Range]:
105
+ """
106
+ Helper function for converting list/tuple/set/Range/Tuple/FiniteSet
107
+ to tuple/Range.
108
+ """
109
+ itr_ret: tUnion[Tuple, Range]
110
+
111
+ if isinstance(itr, (Tuple, set, FiniteSet)):
112
+ itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
113
+
114
+ elif isinstance(itr, (list, tuple)):
115
+ # check if states are unique
116
+ if len(set(itr)) != len(itr):
117
+ raise ValueError('The state space must have unique elements.')
118
+ itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
119
+
120
+ elif isinstance(itr, Range):
121
+ # the only ordered set in SymPy I know of
122
+ # try to convert to tuple
123
+ try:
124
+ itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
125
+ except (TypeError, ValueError):
126
+ itr_ret = itr
127
+
128
+ else:
129
+ raise TypeError("%s is not an instance of list/tuple/set/Range/Tuple/FiniteSet." % (itr))
130
+ return itr_ret
131
+
132
+ def _sym_sympify(arg):
133
+ """
134
+ Converts an arbitrary expression to a type that can be used inside SymPy.
135
+ As generally strings are unwise to use in the expressions,
136
+ it returns the Symbol of argument if the string type argument is passed.
137
+
138
+ Parameters
139
+ =========
140
+
141
+ arg: The parameter to be converted to be used in SymPy.
142
+
143
+ Returns
144
+ =======
145
+
146
+ The converted parameter.
147
+
148
+ """
149
+ if isinstance(arg, str):
150
+ return Symbol(arg)
151
+ else:
152
+ return _sympify(arg)
153
+
154
+ def _matrix_checks(matrix):
155
+ if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)):
156
+ raise TypeError("Transition probabilities either should "
157
+ "be a Matrix or a MatrixSymbol.")
158
+ if matrix.shape[0] != matrix.shape[1]:
159
+ raise NonSquareMatrixError("%s is not a square matrix"%(matrix))
160
+ if isinstance(matrix, Matrix):
161
+ matrix = ImmutableMatrix(matrix.tolist())
162
+ return matrix
163
+
164
+ class StochasticProcess(Basic):
165
+ """
166
+ Base class for all the stochastic processes whether
167
+ discrete or continuous.
168
+
169
+ Parameters
170
+ ==========
171
+
172
+ sym: Symbol or str
173
+ state_space: Set
174
+ The state space of the stochastic process, by default S.Reals.
175
+ For discrete sets it is zero indexed.
176
+
177
+ See Also
178
+ ========
179
+
180
+ DiscreteTimeStochasticProcess
181
+ """
182
+
183
+ index_set = S.Reals
184
+
185
+ def __new__(cls, sym, state_space=S.Reals, **kwargs):
186
+ sym = _symbol_converter(sym)
187
+ state_space = _set_converter(state_space)
188
+ return Basic.__new__(cls, sym, state_space)
189
+
190
+ @property
191
+ def symbol(self):
192
+ return self.args[0]
193
+
194
+ @property
195
+ def state_space(self) -> tUnion[FiniteSet, Range]:
196
+ if not isinstance(self.args[1], (FiniteSet, Range)):
197
+ assert isinstance(self.args[1], Tuple)
198
+ return FiniteSet(*self.args[1])
199
+ return self.args[1]
200
+
201
+ def _deprecation_warn_distribution(self):
202
+ sympy_deprecation_warning(
203
+ """
204
+ Calling the distribution method with a RandomIndexedSymbol
205
+ argument, like X.distribution(X(t)) is deprecated. Instead, call
206
+ distribution() with the given timestamp, like
207
+
208
+ X.distribution(t)
209
+ """,
210
+ deprecated_since_version="1.7.1",
211
+ active_deprecations_target="deprecated-distribution-randomindexedsymbol",
212
+ stacklevel=4,
213
+ )
214
+
215
+ def distribution(self, key=None):
216
+ if key is None:
217
+ self._deprecation_warn_distribution()
218
+ return Distribution()
219
+
220
+ def density(self, x):
221
+ return Density()
222
+
223
+ def __call__(self, time):
224
+ """
225
+ Overridden in ContinuousTimeStochasticProcess.
226
+ """
227
+ raise NotImplementedError("Use [] for indexing discrete time stochastic process.")
228
+
229
+ def __getitem__(self, time):
230
+ """
231
+ Overridden in DiscreteTimeStochasticProcess.
232
+ """
233
+ raise NotImplementedError("Use () for indexing continuous time stochastic process.")
234
+
235
+ def probability(self, condition):
236
+ raise NotImplementedError()
237
+
238
+ def joint_distribution(self, *args):
239
+ """
240
+ Computes the joint distribution of the random indexed variables.
241
+
242
+ Parameters
243
+ ==========
244
+
245
+ args: iterable
246
+ The finite list of random indexed variables/the key of a stochastic
247
+ process whose joint distribution has to be computed.
248
+
249
+ Returns
250
+ =======
251
+
252
+ JointDistribution
253
+ The joint distribution of the list of random indexed variables.
254
+ An unevaluated object is returned if it is not possible to
255
+ compute the joint distribution.
256
+
257
+ Raises
258
+ ======
259
+
260
+ ValueError: When the arguments passed are not of type RandomIndexSymbol
261
+ or Number.
262
+ """
263
+ args = list(args)
264
+ for i, arg in enumerate(args):
265
+ if S(arg).is_Number:
266
+ if self.index_set.is_subset(S.Integers):
267
+ args[i] = self.__getitem__(arg)
268
+ else:
269
+ args[i] = self.__call__(arg)
270
+ elif not isinstance(arg, RandomIndexedSymbol):
271
+ raise ValueError("Expected a RandomIndexedSymbol or "
272
+ "key not %s"%(type(arg)))
273
+
274
+ if args[0].pspace.distribution == Distribution():
275
+ return JointDistribution(*args)
276
+ density = Lambda(tuple(args),
277
+ expr=Mul.fromiter(arg.pspace.process.density(arg) for arg in args))
278
+ return JointDistributionHandmade(density)
279
+
280
+ def expectation(self, condition, given_condition):
281
+ raise NotImplementedError("Abstract method for expectation queries.")
282
+
283
+ def sample(self):
284
+ raise NotImplementedError("Abstract method for sampling queries.")
285
+
286
+ class DiscreteTimeStochasticProcess(StochasticProcess):
287
+ """
288
+ Base class for all discrete stochastic processes.
289
+ """
290
+ def __getitem__(self, time):
291
+ """
292
+ For indexing discrete time stochastic processes.
293
+
294
+ Returns
295
+ =======
296
+
297
+ RandomIndexedSymbol
298
+ """
299
+ time = sympify(time)
300
+ if not time.is_symbol and time not in self.index_set:
301
+ raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
302
+ idx_obj = Indexed(self.symbol, time)
303
+ pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time))
304
+ return RandomIndexedSymbol(idx_obj, pspace_obj)
305
+
306
+ class ContinuousTimeStochasticProcess(StochasticProcess):
307
+ """
308
+ Base class for all continuous time stochastic process.
309
+ """
310
+ def __call__(self, time):
311
+ """
312
+ For indexing continuous time stochastic processes.
313
+
314
+ Returns
315
+ =======
316
+
317
+ RandomIndexedSymbol
318
+ """
319
+ time = sympify(time)
320
+ if not time.is_symbol and time not in self.index_set:
321
+ raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
322
+ func_obj = Function(self.symbol)(time)
323
+ pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time))
324
+ return RandomIndexedSymbol(func_obj, pspace_obj)
325
+
326
+ class TransitionMatrixOf(Boolean):
327
+ """
328
+ Assumes that the matrix is the transition matrix
329
+ of the process.
330
+ """
331
+
332
+ def __new__(cls, process, matrix):
333
+ if not isinstance(process, DiscreteMarkovChain):
334
+ raise ValueError("Currently only DiscreteMarkovChain "
335
+ "support TransitionMatrixOf.")
336
+ matrix = _matrix_checks(matrix)
337
+ return Basic.__new__(cls, process, matrix)
338
+
339
+ process = property(lambda self: self.args[0])
340
+ matrix = property(lambda self: self.args[1])
341
+
342
+ class GeneratorMatrixOf(TransitionMatrixOf):
343
+ """
344
+ Assumes that the matrix is the generator matrix
345
+ of the process.
346
+ """
347
+
348
+ def __new__(cls, process, matrix):
349
+ if not isinstance(process, ContinuousMarkovChain):
350
+ raise ValueError("Currently only ContinuousMarkovChain "
351
+ "support GeneratorMatrixOf.")
352
+ matrix = _matrix_checks(matrix)
353
+ return Basic.__new__(cls, process, matrix)
354
+
355
+ class StochasticStateSpaceOf(Boolean):
356
+
357
+ def __new__(cls, process, state_space):
358
+ if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)):
359
+ raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain "
360
+ "support StochasticStateSpaceOf.")
361
+ state_space = _state_converter(state_space)
362
+ if isinstance(state_space, Range):
363
+ ss_size = ceiling((state_space.stop - state_space.start) / state_space.step)
364
+ else:
365
+ ss_size = len(state_space)
366
+ state_index = Range(ss_size)
367
+ return Basic.__new__(cls, process, state_index)
368
+
369
+ process = property(lambda self: self.args[0])
370
+ state_index = property(lambda self: self.args[1])
371
+
372
+ class MarkovProcess(StochasticProcess):
373
+ """
374
+ Contains methods that handle queries
375
+ common to Markov processes.
376
+ """
377
+
378
+ @property
379
+ def number_of_states(self) -> tUnion[Integer, Symbol]:
380
+ """
381
+ The number of states in the Markov Chain.
382
+ """
383
+ return _sympify(self.args[2].shape[0]) # type: ignore
384
+
385
+ @property
386
+ def _state_index(self):
387
+ """
388
+ Returns state index as Range.
389
+ """
390
+ return self.args[1]
391
+
392
+ @classmethod
393
+ def _sanity_checks(cls, state_space, trans_probs):
394
+ # Try to never have None as state_space or trans_probs.
395
+ # This helps a lot if we get it done at the start.
396
+ if (state_space is None) and (trans_probs is None):
397
+ _n = Dummy('n', integer=True, nonnegative=True)
398
+ state_space = _state_converter(Range(_n))
399
+ trans_probs = _matrix_checks(MatrixSymbol('_T', _n, _n))
400
+
401
+ elif state_space is None:
402
+ trans_probs = _matrix_checks(trans_probs)
403
+ state_space = _state_converter(Range(trans_probs.shape[0]))
404
+
405
+ elif trans_probs is None:
406
+ state_space = _state_converter(state_space)
407
+ if isinstance(state_space, Range):
408
+ _n = ceiling((state_space.stop - state_space.start) / state_space.step)
409
+ else:
410
+ _n = len(state_space)
411
+ trans_probs = MatrixSymbol('_T', _n, _n)
412
+
413
+ else:
414
+ state_space = _state_converter(state_space)
415
+ trans_probs = _matrix_checks(trans_probs)
416
+ # Range object doesn't want to give a symbolic size
417
+ # so we do it ourselves.
418
+ if isinstance(state_space, Range):
419
+ ss_size = ceiling((state_space.stop - state_space.start) / state_space.step)
420
+ else:
421
+ ss_size = len(state_space)
422
+ if ss_size != trans_probs.shape[0]:
423
+ raise ValueError('The size of the state space and the number of '
424
+ 'rows of the transition matrix must be the same.')
425
+
426
+ return state_space, trans_probs
427
+
428
+ def _extract_information(self, given_condition):
429
+ """
430
+ Helper function to extract information, like,
431
+ transition matrix/generator matrix, state space, etc.
432
+ """
433
+ if isinstance(self, DiscreteMarkovChain):
434
+ trans_probs = self.transition_probabilities
435
+ state_index = self._state_index
436
+ elif isinstance(self, ContinuousMarkovChain):
437
+ trans_probs = self.generator_matrix
438
+ state_index = self._state_index
439
+ if isinstance(given_condition, And):
440
+ gcs = given_condition.args
441
+ given_condition = S.true
442
+ for gc in gcs:
443
+ if isinstance(gc, TransitionMatrixOf):
444
+ trans_probs = gc.matrix
445
+ if isinstance(gc, StochasticStateSpaceOf):
446
+ state_index = gc.state_index
447
+ if isinstance(gc, Relational):
448
+ given_condition = given_condition & gc
449
+ if isinstance(given_condition, TransitionMatrixOf):
450
+ trans_probs = given_condition.matrix
451
+ given_condition = S.true
452
+ if isinstance(given_condition, StochasticStateSpaceOf):
453
+ state_index = given_condition.state_index
454
+ given_condition = S.true
455
+ return trans_probs, state_index, given_condition
456
+
457
+ def _check_trans_probs(self, trans_probs, row_sum=1):
458
+ """
459
+ Helper function for checking the validity of transition
460
+ probabilities.
461
+ """
462
+ if not isinstance(trans_probs, MatrixSymbol):
463
+ rows = trans_probs.tolist()
464
+ for row in rows:
465
+ if (sum(row) - row_sum) != 0:
466
+ raise ValueError("Values in a row must sum to %s. "
467
+ "If you are using Float or floats then please use Rational."%(row_sum))
468
+
469
+ def _work_out_state_index(self, state_index, given_condition, trans_probs):
470
+ """
471
+ Helper function to extract state space if there
472
+ is a random symbol in the given condition.
473
+ """
474
+ # if given condition is None, then there is no need to work out
475
+ # state_space from random variables
476
+ if given_condition != None:
477
+ rand_var = list(given_condition.atoms(RandomSymbol) -
478
+ given_condition.atoms(RandomIndexedSymbol))
479
+ if len(rand_var) == 1:
480
+ state_index = rand_var[0].pspace.set
481
+
482
+ # `not None` is `True`. So the old test fails for symbolic sizes.
483
+ # Need to build the statement differently.
484
+ sym_cond = not self.number_of_states.is_Integer
485
+ cond1 = not sym_cond and len(state_index) != trans_probs.shape[0]
486
+ if cond1:
487
+ raise ValueError("state space is not compatible with the transition probabilities.")
488
+ if not isinstance(trans_probs.shape[0], Symbol):
489
+ state_index = FiniteSet(*range(trans_probs.shape[0]))
490
+ return state_index
491
+
492
+ @cacheit
493
+ def _preprocess(self, given_condition, evaluate):
494
+ """
495
+ Helper function for pre-processing the information.
496
+ """
497
+ is_insufficient = False
498
+
499
+ if not evaluate: # avoid pre-processing if the result is not to be evaluated
500
+ return (True, None, None, None)
501
+
502
+ # extracting transition matrix and state space
503
+ trans_probs, state_index, given_condition = self._extract_information(given_condition)
504
+
505
+ # given_condition does not have sufficient information
506
+ # for computations
507
+ if trans_probs is None or \
508
+ given_condition is None:
509
+ is_insufficient = True
510
+ else:
511
+ # checking transition probabilities
512
+ if isinstance(self, DiscreteMarkovChain):
513
+ self._check_trans_probs(trans_probs, row_sum=1)
514
+ elif isinstance(self, ContinuousMarkovChain):
515
+ self._check_trans_probs(trans_probs, row_sum=0)
516
+
517
+ # working out state space
518
+ state_index = self._work_out_state_index(state_index, given_condition, trans_probs)
519
+
520
+ return is_insufficient, trans_probs, state_index, given_condition
521
+
522
+ def replace_with_index(self, condition):
523
+ if isinstance(condition, Relational):
524
+ lhs, rhs = condition.lhs, condition.rhs
525
+ if not isinstance(lhs, RandomIndexedSymbol):
526
+ lhs, rhs = rhs, lhs
527
+ condition = type(condition)(self.index_of.get(lhs, lhs),
528
+ self.index_of.get(rhs, rhs))
529
+ return condition
530
+
531
+ def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
532
+ """
533
+ Handles probability queries for Markov process.
534
+
535
+ Parameters
536
+ ==========
537
+
538
+ condition: Relational
539
+ given_condition: Relational/And
540
+
541
+ Returns
542
+ =======
543
+ Probability
544
+ If the information is not sufficient.
545
+ Expr
546
+ In all other cases.
547
+
548
+ Note
549
+ ====
550
+ Any information passed at the time of query overrides
551
+ any information passed at the time of object creation like
552
+ transition probabilities, state space.
553
+ Pass the transition matrix using TransitionMatrixOf,
554
+ generator matrix using GeneratorMatrixOf and state space
555
+ using StochasticStateSpaceOf in given_condition using & or And.
556
+ """
557
+ check, mat, state_index, new_given_condition = \
558
+ self._preprocess(given_condition, evaluate)
559
+
560
+ rv = list(condition.atoms(RandomIndexedSymbol))
561
+ symbolic = False
562
+ for sym in rv:
563
+ if sym.key.is_symbol:
564
+ symbolic = True
565
+ break
566
+
567
+ if check:
568
+ return Probability(condition, new_given_condition)
569
+
570
+ if isinstance(self, ContinuousMarkovChain):
571
+ trans_probs = self.transition_probabilities(mat)
572
+ elif isinstance(self, DiscreteMarkovChain):
573
+ trans_probs = mat
574
+ condition = self.replace_with_index(condition)
575
+ given_condition = self.replace_with_index(given_condition)
576
+ new_given_condition = self.replace_with_index(new_given_condition)
577
+
578
+ if isinstance(condition, Relational):
579
+ if isinstance(new_given_condition, And):
580
+ gcs = new_given_condition.args
581
+ else:
582
+ gcs = (new_given_condition, )
583
+ min_key_rv = list(new_given_condition.atoms(RandomIndexedSymbol))
584
+
585
+ if len(min_key_rv):
586
+ min_key_rv = min_key_rv[0]
587
+ for r in rv:
588
+ if min_key_rv.key.is_symbol or r.key.is_symbol:
589
+ continue
590
+ if min_key_rv.key > r.key:
591
+ return Probability(condition)
592
+ else:
593
+ min_key_rv = None
594
+ return Probability(condition)
595
+
596
+ if symbolic:
597
+ return self._symbolic_probability(condition, new_given_condition, rv, min_key_rv)
598
+
599
+ if len(rv) > 1:
600
+ rv[0] = condition.lhs
601
+ rv[1] = condition.rhs
602
+ if rv[0].key < rv[1].key:
603
+ rv[0], rv[1] = rv[1], rv[0]
604
+ if isinstance(condition, Gt):
605
+ condition = Lt(condition.lhs, condition.rhs)
606
+ elif isinstance(condition, Lt):
607
+ condition = Gt(condition.lhs, condition.rhs)
608
+ elif isinstance(condition, Ge):
609
+ condition = Le(condition.lhs, condition.rhs)
610
+ elif isinstance(condition, Le):
611
+ condition = Ge(condition.lhs, condition.rhs)
612
+ s = Rational(0, 1)
613
+ n = len(self.state_space)
614
+
615
+ if isinstance(condition, (Eq, Ne)):
616
+ for i in range(0, n):
617
+ s += self.probability(Eq(rv[0], i), Eq(rv[1], i)) * self.probability(Eq(rv[1], i), new_given_condition)
618
+ return s if isinstance(condition, Eq) else 1 - s
619
+ else:
620
+ upper = 0
621
+ greater = False
622
+ if isinstance(condition, (Ge, Lt)):
623
+ upper = 1
624
+ if isinstance(condition, (Ge, Gt)):
625
+ greater = True
626
+
627
+ for i in range(0, n):
628
+ if i <= n//2:
629
+ for j in range(0, i + upper):
630
+ s += self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition)
631
+ else:
632
+ s += self.probability(Eq(rv[0], i), new_given_condition)
633
+ for j in range(i + upper, n):
634
+ s -= self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition)
635
+ return s if greater else 1 - s
636
+
637
+ rv = rv[0]
638
+ states = condition.as_set()
639
+ prob, gstate = {}, None
640
+ for gc in gcs:
641
+ if gc.has(min_key_rv):
642
+ if gc.has(Probability):
643
+ p, gp = (gc.rhs, gc.lhs) if isinstance(gc.lhs, Probability) \
644
+ else (gc.lhs, gc.rhs)
645
+ gr = gp.args[0]
646
+ gset = Intersection(gr.as_set(), state_index)
647
+ gstate = list(gset)[0]
648
+ prob[gset] = p
649
+ else:
650
+ _, gstate = (gc.lhs.key, gc.rhs) if isinstance(gc.lhs, RandomIndexedSymbol) \
651
+ else (gc.rhs.key, gc.lhs)
652
+
653
+ if not all(k in self.index_set for k in (rv.key, min_key_rv.key)):
654
+ raise IndexError("The timestamps of the process are not in it's index set.")
655
+ states = Intersection(states, state_index) if not isinstance(self.number_of_states, Symbol) else states
656
+ for state in Union(states, FiniteSet(gstate)):
657
+ if not state.is_Integer or Ge(state, mat.shape[0]) is True:
658
+ raise IndexError("No information is available for (%s, %s) in "
659
+ "transition probabilities of shape, (%s, %s). "
660
+ "State space is zero indexed."
661
+ %(gstate, state, mat.shape[0], mat.shape[1]))
662
+ if prob:
663
+ gstates = Union(*prob.keys())
664
+ if len(gstates) == 1:
665
+ gstate = list(gstates)[0]
666
+ gprob = list(prob.values())[0]
667
+ prob[gstates] = gprob
668
+ elif len(gstates) == len(state_index) - 1:
669
+ gstate = list(state_index - gstates)[0]
670
+ gprob = S.One - sum(prob.values())
671
+ prob[state_index - gstates] = gprob
672
+ else:
673
+ raise ValueError("Conflicting information.")
674
+ else:
675
+ gprob = S.One
676
+
677
+ if min_key_rv == rv:
678
+ return sum(prob[FiniteSet(state)] for state in states)
679
+ if isinstance(self, ContinuousMarkovChain):
680
+ return gprob * sum(trans_probs(rv.key - min_key_rv.key).__getitem__((gstate, state))
681
+ for state in states)
682
+ if isinstance(self, DiscreteMarkovChain):
683
+ return gprob * sum((trans_probs**(rv.key - min_key_rv.key)).__getitem__((gstate, state))
684
+ for state in states)
685
+
686
+ if isinstance(condition, Not):
687
+ expr = condition.args[0]
688
+ return S.One - self.probability(expr, given_condition, evaluate, **kwargs)
689
+
690
+ if isinstance(condition, And):
691
+ compute_later, state2cond, conds = [], {}, condition.args
692
+ for expr in conds:
693
+ if isinstance(expr, Relational):
694
+ ris = list(expr.atoms(RandomIndexedSymbol))[0]
695
+ if state2cond.get(ris, None) is None:
696
+ state2cond[ris] = S.true
697
+ state2cond[ris] &= expr
698
+ else:
699
+ compute_later.append(expr)
700
+ ris = []
701
+ for ri in state2cond:
702
+ ris.append(ri)
703
+ cset = Intersection(state2cond[ri].as_set(), state_index)
704
+ if len(cset) == 0:
705
+ return S.Zero
706
+ state2cond[ri] = cset.as_relational(ri)
707
+ sorted_ris = sorted(ris, key=lambda ri: ri.key)
708
+ prod = self.probability(state2cond[sorted_ris[0]], given_condition, evaluate, **kwargs)
709
+ for i in range(1, len(sorted_ris)):
710
+ ri, prev_ri = sorted_ris[i], sorted_ris[i-1]
711
+ if not isinstance(state2cond[ri], Eq):
712
+ raise ValueError("The process is in multiple states at %s, unable to determine the probability."%(ri))
713
+ mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
714
+ prod *= self.probability(state2cond[ri], state2cond[prev_ri]
715
+ & mat_of
716
+ & StochasticStateSpaceOf(self, state_index),
717
+ evaluate, **kwargs)
718
+ for expr in compute_later:
719
+ prod *= self.probability(expr, given_condition, evaluate, **kwargs)
720
+ return prod
721
+
722
+ if isinstance(condition, Or):
723
+ return sum(self.probability(expr, given_condition, evaluate, **kwargs)
724
+ for expr in condition.args)
725
+
726
+ raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
727
+ "implemented yet."%(condition, given_condition))
728
+
729
+ def _symbolic_probability(self, condition, new_given_condition, rv, min_key_rv):
730
+ #Function to calculate probability for queries with symbols
731
+ if isinstance(condition, Relational):
732
+ curr_state = new_given_condition.rhs if isinstance(new_given_condition.lhs, RandomIndexedSymbol) \
733
+ else new_given_condition.lhs
734
+ next_state = condition.rhs if isinstance(condition.lhs, RandomIndexedSymbol) \
735
+ else condition.lhs
736
+
737
+ if isinstance(condition, (Eq, Ne)):
738
+ if isinstance(self, DiscreteMarkovChain):
739
+ P = self.transition_probabilities**(rv[0].key - min_key_rv.key)
740
+ else:
741
+ P = exp(self.generator_matrix*(rv[0].key - min_key_rv.key))
742
+ prob = P[curr_state, next_state] if isinstance(condition, Eq) else 1 - P[curr_state, next_state]
743
+ return Piecewise((prob, rv[0].key > min_key_rv.key), (Probability(condition), True))
744
+ else:
745
+ upper = 1
746
+ greater = False
747
+ if isinstance(condition, (Ge, Lt)):
748
+ upper = 0
749
+ if isinstance(condition, (Ge, Gt)):
750
+ greater = True
751
+ k = Dummy('k')
752
+ condition = Eq(condition.lhs, k) if isinstance(condition.lhs, RandomIndexedSymbol)\
753
+ else Eq(condition.rhs, k)
754
+ total = Sum(self.probability(condition, new_given_condition), (k, next_state + upper, self.state_space._sup))
755
+ return Piecewise((total, rv[0].key > min_key_rv.key), (Probability(condition), True)) if greater\
756
+ else Piecewise((1 - total, rv[0].key > min_key_rv.key), (Probability(condition), True))
757
+ else:
758
+ return Probability(condition, new_given_condition)
759
+
760
+ def expectation(self, expr, condition=None, evaluate=True, **kwargs):
761
+ """
762
+ Handles expectation queries for markov process.
763
+
764
+ Parameters
765
+ ==========
766
+
767
+ expr: RandomIndexedSymbol, Relational, Logic
768
+ Condition for which expectation has to be computed. Must
769
+ contain a RandomIndexedSymbol of the process.
770
+ condition: Relational, Logic
771
+ The given conditions under which computations should be done.
772
+
773
+ Returns
774
+ =======
775
+
776
+ Expectation
777
+ Unevaluated object if computations cannot be done due to
778
+ insufficient information.
779
+ Expr
780
+ In all other cases when the computations are successful.
781
+
782
+ Note
783
+ ====
784
+
785
+ Any information passed at the time of query overrides
786
+ any information passed at the time of object creation like
787
+ transition probabilities, state space.
788
+
789
+ Pass the transition matrix using TransitionMatrixOf,
790
+ generator matrix using GeneratorMatrixOf and state space
791
+ using StochasticStateSpaceOf in given_condition using & or And.
792
+ """
793
+
794
+ check, mat, state_index, condition = \
795
+ self._preprocess(condition, evaluate)
796
+
797
+ if check:
798
+ return Expectation(expr, condition)
799
+
800
+ rvs = random_symbols(expr)
801
+ if isinstance(expr, Expr) and isinstance(condition, Eq) \
802
+ and len(rvs) == 1:
803
+ # handle queries similar to E(f(X[i]), Eq(X[i-m], <some-state>))
804
+ condition=self.replace_with_index(condition)
805
+ state_index=self.replace_with_index(state_index)
806
+ rv = list(rvs)[0]
807
+ lhsg, rhsg = condition.lhs, condition.rhs
808
+ if not isinstance(lhsg, RandomIndexedSymbol):
809
+ lhsg, rhsg = (rhsg, lhsg)
810
+ if rhsg not in state_index:
811
+ raise ValueError("%s state is not in the state space."%(rhsg))
812
+ if rv.key < lhsg.key:
813
+ raise ValueError("Incorrect given condition is given, expectation "
814
+ "time %s < time %s"%(rv.key, rv.key))
815
+ mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
816
+ cond = condition & mat_of & \
817
+ StochasticStateSpaceOf(self, state_index)
818
+ func = lambda s: self.probability(Eq(rv, s), cond) * expr.subs(rv, self._state_index[s])
819
+ return sum(func(s) for s in state_index)
820
+
821
+ raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
822
+ "implemented yet."%(expr, condition))
823
+
824
+ class DiscreteMarkovChain(DiscreteTimeStochasticProcess, MarkovProcess):
825
+ """
826
+ Represents a finite discrete time-homogeneous Markov chain.
827
+
828
+ This type of Markov Chain can be uniquely characterised by
829
+ its (ordered) state space and its one-step transition probability
830
+ matrix.
831
+
832
+ Parameters
833
+ ==========
834
+
835
+ sym:
836
+ The name given to the Markov Chain
837
+ state_space:
838
+ Optional, by default, Range(n)
839
+ trans_probs:
840
+ Optional, by default, MatrixSymbol('_T', n, n)
841
+
842
+ Examples
843
+ ========
844
+
845
+ >>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf, P, E
846
+ >>> from sympy import Matrix, MatrixSymbol, Eq, symbols
847
+ >>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
848
+ >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
849
+ >>> YS = DiscreteMarkovChain("Y")
850
+
851
+ >>> Y.state_space
852
+ {0, 1, 2}
853
+ >>> Y.transition_probabilities
854
+ Matrix([
855
+ [0.5, 0.2, 0.3],
856
+ [0.2, 0.5, 0.3],
857
+ [0.2, 0.3, 0.5]])
858
+ >>> TS = MatrixSymbol('T', 3, 3)
859
+ >>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS))
860
+ T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2]
861
+ >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2)
862
+ 0.36
863
+
864
+ Probabilities will be calculated based on indexes rather
865
+ than state names. For example, with the Sunny-Cloudy-Rainy
866
+ model with string state names:
867
+
868
+ >>> from sympy.core.symbol import Str
869
+ >>> Y = DiscreteMarkovChain("Y", [Str('Sunny'), Str('Cloudy'), Str('Rainy')], T)
870
+ >>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2)
871
+ 0.36
872
+
873
+ This gives the same answer as the ``[0, 1, 2]`` state space.
874
+ Currently, there is no support for state names within probability
875
+ and expectation statements. Here is a work-around using ``Str``:
876
+
877
+ >>> P(Eq(Str('Rainy'), Y[3]), Eq(Y[1], Str('Cloudy'))).round(2)
878
+ 0.36
879
+
880
+ Symbol state names can also be used:
881
+
882
+ >>> sunny, cloudy, rainy = symbols('Sunny, Cloudy, Rainy')
883
+ >>> Y = DiscreteMarkovChain("Y", [sunny, cloudy, rainy], T)
884
+ >>> P(Eq(Y[3], rainy), Eq(Y[1], cloudy)).round(2)
885
+ 0.36
886
+
887
+ Expectations will be calculated as follows:
888
+
889
+ >>> E(Y[3], Eq(Y[1], cloudy))
890
+ 0.38*Cloudy + 0.36*Rainy + 0.26*Sunny
891
+
892
+ Probability of expressions with multiple RandomIndexedSymbols
893
+ can also be calculated provided there is only 1 RandomIndexedSymbol
894
+ in the given condition. It is always better to use Rational instead
895
+ of floating point numbers for the probabilities in the
896
+ transition matrix to avoid errors.
897
+
898
+ >>> from sympy import Gt, Le, Rational
899
+ >>> T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]])
900
+ >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
901
+ >>> P(Eq(Y[3], Y[1]), Eq(Y[0], 0)).round(3)
902
+ 0.409
903
+ >>> P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2)
904
+ 0.36
905
+ >>> P(Le(Y[15], Y[10]), Eq(Y[8], 2)).round(7)
906
+ 0.6963328
907
+
908
+ Symbolic probability queries are also supported
909
+
910
+ >>> a, b, c, d = symbols('a b c d')
911
+ >>> T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]])
912
+ >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
913
+ >>> query = P(Eq(Y[a], b), Eq(Y[c], d))
914
+ >>> query.subs({a:10, b:2, c:5, d:1}).round(4)
915
+ 0.3096
916
+ >>> P(Eq(Y[10], 2), Eq(Y[5], 1)).evalf().round(4)
917
+ 0.3096
918
+ >>> query_gt = P(Gt(Y[a], b), Eq(Y[c], d))
919
+ >>> query_gt.subs({a:21, b:0, c:5, d:0}).evalf().round(5)
920
+ 0.64705
921
+ >>> P(Gt(Y[21], 0), Eq(Y[5], 0)).round(5)
922
+ 0.64705
923
+
924
+ There is limited support for arbitrarily sized states:
925
+
926
+ >>> n = symbols('n', nonnegative=True, integer=True)
927
+ >>> T = MatrixSymbol('T', n, n)
928
+ >>> Y = DiscreteMarkovChain("Y", trans_probs=T)
929
+ >>> Y.state_space
930
+ Range(0, n, 1)
931
+ >>> query = P(Eq(Y[a], b), Eq(Y[c], d))
932
+ >>> query.subs({a:10, b:2, c:5, d:1})
933
+ (T**5)[1, 2]
934
+
935
+ References
936
+ ==========
937
+
938
+ .. [1] https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain
939
+ .. [2] https://web.archive.org/web/20201230182007/https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf
940
+ """
941
+ index_set = S.Naturals0
942
+
943
+ def __new__(cls, sym, state_space=None, trans_probs=None):
944
+ sym = _symbol_converter(sym)
945
+
946
+ state_space, trans_probs = MarkovProcess._sanity_checks(state_space, trans_probs)
947
+
948
+ obj = Basic.__new__(cls, sym, state_space, trans_probs) # type: ignore
949
+ indices = {}
950
+ if isinstance(obj.number_of_states, Integer):
951
+ for index, state in enumerate(obj._state_index):
952
+ indices[state] = index
953
+ obj.index_of = indices
954
+ return obj
955
+
956
+ @property
957
+ def transition_probabilities(self):
958
+ """
959
+ Transition probabilities of discrete Markov chain,
960
+ either an instance of Matrix or MatrixSymbol.
961
+ """
962
+ return self.args[2]
963
+
964
+ def communication_classes(self) -> tList[tTuple[tList[Basic], Boolean, Integer]]:
965
+ """
966
+ Returns the list of communication classes that partition
967
+ the states of the markov chain.
968
+
969
+ A communication class is defined to be a set of states
970
+ such that every state in that set is reachable from
971
+ every other state in that set. Due to its properties
972
+ this forms a class in the mathematical sense.
973
+ Communication classes are also known as recurrence
974
+ classes.
975
+
976
+ Returns
977
+ =======
978
+
979
+ classes
980
+ The ``classes`` are a list of tuples. Each
981
+ tuple represents a single communication class
982
+ with its properties. The first element in the
983
+ tuple is the list of states in the class, the
984
+ second element is whether the class is recurrent
985
+ and the third element is the period of the
986
+ communication class.
987
+
988
+ Examples
989
+ ========
990
+
991
+ >>> from sympy.stats import DiscreteMarkovChain
992
+ >>> from sympy import Matrix
993
+ >>> T = Matrix([[0, 1, 0],
994
+ ... [1, 0, 0],
995
+ ... [1, 0, 0]])
996
+ >>> X = DiscreteMarkovChain('X', [1, 2, 3], T)
997
+ >>> classes = X.communication_classes()
998
+ >>> for states, is_recurrent, period in classes:
999
+ ... states, is_recurrent, period
1000
+ ([1, 2], True, 2)
1001
+ ([3], False, 1)
1002
+
1003
+ From this we can see that states ``1`` and ``2``
1004
+ communicate, are recurrent and have a period
1005
+ of 2. We can also see state ``3`` is transient
1006
+ with a period of 1.
1007
+
1008
+ Notes
1009
+ =====
1010
+
1011
+ The algorithm used is of order ``O(n**2)`` where
1012
+ ``n`` is the number of states in the markov chain.
1013
+ It uses Tarjan's algorithm to find the classes
1014
+ themselves and then it uses a breadth-first search
1015
+ algorithm to find each class's periodicity.
1016
+ Most of the algorithm's components approach ``O(n)``
1017
+ as the matrix becomes more and more sparse.
1018
+
1019
+ References
1020
+ ==========
1021
+
1022
+ .. [1] https://web.archive.org/web/20220207032113/https://www.columbia.edu/~ww2040/4701Sum07/4701-06-Notes-MCII.pdf
1023
+ .. [2] https://cecas.clemson.edu/~shierd/Shier/markov.pdf
1024
+ .. [3] https://www.proquest.com/openview/4adc6a51d8371be5b0e4c7dff287fc70/1?pq-origsite=gscholar&cbl=2026366&diss=y
1025
+ .. [4] https://www.mathworks.com/help/econ/dtmc.classify.html
1026
+ """
1027
+ n = self.number_of_states
1028
+ T = self.transition_probabilities
1029
+
1030
+ if isinstance(T, MatrixSymbol):
1031
+ raise NotImplementedError("Cannot perform the operation with a symbolic matrix.")
1032
+
1033
+ # begin Tarjan's algorithm
1034
+ V = Range(n)
1035
+ # don't use state names. Rather use state
1036
+ # indexes since we use them for matrix
1037
+ # indexing here and later onward
1038
+ E = [(i, j) for i in V for j in V if T[i, j] != 0]
1039
+ classes = strongly_connected_components((V, E))
1040
+ # end Tarjan's algorithm
1041
+
1042
+ recurrence = []
1043
+ periods = []
1044
+ for class_ in classes:
1045
+ # begin recurrent check (similar to self._check_trans_probs())
1046
+ submatrix = T[class_, class_] # get the submatrix with those states
1047
+ is_recurrent = S.true
1048
+ rows = submatrix.tolist()
1049
+ for row in rows:
1050
+ if (sum(row) - 1) != 0:
1051
+ is_recurrent = S.false
1052
+ break
1053
+ recurrence.append(is_recurrent)
1054
+ # end recurrent check
1055
+
1056
+ # begin breadth-first search
1057
+ non_tree_edge_values: tSet[int] = set()
1058
+ visited = {class_[0]}
1059
+ newly_visited = {class_[0]}
1060
+ level = {class_[0]: 0}
1061
+ current_level = 0
1062
+ done = False # imitate a do-while loop
1063
+ while not done: # runs at most len(class_) times
1064
+ done = len(visited) == len(class_)
1065
+ current_level += 1
1066
+
1067
+ # this loop and the while loop above run a combined len(class_) number of times.
1068
+ # so this triple nested loop runs through each of the n states once.
1069
+ for i in newly_visited:
1070
+
1071
+ # the loop below runs len(class_) number of times
1072
+ # complexity is around about O(n * avg(len(class_)))
1073
+ newly_visited = {j for j in class_ if T[i, j] != 0}
1074
+
1075
+ new_tree_edges = newly_visited.difference(visited)
1076
+ for j in new_tree_edges:
1077
+ level[j] = current_level
1078
+
1079
+ new_non_tree_edges = newly_visited.intersection(visited)
1080
+ new_non_tree_edge_values = {level[i]-level[j]+1 for j in new_non_tree_edges}
1081
+
1082
+ non_tree_edge_values = non_tree_edge_values.union(new_non_tree_edge_values)
1083
+ visited = visited.union(new_tree_edges)
1084
+
1085
+ # igcd needs at least 2 arguments
1086
+ positive_ntev = {val_e for val_e in non_tree_edge_values if val_e > 0}
1087
+ if len(positive_ntev) == 0:
1088
+ periods.append(len(class_))
1089
+ elif len(positive_ntev) == 1:
1090
+ periods.append(positive_ntev.pop())
1091
+ else:
1092
+ periods.append(igcd(*positive_ntev))
1093
+ # end breadth-first search
1094
+
1095
+ # convert back to the user's state names
1096
+ classes = [[_sympify(self._state_index[i]) for i in class_] for class_ in classes]
1097
+ return list(zip(classes, recurrence, map(Integer,periods)))
1098
+
1099
+ def fundamental_matrix(self):
1100
+ """
1101
+ Each entry fundamental matrix can be interpreted as
1102
+ the expected number of times the chains is in state j
1103
+ if it started in state i.
1104
+
1105
+ References
1106
+ ==========
1107
+
1108
+ .. [1] https://lips.cs.princeton.edu/the-fundamental-matrix-of-a-finite-markov-chain/
1109
+
1110
+ """
1111
+ _, _, _, Q = self.decompose()
1112
+
1113
+ if Q.shape[0] > 0: # if non-ergodic
1114
+ I = eye(Q.shape[0])
1115
+ if (I - Q).det() == 0:
1116
+ raise ValueError("The fundamental matrix doesn't exist.")
1117
+ return (I - Q).inv().as_immutable()
1118
+ else: # if ergodic
1119
+ P = self.transition_probabilities
1120
+ I = eye(P.shape[0])
1121
+ w = self.fixed_row_vector()
1122
+ W = Matrix([list(w) for i in range(0, P.shape[0])])
1123
+ if (I - P + W).det() == 0:
1124
+ raise ValueError("The fundamental matrix doesn't exist.")
1125
+ return (I - P + W).inv().as_immutable()
1126
+
1127
+ def absorbing_probabilities(self):
1128
+ """
1129
+ Computes the absorbing probabilities, i.e.
1130
+ the ij-th entry of the matrix denotes the
1131
+ probability of Markov chain being absorbed
1132
+ in state j starting from state i.
1133
+ """
1134
+ _, _, R, _ = self.decompose()
1135
+ N = self.fundamental_matrix()
1136
+ if R is None or N is None:
1137
+ return None
1138
+ return N*R
1139
+
1140
+ def absorbing_probabilites(self):
1141
+ sympy_deprecation_warning(
1142
+ """
1143
+ DiscreteMarkovChain.absorbing_probabilites() is deprecated. Use
1144
+ absorbing_probabilities() instead (note the spelling difference).
1145
+ """,
1146
+ deprecated_since_version="1.7",
1147
+ active_deprecations_target="deprecated-absorbing_probabilites",
1148
+ )
1149
+ return self.absorbing_probabilities()
1150
+
1151
+ def is_regular(self):
1152
+ tuples = self.communication_classes()
1153
+ if len(tuples) == 0:
1154
+ return S.false # not defined for a 0x0 matrix
1155
+ classes, _, periods = list(zip(*tuples))
1156
+ return And(len(classes) == 1, periods[0] == 1)
1157
+
1158
+ def is_ergodic(self):
1159
+ tuples = self.communication_classes()
1160
+ if len(tuples) == 0:
1161
+ return S.false # not defined for a 0x0 matrix
1162
+ classes, _, _ = list(zip(*tuples))
1163
+ return S(len(classes) == 1)
1164
+
1165
+ def is_absorbing_state(self, state):
1166
+ trans_probs = self.transition_probabilities
1167
+ if isinstance(trans_probs, ImmutableMatrix) and \
1168
+ state < trans_probs.shape[0]:
1169
+ return S(trans_probs[state, state]) is S.One
1170
+
1171
+ def is_absorbing_chain(self):
1172
+ states, A, B, C = self.decompose()
1173
+ r = A.shape[0]
1174
+ return And(r > 0, A == Identity(r).as_explicit())
1175
+
1176
+ def stationary_distribution(self, condition_set=False) -> tUnion[ImmutableMatrix, ConditionSet, Lambda]:
1177
+ r"""
1178
+ The stationary distribution is any row vector, p, that solves p = pP,
1179
+ is row stochastic and each element in p must be nonnegative.
1180
+ That means in matrix form: :math:`(P-I)^T p^T = 0` and
1181
+ :math:`(1, \dots, 1) p = 1`
1182
+ where ``P`` is the one-step transition matrix.
1183
+
1184
+ All time-homogeneous Markov Chains with a finite state space
1185
+ have at least one stationary distribution. In addition, if
1186
+ a finite time-homogeneous Markov Chain is irreducible, the
1187
+ stationary distribution is unique.
1188
+
1189
+ Parameters
1190
+ ==========
1191
+
1192
+ condition_set : bool
1193
+ If the chain has a symbolic size or transition matrix,
1194
+ it will return a ``Lambda`` if ``False`` and return a
1195
+ ``ConditionSet`` if ``True``.
1196
+
1197
+ Examples
1198
+ ========
1199
+
1200
+ >>> from sympy.stats import DiscreteMarkovChain
1201
+ >>> from sympy import Matrix, S
1202
+
1203
+ An irreducible Markov Chain
1204
+
1205
+ >>> T = Matrix([[S(1)/2, S(1)/2, 0],
1206
+ ... [S(4)/5, S(1)/5, 0],
1207
+ ... [1, 0, 0]])
1208
+ >>> X = DiscreteMarkovChain('X', trans_probs=T)
1209
+ >>> X.stationary_distribution()
1210
+ Matrix([[8/13, 5/13, 0]])
1211
+
1212
+ A reducible Markov Chain
1213
+
1214
+ >>> T = Matrix([[S(1)/2, S(1)/2, 0],
1215
+ ... [S(4)/5, S(1)/5, 0],
1216
+ ... [0, 0, 1]])
1217
+ >>> X = DiscreteMarkovChain('X', trans_probs=T)
1218
+ >>> X.stationary_distribution()
1219
+ Matrix([[8/13 - 8*tau0/13, 5/13 - 5*tau0/13, tau0]])
1220
+
1221
+ >>> Y = DiscreteMarkovChain('Y')
1222
+ >>> Y.stationary_distribution()
1223
+ Lambda((wm, _T), Eq(wm*_T, wm))
1224
+
1225
+ >>> Y.stationary_distribution(condition_set=True)
1226
+ ConditionSet(wm, Eq(wm*_T, wm))
1227
+
1228
+ References
1229
+ ==========
1230
+
1231
+ .. [1] https://www.probabilitycourse.com/chapter11/11_2_6_stationary_and_limiting_distributions.php
1232
+ .. [2] https://web.archive.org/web/20210508104430/https://galton.uchicago.edu/~yibi/teaching/stat317/2014/Lectures/Lecture4_6up.pdf
1233
+
1234
+ See Also
1235
+ ========
1236
+
1237
+ sympy.stats.DiscreteMarkovChain.limiting_distribution
1238
+ """
1239
+ trans_probs = self.transition_probabilities
1240
+ n = self.number_of_states
1241
+
1242
+ if n == 0:
1243
+ return ImmutableMatrix(Matrix([[]]))
1244
+
1245
+ # symbolic matrix version
1246
+ if isinstance(trans_probs, MatrixSymbol):
1247
+ wm = MatrixSymbol('wm', 1, n)
1248
+ if condition_set:
1249
+ return ConditionSet(wm, Eq(wm * trans_probs, wm))
1250
+ else:
1251
+ return Lambda((wm, trans_probs), Eq(wm * trans_probs, wm))
1252
+
1253
+ # numeric matrix version
1254
+ a = Matrix(trans_probs - Identity(n)).T
1255
+ a[0, 0:n] = ones(1, n) # type: ignore
1256
+ b = zeros(n, 1)
1257
+ b[0, 0] = 1
1258
+
1259
+ soln = list(linsolve((a, b)))[0]
1260
+ return ImmutableMatrix([soln])
1261
+
1262
+ def fixed_row_vector(self):
1263
+ """
1264
+ A wrapper for ``stationary_distribution()``.
1265
+ """
1266
+ return self.stationary_distribution()
1267
+
1268
+ @property
1269
+ def limiting_distribution(self):
1270
+ """
1271
+ The fixed row vector is the limiting
1272
+ distribution of a discrete Markov chain.
1273
+ """
1274
+ return self.fixed_row_vector()
1275
+
1276
+ def decompose(self) -> tTuple[tList[Basic], ImmutableMatrix, ImmutableMatrix, ImmutableMatrix]:
1277
+ """
1278
+ Decomposes the transition matrix into submatrices with
1279
+ special properties.
1280
+
1281
+ The transition matrix can be decomposed into 4 submatrices:
1282
+ - A - the submatrix from recurrent states to recurrent states.
1283
+ - B - the submatrix from transient to recurrent states.
1284
+ - C - the submatrix from transient to transient states.
1285
+ - O - the submatrix of zeros for recurrent to transient states.
1286
+
1287
+ Returns
1288
+ =======
1289
+
1290
+ states, A, B, C
1291
+ ``states`` - a list of state names with the first being
1292
+ the recurrent states and the last being
1293
+ the transient states in the order
1294
+ of the row names of A and then the row names of C.
1295
+ ``A`` - the submatrix from recurrent states to recurrent states.
1296
+ ``B`` - the submatrix from transient to recurrent states.
1297
+ ``C`` - the submatrix from transient to transient states.
1298
+
1299
+ Examples
1300
+ ========
1301
+
1302
+ >>> from sympy.stats import DiscreteMarkovChain
1303
+ >>> from sympy import Matrix, S
1304
+
1305
+ One can decompose this chain for example:
1306
+
1307
+ >>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0],
1308
+ ... [S(2)/5, S(1)/5, S(2)/5, 0, 0],
1309
+ ... [0, 0, 1, 0, 0],
1310
+ ... [0, 0, S(1)/2, S(1)/2, 0],
1311
+ ... [S(1)/2, 0, 0, 0, S(1)/2]])
1312
+ >>> X = DiscreteMarkovChain('X', trans_probs=T)
1313
+ >>> states, A, B, C = X.decompose()
1314
+ >>> states
1315
+ [2, 0, 1, 3, 4]
1316
+
1317
+ >>> A # recurrent to recurrent
1318
+ Matrix([[1]])
1319
+
1320
+ >>> B # transient to recurrent
1321
+ Matrix([
1322
+ [ 0],
1323
+ [2/5],
1324
+ [1/2],
1325
+ [ 0]])
1326
+
1327
+ >>> C # transient to transient
1328
+ Matrix([
1329
+ [1/2, 1/2, 0, 0],
1330
+ [2/5, 1/5, 0, 0],
1331
+ [ 0, 0, 1/2, 0],
1332
+ [1/2, 0, 0, 1/2]])
1333
+
1334
+ This means that state 2 is the only absorbing state
1335
+ (since A is a 1x1 matrix). B is a 4x1 matrix since
1336
+ the 4 remaining transient states all merge into reccurent
1337
+ state 2. And C is the 4x4 matrix that shows how the
1338
+ transient states 0, 1, 3, 4 all interact.
1339
+
1340
+ See Also
1341
+ ========
1342
+
1343
+ sympy.stats.DiscreteMarkovChain.communication_classes
1344
+ sympy.stats.DiscreteMarkovChain.canonical_form
1345
+
1346
+ References
1347
+ ==========
1348
+
1349
+ .. [1] https://en.wikipedia.org/wiki/Absorbing_Markov_chain
1350
+ .. [2] https://people.brandeis.edu/~igusa/Math56aS08/Math56a_S08_notes015.pdf
1351
+ """
1352
+ trans_probs = self.transition_probabilities
1353
+
1354
+ classes = self.communication_classes()
1355
+ r_states = []
1356
+ t_states = []
1357
+
1358
+ for states, recurrent, period in classes:
1359
+ if recurrent:
1360
+ r_states += states
1361
+ else:
1362
+ t_states += states
1363
+
1364
+ states = r_states + t_states
1365
+ indexes = [self.index_of[state] for state in states] # type: ignore
1366
+
1367
+ A = Matrix(len(r_states), len(r_states),
1368
+ lambda i, j: trans_probs[indexes[i], indexes[j]])
1369
+
1370
+ B = Matrix(len(t_states), len(r_states),
1371
+ lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[j]])
1372
+
1373
+ C = Matrix(len(t_states), len(t_states),
1374
+ lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[len(r_states) + j]])
1375
+
1376
+ return states, A.as_immutable(), B.as_immutable(), C.as_immutable()
1377
+
1378
+ def canonical_form(self) -> tTuple[tList[Basic], ImmutableMatrix]:
1379
+ """
1380
+ Reorders the one-step transition matrix
1381
+ so that recurrent states appear first and transient
1382
+ states appear last. Other representations include inserting
1383
+ transient states first and recurrent states last.
1384
+
1385
+ Returns
1386
+ =======
1387
+
1388
+ states, P_new
1389
+ ``states`` is the list that describes the order of the
1390
+ new states in the matrix
1391
+ so that the ith element in ``states`` is the state of the
1392
+ ith row of A.
1393
+ ``P_new`` is the new transition matrix in canonical form.
1394
+
1395
+ Examples
1396
+ ========
1397
+
1398
+ >>> from sympy.stats import DiscreteMarkovChain
1399
+ >>> from sympy import Matrix, S
1400
+
1401
+ You can convert your chain into canonical form:
1402
+
1403
+ >>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0],
1404
+ ... [S(2)/5, S(1)/5, S(2)/5, 0, 0],
1405
+ ... [0, 0, 1, 0, 0],
1406
+ ... [0, 0, S(1)/2, S(1)/2, 0],
1407
+ ... [S(1)/2, 0, 0, 0, S(1)/2]])
1408
+ >>> X = DiscreteMarkovChain('X', list(range(1, 6)), trans_probs=T)
1409
+ >>> states, new_matrix = X.canonical_form()
1410
+ >>> states
1411
+ [3, 1, 2, 4, 5]
1412
+
1413
+ >>> new_matrix
1414
+ Matrix([
1415
+ [ 1, 0, 0, 0, 0],
1416
+ [ 0, 1/2, 1/2, 0, 0],
1417
+ [2/5, 2/5, 1/5, 0, 0],
1418
+ [1/2, 0, 0, 1/2, 0],
1419
+ [ 0, 1/2, 0, 0, 1/2]])
1420
+
1421
+ The new states are [3, 1, 2, 4, 5] and you can
1422
+ create a new chain with this and its canonical
1423
+ form will remain the same (since it is already
1424
+ in canonical form).
1425
+
1426
+ >>> X = DiscreteMarkovChain('X', states, new_matrix)
1427
+ >>> states, new_matrix = X.canonical_form()
1428
+ >>> states
1429
+ [3, 1, 2, 4, 5]
1430
+
1431
+ >>> new_matrix
1432
+ Matrix([
1433
+ [ 1, 0, 0, 0, 0],
1434
+ [ 0, 1/2, 1/2, 0, 0],
1435
+ [2/5, 2/5, 1/5, 0, 0],
1436
+ [1/2, 0, 0, 1/2, 0],
1437
+ [ 0, 1/2, 0, 0, 1/2]])
1438
+
1439
+ This is not limited to absorbing chains:
1440
+
1441
+ >>> T = Matrix([[0, 5, 5, 0, 0],
1442
+ ... [0, 0, 0, 10, 0],
1443
+ ... [5, 0, 5, 0, 0],
1444
+ ... [0, 10, 0, 0, 0],
1445
+ ... [0, 3, 0, 3, 4]])/10
1446
+ >>> X = DiscreteMarkovChain('X', trans_probs=T)
1447
+ >>> states, new_matrix = X.canonical_form()
1448
+ >>> states
1449
+ [1, 3, 0, 2, 4]
1450
+
1451
+ >>> new_matrix
1452
+ Matrix([
1453
+ [ 0, 1, 0, 0, 0],
1454
+ [ 1, 0, 0, 0, 0],
1455
+ [ 1/2, 0, 0, 1/2, 0],
1456
+ [ 0, 0, 1/2, 1/2, 0],
1457
+ [3/10, 3/10, 0, 0, 2/5]])
1458
+
1459
+ See Also
1460
+ ========
1461
+
1462
+ sympy.stats.DiscreteMarkovChain.communication_classes
1463
+ sympy.stats.DiscreteMarkovChain.decompose
1464
+
1465
+ References
1466
+ ==========
1467
+
1468
+ .. [1] https://onlinelibrary.wiley.com/doi/pdf/10.1002/9780470316887.app1
1469
+ .. [2] http://www.columbia.edu/~ww2040/6711F12/lect1023big.pdf
1470
+ """
1471
+ states, A, B, C = self.decompose()
1472
+ O = zeros(A.shape[0], C.shape[1])
1473
+ return states, BlockMatrix([[A, O], [B, C]]).as_explicit()
1474
+
1475
+ def sample(self):
1476
+ """
1477
+ Returns
1478
+ =======
1479
+
1480
+ sample: iterator object
1481
+ iterator object containing the sample
1482
+
1483
+ """
1484
+ if not isinstance(self.transition_probabilities, (Matrix, ImmutableMatrix)):
1485
+ raise ValueError("Transition Matrix must be provided for sampling")
1486
+ Tlist = self.transition_probabilities.tolist()
1487
+ samps = [random.choice(list(self.state_space))]
1488
+ yield samps[0]
1489
+ time = 1
1490
+ densities = {}
1491
+ for state in self.state_space:
1492
+ states = list(self.state_space)
1493
+ densities[state] = {states[i]: Tlist[state][i]
1494
+ for i in range(len(states))}
1495
+ while time < S.Infinity:
1496
+ samps.append((next(sample_iter(FiniteRV("_", densities[samps[time - 1]])))))
1497
+ yield samps[time]
1498
+ time += 1
1499
+
1500
+ class ContinuousMarkovChain(ContinuousTimeStochasticProcess, MarkovProcess):
1501
+ """
1502
+ Represents continuous time Markov chain.
1503
+
1504
+ Parameters
1505
+ ==========
1506
+
1507
+ sym : Symbol/str
1508
+ state_space : Set
1509
+ Optional, by default, S.Reals
1510
+ gen_mat : Matrix/ImmutableMatrix/MatrixSymbol
1511
+ Optional, by default, None
1512
+
1513
+ Examples
1514
+ ========
1515
+
1516
+ >>> from sympy.stats import ContinuousMarkovChain, P
1517
+ >>> from sympy import Matrix, S, Eq, Gt
1518
+ >>> G = Matrix([[-S(1), S(1)], [S(1), -S(1)]])
1519
+ >>> C = ContinuousMarkovChain('C', state_space=[0, 1], gen_mat=G)
1520
+ >>> C.limiting_distribution()
1521
+ Matrix([[1/2, 1/2]])
1522
+ >>> C.state_space
1523
+ {0, 1}
1524
+ >>> C.generator_matrix
1525
+ Matrix([
1526
+ [-1, 1],
1527
+ [ 1, -1]])
1528
+
1529
+ Probability queries are supported
1530
+
1531
+ >>> P(Eq(C(1.96), 0), Eq(C(0.78), 1)).round(5)
1532
+ 0.45279
1533
+ >>> P(Gt(C(1.7), 0), Eq(C(0.82), 1)).round(5)
1534
+ 0.58602
1535
+
1536
+ Probability of expressions with multiple RandomIndexedSymbols
1537
+ can also be calculated provided there is only 1 RandomIndexedSymbol
1538
+ in the given condition. It is always better to use Rational instead
1539
+ of floating point numbers for the probabilities in the
1540
+ generator matrix to avoid errors.
1541
+
1542
+ >>> from sympy import Gt, Le, Rational
1543
+ >>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]])
1544
+ >>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
1545
+ >>> P(Eq(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5)
1546
+ 0.37933
1547
+ >>> P(Gt(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5)
1548
+ 0.34211
1549
+ >>> P(Le(C(1.57), C(3.14)), Eq(C(1.22), 1)).round(4)
1550
+ 0.7143
1551
+
1552
+ Symbolic probability queries are also supported
1553
+
1554
+ >>> from sympy import symbols
1555
+ >>> a,b,c,d = symbols('a b c d')
1556
+ >>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]])
1557
+ >>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
1558
+ >>> query = P(Eq(C(a), b), Eq(C(c), d))
1559
+ >>> query.subs({a:3.65, b:2, c:1.78, d:1}).evalf().round(10)
1560
+ 0.4002723175
1561
+ >>> P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10)
1562
+ 0.4002723175
1563
+ >>> query_gt = P(Gt(C(a), b), Eq(C(c), d))
1564
+ >>> query_gt.subs({a:43.2, b:0, c:3.29, d:2}).evalf().round(10)
1565
+ 0.6832579186
1566
+ >>> P(Gt(C(43.2), 0), Eq(C(3.29), 2)).round(10)
1567
+ 0.6832579186
1568
+
1569
+ References
1570
+ ==========
1571
+
1572
+ .. [1] https://en.wikipedia.org/wiki/Markov_chain#Continuous-time_Markov_chain
1573
+ .. [2] https://u.math.biu.ac.il/~amirgi/CTMCnotes.pdf
1574
+ """
1575
+ index_set = S.Reals
1576
+
1577
+ def __new__(cls, sym, state_space=None, gen_mat=None):
1578
+ sym = _symbol_converter(sym)
1579
+ state_space, gen_mat = MarkovProcess._sanity_checks(state_space, gen_mat)
1580
+ obj = Basic.__new__(cls, sym, state_space, gen_mat)
1581
+ indices = {}
1582
+ if isinstance(obj.number_of_states, Integer):
1583
+ for index, state in enumerate(obj.state_space):
1584
+ indices[state] = index
1585
+ obj.index_of = indices
1586
+ return obj
1587
+
1588
+ @property
1589
+ def generator_matrix(self):
1590
+ return self.args[2]
1591
+
1592
+ @cacheit
1593
+ def transition_probabilities(self, gen_mat=None):
1594
+ t = Dummy('t')
1595
+ if isinstance(gen_mat, (Matrix, ImmutableMatrix)) and \
1596
+ gen_mat.is_diagonalizable():
1597
+ # for faster computation use diagonalized generator matrix
1598
+ Q, D = gen_mat.diagonalize()
1599
+ return Lambda(t, Q*exp(t*D)*Q.inv())
1600
+ if gen_mat != None:
1601
+ return Lambda(t, exp(t*gen_mat))
1602
+
1603
+ def limiting_distribution(self):
1604
+ gen_mat = self.generator_matrix
1605
+ if gen_mat is None:
1606
+ return None
1607
+ if isinstance(gen_mat, MatrixSymbol):
1608
+ wm = MatrixSymbol('wm', 1, gen_mat.shape[0])
1609
+ return Lambda((wm, gen_mat), Eq(wm*gen_mat, wm))
1610
+ w = IndexedBase('w')
1611
+ wi = [w[i] for i in range(gen_mat.shape[0])]
1612
+ wm = Matrix([wi])
1613
+ eqs = (wm*gen_mat).tolist()[0]
1614
+ eqs.append(sum(wi) - 1)
1615
+ soln = list(linsolve(eqs, wi))[0]
1616
+ return ImmutableMatrix([soln])
1617
+
1618
+
1619
+ class BernoulliProcess(DiscreteTimeStochasticProcess):
1620
+ """
1621
+ The Bernoulli process consists of repeated
1622
+ independent Bernoulli process trials with the same parameter `p`.
1623
+ It's assumed that the probability `p` applies to every
1624
+ trial and that the outcomes of each trial
1625
+ are independent of all the rest. Therefore Bernoulli Process
1626
+ is Discrete State and Discrete Time Stochastic Process.
1627
+
1628
+ Parameters
1629
+ ==========
1630
+
1631
+ sym : Symbol/str
1632
+ success : Integer/str
1633
+ The event which is considered to be success. Default: 1.
1634
+ failure: Integer/str
1635
+ The event which is considered to be failure. Default: 0.
1636
+ p : Real Number between 0 and 1
1637
+ Represents the probability of getting success.
1638
+
1639
+ Examples
1640
+ ========
1641
+
1642
+ >>> from sympy.stats import BernoulliProcess, P, E
1643
+ >>> from sympy import Eq, Gt
1644
+ >>> B = BernoulliProcess("B", p=0.7, success=1, failure=0)
1645
+ >>> B.state_space
1646
+ {0, 1}
1647
+ >>> B.p.round(2)
1648
+ 0.70
1649
+ >>> B.success
1650
+ 1
1651
+ >>> B.failure
1652
+ 0
1653
+ >>> X = B[1] + B[2] + B[3]
1654
+ >>> P(Eq(X, 0)).round(2)
1655
+ 0.03
1656
+ >>> P(Eq(X, 2)).round(2)
1657
+ 0.44
1658
+ >>> P(Eq(X, 4)).round(2)
1659
+ 0
1660
+ >>> P(Gt(X, 1)).round(2)
1661
+ 0.78
1662
+ >>> P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2)
1663
+ 0.04
1664
+ >>> B.joint_distribution(B[1], B[2])
1665
+ JointDistributionHandmade(Lambda((B[1], B[2]), Piecewise((0.7, Eq(B[1], 1)),
1666
+ (0.3, Eq(B[1], 0)), (0, True))*Piecewise((0.7, Eq(B[2], 1)), (0.3, Eq(B[2], 0)),
1667
+ (0, True))))
1668
+ >>> E(2*B[1] + B[2]).round(2)
1669
+ 2.10
1670
+ >>> P(B[1] < 1).round(2)
1671
+ 0.30
1672
+
1673
+ References
1674
+ ==========
1675
+
1676
+ .. [1] https://en.wikipedia.org/wiki/Bernoulli_process
1677
+ .. [2] https://mathcs.clarku.edu/~djoyce/ma217/bernoulli.pdf
1678
+
1679
+ """
1680
+
1681
+ index_set = S.Naturals0
1682
+
1683
+ def __new__(cls, sym, p, success=1, failure=0):
1684
+ _value_check(p >= 0 and p <= 1, 'Value of p must be between 0 and 1.')
1685
+ sym = _symbol_converter(sym)
1686
+ p = _sympify(p)
1687
+ success = _sym_sympify(success)
1688
+ failure = _sym_sympify(failure)
1689
+ return Basic.__new__(cls, sym, p, success, failure)
1690
+
1691
+ @property
1692
+ def symbol(self):
1693
+ return self.args[0]
1694
+
1695
+ @property
1696
+ def p(self):
1697
+ return self.args[1]
1698
+
1699
+ @property
1700
+ def success(self):
1701
+ return self.args[2]
1702
+
1703
+ @property
1704
+ def failure(self):
1705
+ return self.args[3]
1706
+
1707
+ @property
1708
+ def state_space(self):
1709
+ return _set_converter([self.success, self.failure])
1710
+
1711
+ def distribution(self, key=None):
1712
+ if key is None:
1713
+ self._deprecation_warn_distribution()
1714
+ return BernoulliDistribution(self.p)
1715
+ return BernoulliDistribution(self.p, self.success, self.failure)
1716
+
1717
+ def simple_rv(self, rv):
1718
+ return Bernoulli(rv.name, p=self.p,
1719
+ succ=self.success, fail=self.failure)
1720
+
1721
+ def expectation(self, expr, condition=None, evaluate=True, **kwargs):
1722
+ """
1723
+ Computes expectation.
1724
+
1725
+ Parameters
1726
+ ==========
1727
+
1728
+ expr : RandomIndexedSymbol, Relational, Logic
1729
+ Condition for which expectation has to be computed. Must
1730
+ contain a RandomIndexedSymbol of the process.
1731
+ condition : Relational, Logic
1732
+ The given conditions under which computations should be done.
1733
+
1734
+ Returns
1735
+ =======
1736
+
1737
+ Expectation of the RandomIndexedSymbol.
1738
+
1739
+ """
1740
+
1741
+ return _SubstituteRV._expectation(expr, condition, evaluate, **kwargs)
1742
+
1743
+ def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
1744
+ """
1745
+ Computes probability.
1746
+
1747
+ Parameters
1748
+ ==========
1749
+
1750
+ condition : Relational
1751
+ Condition for which probability has to be computed. Must
1752
+ contain a RandomIndexedSymbol of the process.
1753
+ given_condition : Relational, Logic
1754
+ The given conditions under which computations should be done.
1755
+
1756
+ Returns
1757
+ =======
1758
+
1759
+ Probability of the condition.
1760
+
1761
+ """
1762
+
1763
+ return _SubstituteRV._probability(condition, given_condition, evaluate, **kwargs)
1764
+
1765
+ def density(self, x):
1766
+ return Piecewise((self.p, Eq(x, self.success)),
1767
+ (1 - self.p, Eq(x, self.failure)),
1768
+ (S.Zero, True))
1769
+
1770
+ class _SubstituteRV:
1771
+ """
1772
+ Internal class to handle the queries of expectation and probability
1773
+ by substitution.
1774
+ """
1775
+
1776
+ @staticmethod
1777
+ def _rvindexed_subs(expr, condition=None):
1778
+ """
1779
+ Substitutes the RandomIndexedSymbol with the RandomSymbol with
1780
+ same name, distribution and probability as RandomIndexedSymbol.
1781
+
1782
+ Parameters
1783
+ ==========
1784
+
1785
+ expr: RandomIndexedSymbol, Relational, Logic
1786
+ Condition for which expectation has to be computed. Must
1787
+ contain a RandomIndexedSymbol of the process.
1788
+ condition: Relational, Logic
1789
+ The given conditions under which computations should be done.
1790
+
1791
+ """
1792
+
1793
+ rvs_expr = random_symbols(expr)
1794
+ if len(rvs_expr) != 0:
1795
+ swapdict_expr = {}
1796
+ for rv in rvs_expr:
1797
+ if isinstance(rv, RandomIndexedSymbol):
1798
+ newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv
1799
+ swapdict_expr[rv] = newrv
1800
+ expr = expr.subs(swapdict_expr)
1801
+ rvs_cond = random_symbols(condition)
1802
+ if len(rvs_cond)!=0:
1803
+ swapdict_cond = {}
1804
+ for rv in rvs_cond:
1805
+ if isinstance(rv, RandomIndexedSymbol):
1806
+ newrv = rv.pspace.process.simple_rv(rv)
1807
+ swapdict_cond[rv] = newrv
1808
+ condition = condition.subs(swapdict_cond)
1809
+ return expr, condition
1810
+
1811
+ @classmethod
1812
+ def _expectation(self, expr, condition=None, evaluate=True, **kwargs):
1813
+ """
1814
+ Internal method for computing expectation of indexed RV.
1815
+
1816
+ Parameters
1817
+ ==========
1818
+
1819
+ expr: RandomIndexedSymbol, Relational, Logic
1820
+ Condition for which expectation has to be computed. Must
1821
+ contain a RandomIndexedSymbol of the process.
1822
+ condition: Relational, Logic
1823
+ The given conditions under which computations should be done.
1824
+
1825
+ Returns
1826
+ =======
1827
+
1828
+ Expectation of the RandomIndexedSymbol.
1829
+
1830
+ """
1831
+ new_expr, new_condition = self._rvindexed_subs(expr, condition)
1832
+
1833
+ if not is_random(new_expr):
1834
+ return new_expr
1835
+ new_pspace = pspace(new_expr)
1836
+ if new_condition is not None:
1837
+ new_expr = given(new_expr, new_condition)
1838
+ if new_expr.is_Add: # As E is Linear
1839
+ return Add(*[new_pspace.compute_expectation(
1840
+ expr=arg, evaluate=evaluate, **kwargs)
1841
+ for arg in new_expr.args])
1842
+ return new_pspace.compute_expectation(
1843
+ new_expr, evaluate=evaluate, **kwargs)
1844
+
1845
+ @classmethod
1846
+ def _probability(self, condition, given_condition=None, evaluate=True, **kwargs):
1847
+ """
1848
+ Internal method for computing probability of indexed RV
1849
+
1850
+ Parameters
1851
+ ==========
1852
+
1853
+ condition: Relational
1854
+ Condition for which probability has to be computed. Must
1855
+ contain a RandomIndexedSymbol of the process.
1856
+ given_condition: Relational/And
1857
+ The given conditions under which computations should be done.
1858
+
1859
+ Returns
1860
+ =======
1861
+
1862
+ Probability of the condition.
1863
+
1864
+ """
1865
+ new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition)
1866
+
1867
+ if isinstance(new_givencondition, RandomSymbol):
1868
+ condrv = random_symbols(new_condition)
1869
+ if len(condrv) == 1 and condrv[0] == new_givencondition:
1870
+ return BernoulliDistribution(self._probability(new_condition), 0, 1)
1871
+
1872
+ if any(dependent(rv, new_givencondition) for rv in condrv):
1873
+ return Probability(new_condition, new_givencondition)
1874
+ else:
1875
+ return self._probability(new_condition)
1876
+
1877
+ if new_givencondition is not None and \
1878
+ not isinstance(new_givencondition, (Relational, Boolean)):
1879
+ raise ValueError("%s is not a relational or combination of relationals"
1880
+ % (new_givencondition))
1881
+ if new_givencondition == False or new_condition == False:
1882
+ return S.Zero
1883
+ if new_condition == True:
1884
+ return S.One
1885
+ if not isinstance(new_condition, (Relational, Boolean)):
1886
+ raise ValueError("%s is not a relational or combination of relationals"
1887
+ % (new_condition))
1888
+
1889
+ if new_givencondition is not None: # If there is a condition
1890
+ # Recompute on new conditional expr
1891
+ return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs)
1892
+ result = pspace(new_condition).probability(new_condition, **kwargs)
1893
+ if evaluate and hasattr(result, 'doit'):
1894
+ return result.doit()
1895
+ else:
1896
+ return result
1897
+
1898
+ def get_timerv_swaps(expr, condition):
1899
+ """
1900
+ Finds the appropriate interval for each time stamp in expr by parsing
1901
+ the given condition and returns intervals for each timestamp and
1902
+ dictionary that maps variable time-stamped Random Indexed Symbol to its
1903
+ corresponding Random Indexed variable with fixed time stamp.
1904
+
1905
+ Parameters
1906
+ ==========
1907
+
1908
+ expr: SymPy Expression
1909
+ Expression containing Random Indexed Symbols with variable time stamps
1910
+ condition: Relational/Boolean Expression
1911
+ Expression containing time bounds of variable time stamps in expr
1912
+
1913
+ Examples
1914
+ ========
1915
+
1916
+ >>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess
1917
+ >>> from sympy import symbols, Contains, Interval
1918
+ >>> x, t, d = symbols('x t d', positive=True)
1919
+ >>> X = PoissonProcess("X", 3)
1920
+ >>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1)))
1921
+ ([Interval.Lopen(0, 1)], {X(t): X(1)})
1922
+ >>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1))
1923
+ ... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP
1924
+ ([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)})
1925
+
1926
+ Returns
1927
+ =======
1928
+
1929
+ intervals: list
1930
+ List of Intervals/FiniteSet on which each time stamp is defined
1931
+ rv_swap: dict
1932
+ Dictionary mapping variable time Random Indexed Symbol to constant time
1933
+ Random Indexed Variable
1934
+
1935
+ """
1936
+
1937
+ if not isinstance(condition, (Relational, Boolean)):
1938
+ raise ValueError("%s is not a relational or combination of relationals"
1939
+ % (condition))
1940
+ expr_syms = list(expr.atoms(RandomIndexedSymbol))
1941
+ if isinstance(condition, (And, Or)):
1942
+ given_cond_args = condition.args
1943
+ else: # single condition
1944
+ given_cond_args = (condition, )
1945
+ rv_swap = {}
1946
+ intervals = []
1947
+ for expr_sym in expr_syms:
1948
+ for arg in given_cond_args:
1949
+ if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol):
1950
+ intv = _set_converter(arg.args[1])
1951
+ diff_key = intv._sup - intv._inf
1952
+ if diff_key == oo:
1953
+ raise ValueError("%s should have finite bounds" % str(expr_sym.name))
1954
+ elif diff_key == S.Zero: # has singleton set
1955
+ diff_key = intv._sup
1956
+ rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key})
1957
+ intervals.append(intv)
1958
+ return intervals, rv_swap
1959
+
1960
+
1961
+ class CountingProcess(ContinuousTimeStochasticProcess):
1962
+ """
1963
+ This class handles the common methods of the Counting Processes
1964
+ such as Poisson, Wiener and Gamma Processes
1965
+ """
1966
+ index_set = _set_converter(Interval(0, oo))
1967
+
1968
+ @property
1969
+ def symbol(self):
1970
+ return self.args[0]
1971
+
1972
+ def expectation(self, expr, condition=None, evaluate=True, **kwargs):
1973
+ """
1974
+ Computes expectation
1975
+
1976
+ Parameters
1977
+ ==========
1978
+
1979
+ expr: RandomIndexedSymbol, Relational, Logic
1980
+ Condition for which expectation has to be computed. Must
1981
+ contain a RandomIndexedSymbol of the process.
1982
+ condition: Relational, Boolean
1983
+ The given conditions under which computations should be done, i.e,
1984
+ the intervals on which each variable time stamp in expr is defined
1985
+
1986
+ Returns
1987
+ =======
1988
+
1989
+ Expectation of the given expr
1990
+
1991
+ """
1992
+ if condition is not None:
1993
+ intervals, rv_swap = get_timerv_swaps(expr, condition)
1994
+ # they are independent when they have non-overlapping intervals
1995
+ if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
1996
+ for intv_comb in itertools.combinations(intervals, 2)):
1997
+ if expr.is_Add:
1998
+ return Add.fromiter(self.expectation(arg, condition)
1999
+ for arg in expr.args)
2000
+ expr = expr.subs(rv_swap)
2001
+ else:
2002
+ return Expectation(expr, condition)
2003
+
2004
+ return _SubstituteRV._expectation(expr, evaluate=evaluate, **kwargs)
2005
+
2006
+ def _solve_argwith_tworvs(self, arg):
2007
+ if arg.args[0].key >= arg.args[1].key or isinstance(arg, Eq):
2008
+ diff_key = abs(arg.args[0].key - arg.args[1].key)
2009
+ rv = arg.args[0]
2010
+ arg = arg.__class__(rv.pspace.process(diff_key), 0)
2011
+ else:
2012
+ diff_key = arg.args[1].key - arg.args[0].key
2013
+ rv = arg.args[1]
2014
+ arg = arg.__class__(rv.pspace.process(diff_key), 0)
2015
+ return arg
2016
+
2017
+ def _solve_numerical(self, condition, given_condition=None):
2018
+ if isinstance(condition, And):
2019
+ args_list = list(condition.args)
2020
+ else:
2021
+ args_list = [condition]
2022
+ if given_condition is not None:
2023
+ if isinstance(given_condition, And):
2024
+ args_list.extend(list(given_condition.args))
2025
+ else:
2026
+ args_list.extend([given_condition])
2027
+ # sort the args based on timestamp to get the independent increments in
2028
+ # each segment using all the condition args as well as given_condition args
2029
+ args_list = sorted(args_list, key=lambda x: x.args[0].key)
2030
+ result = []
2031
+ cond_args = list(condition.args) if isinstance(condition, And) else [condition]
2032
+ if args_list[0] in cond_args and not (is_random(args_list[0].args[0])
2033
+ and is_random(args_list[0].args[1])):
2034
+ result.append(_SubstituteRV._probability(args_list[0]))
2035
+
2036
+ if is_random(args_list[0].args[0]) and is_random(args_list[0].args[1]):
2037
+ arg = self._solve_argwith_tworvs(args_list[0])
2038
+ result.append(_SubstituteRV._probability(arg))
2039
+
2040
+ for i in range(len(args_list) - 1):
2041
+ curr, nex = args_list[i], args_list[i + 1]
2042
+ diff_key = nex.args[0].key - curr.args[0].key
2043
+ working_set = curr.args[0].pspace.process.state_space
2044
+ if curr.args[1] > nex.args[1]: #impossible condition so return 0
2045
+ result.append(0)
2046
+ break
2047
+ if isinstance(curr, Eq):
2048
+ working_set = Intersection(working_set, Interval.Lopen(curr.args[1], oo))
2049
+ else:
2050
+ working_set = Intersection(working_set, curr.as_set())
2051
+ if isinstance(nex, Eq):
2052
+ working_set = Intersection(working_set, Interval(-oo, nex.args[1]))
2053
+ else:
2054
+ working_set = Intersection(working_set, nex.as_set())
2055
+ if working_set == EmptySet:
2056
+ rv = Eq(curr.args[0].pspace.process(diff_key), 0)
2057
+ result.append(_SubstituteRV._probability(rv))
2058
+ else:
2059
+ if working_set.is_finite_set:
2060
+ if isinstance(curr, Eq) and isinstance(nex, Eq):
2061
+ rv = Eq(curr.args[0].pspace.process(diff_key), len(working_set))
2062
+ result.append(_SubstituteRV._probability(rv))
2063
+ elif isinstance(curr, Eq) ^ isinstance(nex, Eq):
2064
+ result.append(Add.fromiter(_SubstituteRV._probability(Eq(
2065
+ curr.args[0].pspace.process(diff_key), x))
2066
+ for x in range(len(working_set))))
2067
+ else:
2068
+ n = len(working_set)
2069
+ result.append(Add.fromiter((n - x)*_SubstituteRV._probability(Eq(
2070
+ curr.args[0].pspace.process(diff_key), x)) for x in range(n)))
2071
+ else:
2072
+ result.append(_SubstituteRV._probability(
2073
+ curr.args[0].pspace.process(diff_key) <= working_set._sup - working_set._inf))
2074
+ return Mul.fromiter(result)
2075
+
2076
+
2077
+ def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
2078
+ """
2079
+ Computes probability.
2080
+
2081
+ Parameters
2082
+ ==========
2083
+
2084
+ condition: Relational
2085
+ Condition for which probability has to be computed. Must
2086
+ contain a RandomIndexedSymbol of the process.
2087
+ given_condition: Relational, Boolean
2088
+ The given conditions under which computations should be done, i.e,
2089
+ the intervals on which each variable time stamp in expr is defined
2090
+
2091
+ Returns
2092
+ =======
2093
+
2094
+ Probability of the condition
2095
+
2096
+ """
2097
+ check_numeric = True
2098
+ if isinstance(condition, (And, Or)):
2099
+ cond_args = condition.args
2100
+ else:
2101
+ cond_args = (condition, )
2102
+ # check that condition args are numeric or not
2103
+ if not all(arg.args[0].key.is_number for arg in cond_args):
2104
+ check_numeric = False
2105
+ if given_condition is not None:
2106
+ check_given_numeric = True
2107
+ if isinstance(given_condition, (And, Or)):
2108
+ given_cond_args = given_condition.args
2109
+ else:
2110
+ given_cond_args = (given_condition, )
2111
+ # check that given condition args are numeric or not
2112
+ if given_condition.has(Contains):
2113
+ check_given_numeric = False
2114
+ # Handle numerical queries
2115
+ if check_numeric and check_given_numeric:
2116
+ res = []
2117
+ if isinstance(condition, Or):
2118
+ res.append(Add.fromiter(self._solve_numerical(arg, given_condition)
2119
+ for arg in condition.args))
2120
+ if isinstance(given_condition, Or):
2121
+ res.append(Add.fromiter(self._solve_numerical(condition, arg)
2122
+ for arg in given_condition.args))
2123
+ if res:
2124
+ return Add.fromiter(res)
2125
+ return self._solve_numerical(condition, given_condition)
2126
+
2127
+ # No numeric queries, go by Contains?... then check that all the
2128
+ # given condition are in form of `Contains`
2129
+ if not all(arg.has(Contains) for arg in given_cond_args):
2130
+ raise ValueError("If given condition is passed with `Contains`, then "
2131
+ "please pass the evaluated condition with its corresponding information "
2132
+ "in terms of intervals of each time stamp to be passed in given condition.")
2133
+
2134
+ intervals, rv_swap = get_timerv_swaps(condition, given_condition)
2135
+ # they are independent when they have non-overlapping intervals
2136
+ if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
2137
+ for intv_comb in itertools.combinations(intervals, 2)):
2138
+ if isinstance(condition, And):
2139
+ return Mul.fromiter(self.probability(arg, given_condition)
2140
+ for arg in condition.args)
2141
+ elif isinstance(condition, Or):
2142
+ return Add.fromiter(self.probability(arg, given_condition)
2143
+ for arg in condition.args)
2144
+ condition = condition.subs(rv_swap)
2145
+ else:
2146
+ return Probability(condition, given_condition)
2147
+ if check_numeric:
2148
+ return self._solve_numerical(condition)
2149
+ return _SubstituteRV._probability(condition, evaluate=evaluate, **kwargs)
2150
+
2151
+ class PoissonProcess(CountingProcess):
2152
+ """
2153
+ The Poisson process is a counting process. It is usually used in scenarios
2154
+ where we are counting the occurrences of certain events that appear
2155
+ to happen at a certain rate, but completely at random.
2156
+
2157
+ Parameters
2158
+ ==========
2159
+
2160
+ sym : Symbol/str
2161
+ lamda : Positive number
2162
+ Rate of the process, ``lambda > 0``
2163
+
2164
+ Examples
2165
+ ========
2166
+
2167
+ >>> from sympy.stats import PoissonProcess, P, E
2168
+ >>> from sympy import symbols, Eq, Ne, Contains, Interval
2169
+ >>> X = PoissonProcess("X", lamda=3)
2170
+ >>> X.state_space
2171
+ Naturals0
2172
+ >>> X.lamda
2173
+ 3
2174
+ >>> t1, t2 = symbols('t1 t2', positive=True)
2175
+ >>> P(X(t1) < 4)
2176
+ (9*t1**3/2 + 9*t1**2/2 + 3*t1 + 1)*exp(-3*t1)
2177
+ >>> P(Eq(X(t1), 2) | Ne(X(t1), 4), Contains(t1, Interval.Ropen(2, 4)))
2178
+ 1 - 36*exp(-6)
2179
+ >>> P(Eq(X(t1), 2) & Eq(X(t2), 3), Contains(t1, Interval.Lopen(0, 2))
2180
+ ... & Contains(t2, Interval.Lopen(2, 4)))
2181
+ 648*exp(-12)
2182
+ >>> E(X(t1))
2183
+ 3*t1
2184
+ >>> E(X(t1)**2 + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
2185
+ ... & Contains(t2, Interval.Lopen(1, 2)))
2186
+ 18
2187
+ >>> P(X(3) < 1, Eq(X(1), 0))
2188
+ exp(-6)
2189
+ >>> P(Eq(X(4), 3), Eq(X(2), 3))
2190
+ exp(-6)
2191
+ >>> P(X(2) <= 3, X(1) > 1)
2192
+ 5*exp(-3)
2193
+
2194
+ Merging two Poisson Processes
2195
+
2196
+ >>> Y = PoissonProcess("Y", lamda=4)
2197
+ >>> Z = X + Y
2198
+ >>> Z.lamda
2199
+ 7
2200
+
2201
+ Splitting a Poisson Process into two independent Poisson Processes
2202
+
2203
+ >>> N, M = Z.split(l1=2, l2=5)
2204
+ >>> N.lamda, M.lamda
2205
+ (2, 5)
2206
+
2207
+ References
2208
+ ==========
2209
+
2210
+ .. [1] https://www.probabilitycourse.com/chapter11/11_0_0_intro.php
2211
+ .. [2] https://en.wikipedia.org/wiki/Poisson_point_process
2212
+
2213
+ """
2214
+
2215
+ def __new__(cls, sym, lamda):
2216
+ _value_check(lamda > 0, 'lamda should be a positive number.')
2217
+ sym = _symbol_converter(sym)
2218
+ lamda = _sympify(lamda)
2219
+ return Basic.__new__(cls, sym, lamda)
2220
+
2221
+ @property
2222
+ def lamda(self):
2223
+ return self.args[1]
2224
+
2225
+ @property
2226
+ def state_space(self):
2227
+ return S.Naturals0
2228
+
2229
+ def distribution(self, key):
2230
+ if isinstance(key, RandomIndexedSymbol):
2231
+ self._deprecation_warn_distribution()
2232
+ return PoissonDistribution(self.lamda*key.key)
2233
+ return PoissonDistribution(self.lamda*key)
2234
+
2235
+ def density(self, x):
2236
+ return (self.lamda*x.key)**x / factorial(x) * exp(-(self.lamda*x.key))
2237
+
2238
+ def simple_rv(self, rv):
2239
+ return Poisson(rv.name, lamda=self.lamda*rv.key)
2240
+
2241
+ def __add__(self, other):
2242
+ if not isinstance(other, PoissonProcess):
2243
+ raise ValueError("Only instances of Poisson Process can be merged")
2244
+ return PoissonProcess(Dummy(self.symbol.name + other.symbol.name),
2245
+ self.lamda + other.lamda)
2246
+
2247
+ def split(self, l1, l2):
2248
+ if _sympify(l1 + l2) != self.lamda:
2249
+ raise ValueError("Sum of l1 and l2 should be %s" % str(self.lamda))
2250
+ return PoissonProcess(Dummy("l1"), l1), PoissonProcess(Dummy("l2"), l2)
2251
+
2252
+ class WienerProcess(CountingProcess):
2253
+ """
2254
+ The Wiener process is a real valued continuous-time stochastic process.
2255
+ In physics it is used to study Brownian motion and it is often also called
2256
+ Brownian motion due to its historical connection with physical process of the
2257
+ same name originally observed by Scottish botanist Robert Brown.
2258
+
2259
+ Parameters
2260
+ ==========
2261
+
2262
+ sym : Symbol/str
2263
+
2264
+ Examples
2265
+ ========
2266
+
2267
+ >>> from sympy.stats import WienerProcess, P, E
2268
+ >>> from sympy import symbols, Contains, Interval
2269
+ >>> X = WienerProcess("X")
2270
+ >>> X.state_space
2271
+ Reals
2272
+ >>> t1, t2 = symbols('t1 t2', positive=True)
2273
+ >>> P(X(t1) < 7).simplify()
2274
+ erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2
2275
+ >>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify()
2276
+ -erf(1)/2 + erf(2)/2 + 1
2277
+ >>> E(X(t1))
2278
+ 0
2279
+ >>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
2280
+ ... & Contains(t2, Interval.Lopen(1, 2)))
2281
+ 0
2282
+
2283
+ References
2284
+ ==========
2285
+
2286
+ .. [1] https://www.probabilitycourse.com/chapter11/11_4_0_brownian_motion_wiener_process.php
2287
+ .. [2] https://en.wikipedia.org/wiki/Wiener_process
2288
+
2289
+ """
2290
+ def __new__(cls, sym):
2291
+ sym = _symbol_converter(sym)
2292
+ return Basic.__new__(cls, sym)
2293
+
2294
+ @property
2295
+ def state_space(self):
2296
+ return S.Reals
2297
+
2298
+ def distribution(self, key):
2299
+ if isinstance(key, RandomIndexedSymbol):
2300
+ self._deprecation_warn_distribution()
2301
+ return NormalDistribution(0, sqrt(key.key))
2302
+ return NormalDistribution(0, sqrt(key))
2303
+
2304
+ def density(self, x):
2305
+ return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key))
2306
+
2307
+ def simple_rv(self, rv):
2308
+ return Normal(rv.name, 0, sqrt(rv.key))
2309
+
2310
+
2311
+ class GammaProcess(CountingProcess):
2312
+ r"""
2313
+ A Gamma process is a random process with independent gamma distributed
2314
+ increments. It is a pure-jump increasing Levy process.
2315
+
2316
+ Parameters
2317
+ ==========
2318
+
2319
+ sym : Symbol/str
2320
+ lamda : Positive number
2321
+ Jump size of the process, ``lamda > 0``
2322
+ gamma : Positive number
2323
+ Rate of jump arrivals, `\gamma > 0`
2324
+
2325
+ Examples
2326
+ ========
2327
+
2328
+ >>> from sympy.stats import GammaProcess, E, P, variance
2329
+ >>> from sympy import symbols, Contains, Interval, Not
2330
+ >>> t, d, x, l, g = symbols('t d x l g', positive=True)
2331
+ >>> X = GammaProcess("X", l, g)
2332
+ >>> E(X(t))
2333
+ g*t/l
2334
+ >>> variance(X(t)).simplify()
2335
+ g*t/l**2
2336
+ >>> X = GammaProcess('X', 1, 2)
2337
+ >>> P(X(t) < 1).simplify()
2338
+ lowergamma(2*t, 1)/gamma(2*t)
2339
+ >>> P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) &
2340
+ ... Contains(d, Interval.Lopen(7, 8))).simplify()
2341
+ -4*exp(-3) + 472*exp(-8)/3 + 1
2342
+ >>> E(X(2) + x*E(X(5)))
2343
+ 10*x + 4
2344
+
2345
+ References
2346
+ ==========
2347
+
2348
+ .. [1] https://en.wikipedia.org/wiki/Gamma_process
2349
+
2350
+ """
2351
+ def __new__(cls, sym, lamda, gamma):
2352
+ _value_check(lamda > 0, 'lamda should be a positive number')
2353
+ _value_check(gamma > 0, 'gamma should be a positive number')
2354
+ sym = _symbol_converter(sym)
2355
+ gamma = _sympify(gamma)
2356
+ lamda = _sympify(lamda)
2357
+ return Basic.__new__(cls, sym, lamda, gamma)
2358
+
2359
+ @property
2360
+ def lamda(self):
2361
+ return self.args[1]
2362
+
2363
+ @property
2364
+ def gamma(self):
2365
+ return self.args[2]
2366
+
2367
+ @property
2368
+ def state_space(self):
2369
+ return _set_converter(Interval(0, oo))
2370
+
2371
+ def distribution(self, key):
2372
+ if isinstance(key, RandomIndexedSymbol):
2373
+ self._deprecation_warn_distribution()
2374
+ return GammaDistribution(self.gamma*key.key, 1/self.lamda)
2375
+ return GammaDistribution(self.gamma*key, 1/self.lamda)
2376
+
2377
+ def density(self, x):
2378
+ k = self.gamma*x.key
2379
+ theta = 1/self.lamda
2380
+ return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k)
2381
+
2382
+ def simple_rv(self, rv):
2383
+ return Gamma(rv.name, self.gamma*rv.key, 1/self.lamda)
mplug_owl2/lib/python3.10/site-packages/sympy/stats/symbolic_multivariate_probability.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+
3
+ from sympy.core.add import Add
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.function import expand as _expand
6
+ from sympy.core.mul import Mul
7
+ from sympy.core.singleton import S
8
+ from sympy.matrices.exceptions import ShapeError
9
+ from sympy.matrices.expressions.matexpr import MatrixExpr
10
+ from sympy.matrices.expressions.matmul import MatMul
11
+ from sympy.matrices.expressions.special import ZeroMatrix
12
+ from sympy.stats.rv import RandomSymbol, is_random
13
+ from sympy.core.sympify import _sympify
14
+ from sympy.stats.symbolic_probability import Variance, Covariance, Expectation
15
+
16
+
17
+ class ExpectationMatrix(Expectation, MatrixExpr):
18
+ """
19
+ Expectation of a random matrix expression.
20
+
21
+ Examples
22
+ ========
23
+
24
+ >>> from sympy.stats import ExpectationMatrix, Normal
25
+ >>> from sympy.stats.rv import RandomMatrixSymbol
26
+ >>> from sympy import symbols, MatrixSymbol, Matrix
27
+ >>> k = symbols("k")
28
+ >>> A, B = MatrixSymbol("A", k, k), MatrixSymbol("B", k, k)
29
+ >>> X, Y = RandomMatrixSymbol("X", k, 1), RandomMatrixSymbol("Y", k, 1)
30
+ >>> ExpectationMatrix(X)
31
+ ExpectationMatrix(X)
32
+ >>> ExpectationMatrix(A*X).shape
33
+ (k, 1)
34
+
35
+ To expand the expectation in its expression, use ``expand()``:
36
+
37
+ >>> ExpectationMatrix(A*X + B*Y).expand()
38
+ A*ExpectationMatrix(X) + B*ExpectationMatrix(Y)
39
+ >>> ExpectationMatrix((X + Y)*(X - Y).T).expand()
40
+ ExpectationMatrix(X*X.T) - ExpectationMatrix(X*Y.T) + ExpectationMatrix(Y*X.T) - ExpectationMatrix(Y*Y.T)
41
+
42
+ To evaluate the ``ExpectationMatrix``, use ``doit()``:
43
+
44
+ >>> N11, N12 = Normal('N11', 11, 1), Normal('N12', 12, 1)
45
+ >>> N21, N22 = Normal('N21', 21, 1), Normal('N22', 22, 1)
46
+ >>> M11, M12 = Normal('M11', 1, 1), Normal('M12', 2, 1)
47
+ >>> M21, M22 = Normal('M21', 3, 1), Normal('M22', 4, 1)
48
+ >>> x1 = Matrix([[N11, N12], [N21, N22]])
49
+ >>> x2 = Matrix([[M11, M12], [M21, M22]])
50
+ >>> ExpectationMatrix(x1 + x2).doit()
51
+ Matrix([
52
+ [12, 14],
53
+ [24, 26]])
54
+
55
+ """
56
+ def __new__(cls, expr, condition=None):
57
+ expr = _sympify(expr)
58
+ if condition is None:
59
+ if not is_random(expr):
60
+ return expr
61
+ obj = Expr.__new__(cls, expr)
62
+ else:
63
+ condition = _sympify(condition)
64
+ obj = Expr.__new__(cls, expr, condition)
65
+
66
+ obj._shape = expr.shape
67
+ obj._condition = condition
68
+ return obj
69
+
70
+ @property
71
+ def shape(self):
72
+ return self._shape
73
+
74
+ def expand(self, **hints):
75
+ expr = self.args[0]
76
+ condition = self._condition
77
+ if not is_random(expr):
78
+ return expr
79
+
80
+ if isinstance(expr, Add):
81
+ return Add.fromiter(Expectation(a, condition=condition).expand()
82
+ for a in expr.args)
83
+
84
+ expand_expr = _expand(expr)
85
+ if isinstance(expand_expr, Add):
86
+ return Add.fromiter(Expectation(a, condition=condition).expand()
87
+ for a in expand_expr.args)
88
+
89
+ elif isinstance(expr, (Mul, MatMul)):
90
+ rv = []
91
+ nonrv = []
92
+ postnon = []
93
+
94
+ for a in expr.args:
95
+ if is_random(a):
96
+ if rv:
97
+ rv.extend(postnon)
98
+ else:
99
+ nonrv.extend(postnon)
100
+ postnon = []
101
+ rv.append(a)
102
+ elif a.is_Matrix:
103
+ postnon.append(a)
104
+ else:
105
+ nonrv.append(a)
106
+
107
+ # In order to avoid infinite-looping (MatMul may call .doit() again),
108
+ # do not rebuild
109
+ if len(nonrv) == 0:
110
+ return self
111
+ return Mul.fromiter(nonrv)*Expectation(Mul.fromiter(rv),
112
+ condition=condition)*Mul.fromiter(postnon)
113
+
114
+ return self
115
+
116
+ class VarianceMatrix(Variance, MatrixExpr):
117
+ """
118
+ Variance of a random matrix probability expression. Also known as
119
+ Covariance matrix, auto-covariance matrix, dispersion matrix,
120
+ or variance-covariance matrix.
121
+
122
+ Examples
123
+ ========
124
+
125
+ >>> from sympy.stats import VarianceMatrix
126
+ >>> from sympy.stats.rv import RandomMatrixSymbol
127
+ >>> from sympy import symbols, MatrixSymbol
128
+ >>> k = symbols("k")
129
+ >>> A, B = MatrixSymbol("A", k, k), MatrixSymbol("B", k, k)
130
+ >>> X, Y = RandomMatrixSymbol("X", k, 1), RandomMatrixSymbol("Y", k, 1)
131
+ >>> VarianceMatrix(X)
132
+ VarianceMatrix(X)
133
+ >>> VarianceMatrix(X).shape
134
+ (k, k)
135
+
136
+ To expand the variance in its expression, use ``expand()``:
137
+
138
+ >>> VarianceMatrix(A*X).expand()
139
+ A*VarianceMatrix(X)*A.T
140
+ >>> VarianceMatrix(A*X + B*Y).expand()
141
+ 2*A*CrossCovarianceMatrix(X, Y)*B.T + A*VarianceMatrix(X)*A.T + B*VarianceMatrix(Y)*B.T
142
+ """
143
+ def __new__(cls, arg, condition=None):
144
+ arg = _sympify(arg)
145
+
146
+ if 1 not in arg.shape:
147
+ raise ShapeError("Expression is not a vector")
148
+
149
+ shape = (arg.shape[0], arg.shape[0]) if arg.shape[1] == 1 else (arg.shape[1], arg.shape[1])
150
+
151
+ if condition:
152
+ obj = Expr.__new__(cls, arg, condition)
153
+ else:
154
+ obj = Expr.__new__(cls, arg)
155
+
156
+ obj._shape = shape
157
+ obj._condition = condition
158
+ return obj
159
+
160
+ @property
161
+ def shape(self):
162
+ return self._shape
163
+
164
+ def expand(self, **hints):
165
+ arg = self.args[0]
166
+ condition = self._condition
167
+
168
+ if not is_random(arg):
169
+ return ZeroMatrix(*self.shape)
170
+
171
+ if isinstance(arg, RandomSymbol):
172
+ return self
173
+ elif isinstance(arg, Add):
174
+ rv = []
175
+ for a in arg.args:
176
+ if is_random(a):
177
+ rv.append(a)
178
+ variances = Add(*(Variance(xv, condition).expand() for xv in rv))
179
+ map_to_covar = lambda x: 2*Covariance(*x, condition=condition).expand()
180
+ covariances = Add(*map(map_to_covar, itertools.combinations(rv, 2)))
181
+ return variances + covariances
182
+ elif isinstance(arg, (Mul, MatMul)):
183
+ nonrv = []
184
+ rv = []
185
+ for a in arg.args:
186
+ if is_random(a):
187
+ rv.append(a)
188
+ else:
189
+ nonrv.append(a)
190
+ if len(rv) == 0:
191
+ return ZeroMatrix(*self.shape)
192
+ # Avoid possible infinite loops with MatMul:
193
+ if len(nonrv) == 0:
194
+ return self
195
+ # Variance of many multiple matrix products is not implemented:
196
+ if len(rv) > 1:
197
+ return self
198
+ return Mul.fromiter(nonrv)*Variance(Mul.fromiter(rv),
199
+ condition)*(Mul.fromiter(nonrv)).transpose()
200
+
201
+ # this expression contains a RandomSymbol somehow:
202
+ return self
203
+
204
+ class CrossCovarianceMatrix(Covariance, MatrixExpr):
205
+ """
206
+ Covariance of a random matrix probability expression.
207
+
208
+ Examples
209
+ ========
210
+
211
+ >>> from sympy.stats import CrossCovarianceMatrix
212
+ >>> from sympy.stats.rv import RandomMatrixSymbol
213
+ >>> from sympy import symbols, MatrixSymbol
214
+ >>> k = symbols("k")
215
+ >>> A, B = MatrixSymbol("A", k, k), MatrixSymbol("B", k, k)
216
+ >>> C, D = MatrixSymbol("C", k, k), MatrixSymbol("D", k, k)
217
+ >>> X, Y = RandomMatrixSymbol("X", k, 1), RandomMatrixSymbol("Y", k, 1)
218
+ >>> Z, W = RandomMatrixSymbol("Z", k, 1), RandomMatrixSymbol("W", k, 1)
219
+ >>> CrossCovarianceMatrix(X, Y)
220
+ CrossCovarianceMatrix(X, Y)
221
+ >>> CrossCovarianceMatrix(X, Y).shape
222
+ (k, k)
223
+
224
+ To expand the covariance in its expression, use ``expand()``:
225
+
226
+ >>> CrossCovarianceMatrix(X + Y, Z).expand()
227
+ CrossCovarianceMatrix(X, Z) + CrossCovarianceMatrix(Y, Z)
228
+ >>> CrossCovarianceMatrix(A*X, Y).expand()
229
+ A*CrossCovarianceMatrix(X, Y)
230
+ >>> CrossCovarianceMatrix(A*X, B.T*Y).expand()
231
+ A*CrossCovarianceMatrix(X, Y)*B
232
+ >>> CrossCovarianceMatrix(A*X + B*Y, C.T*Z + D.T*W).expand()
233
+ A*CrossCovarianceMatrix(X, W)*D + A*CrossCovarianceMatrix(X, Z)*C + B*CrossCovarianceMatrix(Y, W)*D + B*CrossCovarianceMatrix(Y, Z)*C
234
+
235
+ """
236
+ def __new__(cls, arg1, arg2, condition=None):
237
+ arg1 = _sympify(arg1)
238
+ arg2 = _sympify(arg2)
239
+
240
+ if (1 not in arg1.shape) or (1 not in arg2.shape) or (arg1.shape[1] != arg2.shape[1]):
241
+ raise ShapeError("Expression is not a vector")
242
+
243
+ shape = (arg1.shape[0], arg2.shape[0]) if arg1.shape[1] == 1 and arg2.shape[1] == 1 \
244
+ else (1, 1)
245
+
246
+ if condition:
247
+ obj = Expr.__new__(cls, arg1, arg2, condition)
248
+ else:
249
+ obj = Expr.__new__(cls, arg1, arg2)
250
+
251
+ obj._shape = shape
252
+ obj._condition = condition
253
+ return obj
254
+
255
+ @property
256
+ def shape(self):
257
+ return self._shape
258
+
259
+ def expand(self, **hints):
260
+ arg1 = self.args[0]
261
+ arg2 = self.args[1]
262
+ condition = self._condition
263
+
264
+ if arg1 == arg2:
265
+ return VarianceMatrix(arg1, condition).expand()
266
+
267
+ if not is_random(arg1) or not is_random(arg2):
268
+ return ZeroMatrix(*self.shape)
269
+
270
+ if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol):
271
+ return CrossCovarianceMatrix(arg1, arg2, condition)
272
+
273
+ coeff_rv_list1 = self._expand_single_argument(arg1.expand())
274
+ coeff_rv_list2 = self._expand_single_argument(arg2.expand())
275
+
276
+ addends = [a*CrossCovarianceMatrix(r1, r2, condition=condition)*b.transpose()
277
+ for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2]
278
+ return Add.fromiter(addends)
279
+
280
+ @classmethod
281
+ def _expand_single_argument(cls, expr):
282
+ # return (coefficient, random_symbol) pairs:
283
+ if isinstance(expr, RandomSymbol):
284
+ return [(S.One, expr)]
285
+ elif isinstance(expr, Add):
286
+ outval = []
287
+ for a in expr.args:
288
+ if isinstance(a, (Mul, MatMul)):
289
+ outval.append(cls._get_mul_nonrv_rv_tuple(a))
290
+ elif is_random(a):
291
+ outval.append((S.One, a))
292
+
293
+ return outval
294
+ elif isinstance(expr, (Mul, MatMul)):
295
+ return [cls._get_mul_nonrv_rv_tuple(expr)]
296
+ elif is_random(expr):
297
+ return [(S.One, expr)]
298
+
299
+ @classmethod
300
+ def _get_mul_nonrv_rv_tuple(cls, m):
301
+ rv = []
302
+ nonrv = []
303
+ for a in m.args:
304
+ if is_random(a):
305
+ rv.append(a)
306
+ else:
307
+ nonrv.append(a)
308
+ return (Mul.fromiter(nonrv), Mul.fromiter(rv))
mplug_owl2/lib/python3.10/site-packages/sympy/stats/symbolic_probability.py ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from sympy.concrete.summations import Sum
3
+ from sympy.core.add import Add
4
+ from sympy.core.expr import Expr
5
+ from sympy.core.function import expand as _expand
6
+ from sympy.core.mul import Mul
7
+ from sympy.core.relational import Eq
8
+ from sympy.core.singleton import S
9
+ from sympy.core.symbol import Symbol
10
+ from sympy.integrals.integrals import Integral
11
+ from sympy.logic.boolalg import Not
12
+ from sympy.core.parameters import global_parameters
13
+ from sympy.core.sorting import default_sort_key
14
+ from sympy.core.sympify import _sympify
15
+ from sympy.core.relational import Relational
16
+ from sympy.logic.boolalg import Boolean
17
+ from sympy.stats import variance, covariance
18
+ from sympy.stats.rv import (RandomSymbol, pspace, dependent,
19
+ given, sampling_E, RandomIndexedSymbol, is_random,
20
+ PSpace, sampling_P, random_symbols)
21
+
22
+ __all__ = ['Probability', 'Expectation', 'Variance', 'Covariance']
23
+
24
+
25
+ @is_random.register(Expr)
26
+ def _(x):
27
+ atoms = x.free_symbols
28
+ if len(atoms) == 1 and next(iter(atoms)) == x:
29
+ return False
30
+ return any(is_random(i) for i in atoms)
31
+
32
+ @is_random.register(RandomSymbol) # type: ignore
33
+ def _(x):
34
+ return True
35
+
36
+
37
+ class Probability(Expr):
38
+ """
39
+ Symbolic expression for the probability.
40
+
41
+ Examples
42
+ ========
43
+
44
+ >>> from sympy.stats import Probability, Normal
45
+ >>> from sympy import Integral
46
+ >>> X = Normal("X", 0, 1)
47
+ >>> prob = Probability(X > 1)
48
+ >>> prob
49
+ Probability(X > 1)
50
+
51
+ Integral representation:
52
+
53
+ >>> prob.rewrite(Integral)
54
+ Integral(sqrt(2)*exp(-_z**2/2)/(2*sqrt(pi)), (_z, 1, oo))
55
+
56
+ Evaluation of the integral:
57
+
58
+ >>> prob.evaluate_integral()
59
+ sqrt(2)*(-sqrt(2)*sqrt(pi)*erf(sqrt(2)/2) + sqrt(2)*sqrt(pi))/(4*sqrt(pi))
60
+ """
61
+
62
+ is_commutative = True
63
+
64
+ def __new__(cls, prob, condition=None, **kwargs):
65
+ prob = _sympify(prob)
66
+ if condition is None:
67
+ obj = Expr.__new__(cls, prob)
68
+ else:
69
+ condition = _sympify(condition)
70
+ obj = Expr.__new__(cls, prob, condition)
71
+ obj._condition = condition
72
+ return obj
73
+
74
+ def doit(self, **hints):
75
+ condition = self.args[0]
76
+ given_condition = self._condition
77
+ numsamples = hints.get('numsamples', False)
78
+ evaluate = hints.get('evaluate', True)
79
+
80
+ if isinstance(condition, Not):
81
+ return S.One - self.func(condition.args[0], given_condition,
82
+ evaluate=evaluate).doit(**hints)
83
+
84
+ if condition.has(RandomIndexedSymbol):
85
+ return pspace(condition).probability(condition, given_condition,
86
+ evaluate=evaluate)
87
+
88
+ if isinstance(given_condition, RandomSymbol):
89
+ condrv = random_symbols(condition)
90
+ if len(condrv) == 1 and condrv[0] == given_condition:
91
+ from sympy.stats.frv_types import BernoulliDistribution
92
+ return BernoulliDistribution(self.func(condition).doit(**hints), 0, 1)
93
+ if any(dependent(rv, given_condition) for rv in condrv):
94
+ return Probability(condition, given_condition)
95
+ else:
96
+ return Probability(condition).doit()
97
+
98
+ if given_condition is not None and \
99
+ not isinstance(given_condition, (Relational, Boolean)):
100
+ raise ValueError("%s is not a relational or combination of relationals"
101
+ % (given_condition))
102
+
103
+ if given_condition == False or condition is S.false:
104
+ return S.Zero
105
+ if not isinstance(condition, (Relational, Boolean)):
106
+ raise ValueError("%s is not a relational or combination of relationals"
107
+ % (condition))
108
+ if condition is S.true:
109
+ return S.One
110
+
111
+ if numsamples:
112
+ return sampling_P(condition, given_condition, numsamples=numsamples)
113
+ if given_condition is not None: # If there is a condition
114
+ # Recompute on new conditional expr
115
+ return Probability(given(condition, given_condition)).doit()
116
+
117
+ # Otherwise pass work off to the ProbabilitySpace
118
+ if pspace(condition) == PSpace():
119
+ return Probability(condition, given_condition)
120
+
121
+ result = pspace(condition).probability(condition)
122
+ if hasattr(result, 'doit') and evaluate:
123
+ return result.doit()
124
+ else:
125
+ return result
126
+
127
+ def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs):
128
+ return self.func(arg, condition=condition).doit(evaluate=False)
129
+
130
+ _eval_rewrite_as_Sum = _eval_rewrite_as_Integral
131
+
132
+ def evaluate_integral(self):
133
+ return self.rewrite(Integral).doit()
134
+
135
+
136
+ class Expectation(Expr):
137
+ """
138
+ Symbolic expression for the expectation.
139
+
140
+ Examples
141
+ ========
142
+
143
+ >>> from sympy.stats import Expectation, Normal, Probability, Poisson
144
+ >>> from sympy import symbols, Integral, Sum
145
+ >>> mu = symbols("mu")
146
+ >>> sigma = symbols("sigma", positive=True)
147
+ >>> X = Normal("X", mu, sigma)
148
+ >>> Expectation(X)
149
+ Expectation(X)
150
+ >>> Expectation(X).evaluate_integral().simplify()
151
+ mu
152
+
153
+ To get the integral expression of the expectation:
154
+
155
+ >>> Expectation(X).rewrite(Integral)
156
+ Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo))
157
+
158
+ The same integral expression, in more abstract terms:
159
+
160
+ >>> Expectation(X).rewrite(Probability)
161
+ Integral(x*Probability(Eq(X, x)), (x, -oo, oo))
162
+
163
+ To get the Summation expression of the expectation for discrete random variables:
164
+
165
+ >>> lamda = symbols('lamda', positive=True)
166
+ >>> Z = Poisson('Z', lamda)
167
+ >>> Expectation(Z).rewrite(Sum)
168
+ Sum(Z*lamda**Z*exp(-lamda)/factorial(Z), (Z, 0, oo))
169
+
170
+ This class is aware of some properties of the expectation:
171
+
172
+ >>> from sympy.abc import a
173
+ >>> Expectation(a*X)
174
+ Expectation(a*X)
175
+ >>> Y = Normal("Y", 1, 2)
176
+ >>> Expectation(X + Y)
177
+ Expectation(X + Y)
178
+
179
+ To expand the ``Expectation`` into its expression, use ``expand()``:
180
+
181
+ >>> Expectation(X + Y).expand()
182
+ Expectation(X) + Expectation(Y)
183
+ >>> Expectation(a*X + Y).expand()
184
+ a*Expectation(X) + Expectation(Y)
185
+ >>> Expectation(a*X + Y)
186
+ Expectation(a*X + Y)
187
+ >>> Expectation((X + Y)*(X - Y)).expand()
188
+ Expectation(X**2) - Expectation(Y**2)
189
+
190
+ To evaluate the ``Expectation``, use ``doit()``:
191
+
192
+ >>> Expectation(X + Y).doit()
193
+ mu + 1
194
+ >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit()
195
+ 3*mu + 1
196
+
197
+ To prevent evaluating nested ``Expectation``, use ``doit(deep=False)``
198
+
199
+ >>> Expectation(X + Expectation(Y)).doit(deep=False)
200
+ mu + Expectation(Expectation(Y))
201
+ >>> Expectation(X + Expectation(Y + Expectation(2*X))).doit(deep=False)
202
+ mu + Expectation(Expectation(Expectation(2*X) + Y))
203
+
204
+ """
205
+
206
+ def __new__(cls, expr, condition=None, **kwargs):
207
+ expr = _sympify(expr)
208
+ if expr.is_Matrix:
209
+ from sympy.stats.symbolic_multivariate_probability import ExpectationMatrix
210
+ return ExpectationMatrix(expr, condition)
211
+ if condition is None:
212
+ if not is_random(expr):
213
+ return expr
214
+ obj = Expr.__new__(cls, expr)
215
+ else:
216
+ condition = _sympify(condition)
217
+ obj = Expr.__new__(cls, expr, condition)
218
+ obj._condition = condition
219
+ return obj
220
+
221
+ def _eval_is_commutative(self):
222
+ return(self.args[0].is_commutative)
223
+
224
+ def expand(self, **hints):
225
+ expr = self.args[0]
226
+ condition = self._condition
227
+
228
+ if not is_random(expr):
229
+ return expr
230
+
231
+ if isinstance(expr, Add):
232
+ return Add.fromiter(Expectation(a, condition=condition).expand()
233
+ for a in expr.args)
234
+
235
+ expand_expr = _expand(expr)
236
+ if isinstance(expand_expr, Add):
237
+ return Add.fromiter(Expectation(a, condition=condition).expand()
238
+ for a in expand_expr.args)
239
+
240
+ elif isinstance(expr, Mul):
241
+ rv = []
242
+ nonrv = []
243
+ for a in expr.args:
244
+ if is_random(a):
245
+ rv.append(a)
246
+ else:
247
+ nonrv.append(a)
248
+ return Mul.fromiter(nonrv)*Expectation(Mul.fromiter(rv), condition=condition)
249
+
250
+ return self
251
+
252
+ def doit(self, **hints):
253
+ deep = hints.get('deep', True)
254
+ condition = self._condition
255
+ expr = self.args[0]
256
+ numsamples = hints.get('numsamples', False)
257
+ evaluate = hints.get('evaluate', True)
258
+
259
+ if deep:
260
+ expr = expr.doit(**hints)
261
+
262
+ if not is_random(expr) or isinstance(expr, Expectation): # expr isn't random?
263
+ return expr
264
+ if numsamples: # Computing by monte carlo sampling?
265
+ evalf = hints.get('evalf', True)
266
+ return sampling_E(expr, condition, numsamples=numsamples, evalf=evalf)
267
+
268
+ if expr.has(RandomIndexedSymbol):
269
+ return pspace(expr).compute_expectation(expr, condition)
270
+
271
+ # Create new expr and recompute E
272
+ if condition is not None: # If there is a condition
273
+ return self.func(given(expr, condition)).doit(**hints)
274
+
275
+ # A few known statements for efficiency
276
+
277
+ if expr.is_Add: # We know that E is Linear
278
+ return Add(*[self.func(arg, condition).doit(**hints)
279
+ if not isinstance(arg, Expectation) else self.func(arg, condition)
280
+ for arg in expr.args])
281
+ if expr.is_Mul:
282
+ if expr.atoms(Expectation):
283
+ return expr
284
+
285
+ if pspace(expr) == PSpace():
286
+ return self.func(expr)
287
+ # Otherwise case is simple, pass work off to the ProbabilitySpace
288
+ result = pspace(expr).compute_expectation(expr, evaluate=evaluate)
289
+ if hasattr(result, 'doit') and evaluate:
290
+ return result.doit(**hints)
291
+ else:
292
+ return result
293
+
294
+
295
+ def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs):
296
+ rvs = arg.atoms(RandomSymbol)
297
+ if len(rvs) > 1:
298
+ raise NotImplementedError()
299
+ if len(rvs) == 0:
300
+ return arg
301
+
302
+ rv = rvs.pop()
303
+ if rv.pspace is None:
304
+ raise ValueError("Probability space not known")
305
+
306
+ symbol = rv.symbol
307
+ if symbol.name[0].isupper():
308
+ symbol = Symbol(symbol.name.lower())
309
+ else :
310
+ symbol = Symbol(symbol.name + "_1")
311
+
312
+ if rv.pspace.is_Continuous:
313
+ return Integral(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.domain.set.sup))
314
+ else:
315
+ if rv.pspace.is_Finite:
316
+ raise NotImplementedError
317
+ else:
318
+ return Sum(arg.replace(rv, symbol)*Probability(Eq(rv, symbol), condition), (symbol, rv.pspace.domain.set.inf, rv.pspace.set.sup))
319
+
320
+ def _eval_rewrite_as_Integral(self, arg, condition=None, evaluate=False, **kwargs):
321
+ return self.func(arg, condition=condition).doit(deep=False, evaluate=evaluate)
322
+
323
+ _eval_rewrite_as_Sum = _eval_rewrite_as_Integral # For discrete this will be Sum
324
+
325
+ def evaluate_integral(self):
326
+ return self.rewrite(Integral).doit()
327
+
328
+ evaluate_sum = evaluate_integral
329
+
330
+ class Variance(Expr):
331
+ """
332
+ Symbolic expression for the variance.
333
+
334
+ Examples
335
+ ========
336
+
337
+ >>> from sympy import symbols, Integral
338
+ >>> from sympy.stats import Normal, Expectation, Variance, Probability
339
+ >>> mu = symbols("mu", positive=True)
340
+ >>> sigma = symbols("sigma", positive=True)
341
+ >>> X = Normal("X", mu, sigma)
342
+ >>> Variance(X)
343
+ Variance(X)
344
+ >>> Variance(X).evaluate_integral()
345
+ sigma**2
346
+
347
+ Integral representation of the underlying calculations:
348
+
349
+ >>> Variance(X).rewrite(Integral)
350
+ Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**2*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo))
351
+
352
+ Integral representation, without expanding the PDF:
353
+
354
+ >>> Variance(X).rewrite(Probability)
355
+ -Integral(x*Probability(Eq(X, x)), (x, -oo, oo))**2 + Integral(x**2*Probability(Eq(X, x)), (x, -oo, oo))
356
+
357
+ Rewrite the variance in terms of the expectation
358
+
359
+ >>> Variance(X).rewrite(Expectation)
360
+ -Expectation(X)**2 + Expectation(X**2)
361
+
362
+ Some transformations based on the properties of the variance may happen:
363
+
364
+ >>> from sympy.abc import a
365
+ >>> Y = Normal("Y", 0, 1)
366
+ >>> Variance(a*X)
367
+ Variance(a*X)
368
+
369
+ To expand the variance in its expression, use ``expand()``:
370
+
371
+ >>> Variance(a*X).expand()
372
+ a**2*Variance(X)
373
+ >>> Variance(X + Y)
374
+ Variance(X + Y)
375
+ >>> Variance(X + Y).expand()
376
+ 2*Covariance(X, Y) + Variance(X) + Variance(Y)
377
+
378
+ """
379
+ def __new__(cls, arg, condition=None, **kwargs):
380
+ arg = _sympify(arg)
381
+
382
+ if arg.is_Matrix:
383
+ from sympy.stats.symbolic_multivariate_probability import VarianceMatrix
384
+ return VarianceMatrix(arg, condition)
385
+ if condition is None:
386
+ obj = Expr.__new__(cls, arg)
387
+ else:
388
+ condition = _sympify(condition)
389
+ obj = Expr.__new__(cls, arg, condition)
390
+ obj._condition = condition
391
+ return obj
392
+
393
+ def _eval_is_commutative(self):
394
+ return self.args[0].is_commutative
395
+
396
+ def expand(self, **hints):
397
+ arg = self.args[0]
398
+ condition = self._condition
399
+
400
+ if not is_random(arg):
401
+ return S.Zero
402
+
403
+ if isinstance(arg, RandomSymbol):
404
+ return self
405
+ elif isinstance(arg, Add):
406
+ rv = []
407
+ for a in arg.args:
408
+ if is_random(a):
409
+ rv.append(a)
410
+ variances = Add(*(Variance(xv, condition).expand() for xv in rv))
411
+ map_to_covar = lambda x: 2*Covariance(*x, condition=condition).expand()
412
+ covariances = Add(*map(map_to_covar, itertools.combinations(rv, 2)))
413
+ return variances + covariances
414
+ elif isinstance(arg, Mul):
415
+ nonrv = []
416
+ rv = []
417
+ for a in arg.args:
418
+ if is_random(a):
419
+ rv.append(a)
420
+ else:
421
+ nonrv.append(a**2)
422
+ if len(rv) == 0:
423
+ return S.Zero
424
+ return Mul.fromiter(nonrv)*Variance(Mul.fromiter(rv), condition)
425
+
426
+ # this expression contains a RandomSymbol somehow:
427
+ return self
428
+
429
+ def _eval_rewrite_as_Expectation(self, arg, condition=None, **kwargs):
430
+ e1 = Expectation(arg**2, condition)
431
+ e2 = Expectation(arg, condition)**2
432
+ return e1 - e2
433
+
434
+ def _eval_rewrite_as_Probability(self, arg, condition=None, **kwargs):
435
+ return self.rewrite(Expectation).rewrite(Probability)
436
+
437
+ def _eval_rewrite_as_Integral(self, arg, condition=None, **kwargs):
438
+ return variance(self.args[0], self._condition, evaluate=False)
439
+
440
+ _eval_rewrite_as_Sum = _eval_rewrite_as_Integral
441
+
442
+ def evaluate_integral(self):
443
+ return self.rewrite(Integral).doit()
444
+
445
+
446
+ class Covariance(Expr):
447
+ """
448
+ Symbolic expression for the covariance.
449
+
450
+ Examples
451
+ ========
452
+
453
+ >>> from sympy.stats import Covariance
454
+ >>> from sympy.stats import Normal
455
+ >>> X = Normal("X", 3, 2)
456
+ >>> Y = Normal("Y", 0, 1)
457
+ >>> Z = Normal("Z", 0, 1)
458
+ >>> W = Normal("W", 0, 1)
459
+ >>> cexpr = Covariance(X, Y)
460
+ >>> cexpr
461
+ Covariance(X, Y)
462
+
463
+ Evaluate the covariance, `X` and `Y` are independent,
464
+ therefore zero is the result:
465
+
466
+ >>> cexpr.evaluate_integral()
467
+ 0
468
+
469
+ Rewrite the covariance expression in terms of expectations:
470
+
471
+ >>> from sympy.stats import Expectation
472
+ >>> cexpr.rewrite(Expectation)
473
+ Expectation(X*Y) - Expectation(X)*Expectation(Y)
474
+
475
+ In order to expand the argument, use ``expand()``:
476
+
477
+ >>> from sympy.abc import a, b, c, d
478
+ >>> Covariance(a*X + b*Y, c*Z + d*W)
479
+ Covariance(a*X + b*Y, c*Z + d*W)
480
+ >>> Covariance(a*X + b*Y, c*Z + d*W).expand()
481
+ a*c*Covariance(X, Z) + a*d*Covariance(W, X) + b*c*Covariance(Y, Z) + b*d*Covariance(W, Y)
482
+
483
+ This class is aware of some properties of the covariance:
484
+
485
+ >>> Covariance(X, X).expand()
486
+ Variance(X)
487
+ >>> Covariance(a*X, b*Y).expand()
488
+ a*b*Covariance(X, Y)
489
+ """
490
+
491
+ def __new__(cls, arg1, arg2, condition=None, **kwargs):
492
+ arg1 = _sympify(arg1)
493
+ arg2 = _sympify(arg2)
494
+
495
+ if arg1.is_Matrix or arg2.is_Matrix:
496
+ from sympy.stats.symbolic_multivariate_probability import CrossCovarianceMatrix
497
+ return CrossCovarianceMatrix(arg1, arg2, condition)
498
+
499
+ if kwargs.pop('evaluate', global_parameters.evaluate):
500
+ arg1, arg2 = sorted([arg1, arg2], key=default_sort_key)
501
+
502
+ if condition is None:
503
+ obj = Expr.__new__(cls, arg1, arg2)
504
+ else:
505
+ condition = _sympify(condition)
506
+ obj = Expr.__new__(cls, arg1, arg2, condition)
507
+ obj._condition = condition
508
+ return obj
509
+
510
+ def _eval_is_commutative(self):
511
+ return self.args[0].is_commutative
512
+
513
+ def expand(self, **hints):
514
+ arg1 = self.args[0]
515
+ arg2 = self.args[1]
516
+ condition = self._condition
517
+
518
+ if arg1 == arg2:
519
+ return Variance(arg1, condition).expand()
520
+
521
+ if not is_random(arg1):
522
+ return S.Zero
523
+ if not is_random(arg2):
524
+ return S.Zero
525
+
526
+ arg1, arg2 = sorted([arg1, arg2], key=default_sort_key)
527
+
528
+ if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol):
529
+ return Covariance(arg1, arg2, condition)
530
+
531
+ coeff_rv_list1 = self._expand_single_argument(arg1.expand())
532
+ coeff_rv_list2 = self._expand_single_argument(arg2.expand())
533
+
534
+ addends = [a*b*Covariance(*sorted([r1, r2], key=default_sort_key), condition=condition)
535
+ for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2]
536
+ return Add.fromiter(addends)
537
+
538
+ @classmethod
539
+ def _expand_single_argument(cls, expr):
540
+ # return (coefficient, random_symbol) pairs:
541
+ if isinstance(expr, RandomSymbol):
542
+ return [(S.One, expr)]
543
+ elif isinstance(expr, Add):
544
+ outval = []
545
+ for a in expr.args:
546
+ if isinstance(a, Mul):
547
+ outval.append(cls._get_mul_nonrv_rv_tuple(a))
548
+ elif is_random(a):
549
+ outval.append((S.One, a))
550
+
551
+ return outval
552
+ elif isinstance(expr, Mul):
553
+ return [cls._get_mul_nonrv_rv_tuple(expr)]
554
+ elif is_random(expr):
555
+ return [(S.One, expr)]
556
+
557
+ @classmethod
558
+ def _get_mul_nonrv_rv_tuple(cls, m):
559
+ rv = []
560
+ nonrv = []
561
+ for a in m.args:
562
+ if is_random(a):
563
+ rv.append(a)
564
+ else:
565
+ nonrv.append(a)
566
+ return (Mul.fromiter(nonrv), Mul.fromiter(rv))
567
+
568
+ def _eval_rewrite_as_Expectation(self, arg1, arg2, condition=None, **kwargs):
569
+ e1 = Expectation(arg1*arg2, condition)
570
+ e2 = Expectation(arg1, condition)*Expectation(arg2, condition)
571
+ return e1 - e2
572
+
573
+ def _eval_rewrite_as_Probability(self, arg1, arg2, condition=None, **kwargs):
574
+ return self.rewrite(Expectation).rewrite(Probability)
575
+
576
+ def _eval_rewrite_as_Integral(self, arg1, arg2, condition=None, **kwargs):
577
+ return covariance(self.args[0], self.args[1], self._condition, evaluate=False)
578
+
579
+ _eval_rewrite_as_Sum = _eval_rewrite_as_Integral
580
+
581
+ def evaluate_integral(self):
582
+ return self.rewrite(Integral).doit()
583
+
584
+
585
+ class Moment(Expr):
586
+ """
587
+ Symbolic class for Moment
588
+
589
+ Examples
590
+ ========
591
+
592
+ >>> from sympy import Symbol, Integral
593
+ >>> from sympy.stats import Normal, Expectation, Probability, Moment
594
+ >>> mu = Symbol('mu', real=True)
595
+ >>> sigma = Symbol('sigma', positive=True)
596
+ >>> X = Normal('X', mu, sigma)
597
+ >>> M = Moment(X, 3, 1)
598
+
599
+ To evaluate the result of Moment use `doit`:
600
+
601
+ >>> M.doit()
602
+ mu**3 - 3*mu**2 + 3*mu*sigma**2 + 3*mu - 3*sigma**2 - 1
603
+
604
+ Rewrite the Moment expression in terms of Expectation:
605
+
606
+ >>> M.rewrite(Expectation)
607
+ Expectation((X - 1)**3)
608
+
609
+ Rewrite the Moment expression in terms of Probability:
610
+
611
+ >>> M.rewrite(Probability)
612
+ Integral((x - 1)**3*Probability(Eq(X, x)), (x, -oo, oo))
613
+
614
+ Rewrite the Moment expression in terms of Integral:
615
+
616
+ >>> M.rewrite(Integral)
617
+ Integral(sqrt(2)*(X - 1)**3*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo))
618
+
619
+ """
620
+ def __new__(cls, X, n, c=0, condition=None, **kwargs):
621
+ X = _sympify(X)
622
+ n = _sympify(n)
623
+ c = _sympify(c)
624
+ if condition is not None:
625
+ condition = _sympify(condition)
626
+ return super().__new__(cls, X, n, c, condition)
627
+ else:
628
+ return super().__new__(cls, X, n, c)
629
+
630
+ def doit(self, **hints):
631
+ return self.rewrite(Expectation).doit(**hints)
632
+
633
+ def _eval_rewrite_as_Expectation(self, X, n, c=0, condition=None, **kwargs):
634
+ return Expectation((X - c)**n, condition)
635
+
636
+ def _eval_rewrite_as_Probability(self, X, n, c=0, condition=None, **kwargs):
637
+ return self.rewrite(Expectation).rewrite(Probability)
638
+
639
+ def _eval_rewrite_as_Integral(self, X, n, c=0, condition=None, **kwargs):
640
+ return self.rewrite(Expectation).rewrite(Integral)
641
+
642
+
643
+ class CentralMoment(Expr):
644
+ """
645
+ Symbolic class Central Moment
646
+
647
+ Examples
648
+ ========
649
+
650
+ >>> from sympy import Symbol, Integral
651
+ >>> from sympy.stats import Normal, Expectation, Probability, CentralMoment
652
+ >>> mu = Symbol('mu', real=True)
653
+ >>> sigma = Symbol('sigma', positive=True)
654
+ >>> X = Normal('X', mu, sigma)
655
+ >>> CM = CentralMoment(X, 4)
656
+
657
+ To evaluate the result of CentralMoment use `doit`:
658
+
659
+ >>> CM.doit().simplify()
660
+ 3*sigma**4
661
+
662
+ Rewrite the CentralMoment expression in terms of Expectation:
663
+
664
+ >>> CM.rewrite(Expectation)
665
+ Expectation((-Expectation(X) + X)**4)
666
+
667
+ Rewrite the CentralMoment expression in terms of Probability:
668
+
669
+ >>> CM.rewrite(Probability)
670
+ Integral((x - Integral(x*Probability(True), (x, -oo, oo)))**4*Probability(Eq(X, x)), (x, -oo, oo))
671
+
672
+ Rewrite the CentralMoment expression in terms of Integral:
673
+
674
+ >>> CM.rewrite(Integral)
675
+ Integral(sqrt(2)*(X - Integral(sqrt(2)*X*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo)))**4*exp(-(X - mu)**2/(2*sigma**2))/(2*sqrt(pi)*sigma), (X, -oo, oo))
676
+
677
+ """
678
+ def __new__(cls, X, n, condition=None, **kwargs):
679
+ X = _sympify(X)
680
+ n = _sympify(n)
681
+ if condition is not None:
682
+ condition = _sympify(condition)
683
+ return super().__new__(cls, X, n, condition)
684
+ else:
685
+ return super().__new__(cls, X, n)
686
+
687
+ def doit(self, **hints):
688
+ return self.rewrite(Expectation).doit(**hints)
689
+
690
+ def _eval_rewrite_as_Expectation(self, X, n, condition=None, **kwargs):
691
+ mu = Expectation(X, condition, **kwargs)
692
+ return Moment(X, n, mu, condition, **kwargs).rewrite(Expectation)
693
+
694
+ def _eval_rewrite_as_Probability(self, X, n, condition=None, **kwargs):
695
+ return self.rewrite(Expectation).rewrite(Probability)
696
+
697
+ def _eval_rewrite_as_Integral(self, X, n, condition=None, **kwargs):
698
+ return self.rewrite(Expectation).rewrite(Integral)
mplug_owl2/lib/python3.10/site-packages/sympy/stats/tests/__init__.py ADDED
File without changes