Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- llmeval-env/lib/python3.10/site-packages/sympy/interactive/__init__.py +8 -0
- llmeval-env/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/interactive/printing.py +562 -0
- llmeval-env/lib/python3.10/site-packages/sympy/interactive/session.py +463 -0
- llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/interactive/traversal.py +95 -0
- llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_combsimp.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/compound_rv.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/crv.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/crv_types.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/drv.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/drv_types.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/error_prop.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/frv.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/frv_types.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv_types.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/matrix_distributions.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix_models.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/rv.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/rv_interface.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process_types.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_multivariate_probability.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_probability.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/drv.py +350 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/drv_types.py +835 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/error_prop.py +100 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/frv.py +512 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/frv_types.py +870 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/joint_rv.py +426 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/matrix_distributions.py +610 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/random_matrix.py +30 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/random_matrix_models.py +457 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/rv.py +1792 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/rv_interface.py +519 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/__init__.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_numpy.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_pymc.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_scipy.cpython-310.pyc +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/sample_numpy.py +105 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/sample_pymc.py +99 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/sample_scipy.py +167 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/tests/__init__.py +0 -0
- llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/__init__.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/sympy/interactive/__init__.py
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Helper module for setting up interactive SymPy sessions. """
|
2 |
+
|
3 |
+
from .printing import init_printing
|
4 |
+
from .session import init_session
|
5 |
+
from .traversal import interactive_traversal
|
6 |
+
|
7 |
+
|
8 |
+
__all__ = ['init_printing', 'init_session', 'interactive_traversal']
|
llmeval-env/lib/python3.10/site-packages/sympy/interactive/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (445 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/interactive/__pycache__/printing.cpython-310.pyc
ADDED
Binary file (17.4 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/interactive/__pycache__/session.cpython-310.pyc
ADDED
Binary file (11.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/interactive/__pycache__/traversal.cpython-310.pyc
ADDED
Binary file (2.45 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/interactive/printing.py
ADDED
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tools for setting up printing in interactive sessions. """
|
2 |
+
|
3 |
+
from sympy.external.importtools import version_tuple
|
4 |
+
from io import BytesIO
|
5 |
+
|
6 |
+
from sympy.printing.latex import latex as default_latex
|
7 |
+
from sympy.printing.preview import preview
|
8 |
+
from sympy.utilities.misc import debug
|
9 |
+
from sympy.printing.defaults import Printable
|
10 |
+
|
11 |
+
|
12 |
+
def _init_python_printing(stringify_func, **settings):
|
13 |
+
"""Setup printing in Python interactive session. """
|
14 |
+
import sys
|
15 |
+
import builtins
|
16 |
+
|
17 |
+
def _displayhook(arg):
|
18 |
+
"""Python's pretty-printer display hook.
|
19 |
+
|
20 |
+
This function was adapted from:
|
21 |
+
|
22 |
+
https://www.python.org/dev/peps/pep-0217/
|
23 |
+
|
24 |
+
"""
|
25 |
+
if arg is not None:
|
26 |
+
builtins._ = None
|
27 |
+
print(stringify_func(arg, **settings))
|
28 |
+
builtins._ = arg
|
29 |
+
|
30 |
+
sys.displayhook = _displayhook
|
31 |
+
|
32 |
+
|
33 |
+
def _init_ipython_printing(ip, stringify_func, use_latex, euler, forecolor,
|
34 |
+
backcolor, fontsize, latex_mode, print_builtin,
|
35 |
+
latex_printer, scale, **settings):
|
36 |
+
"""Setup printing in IPython interactive session. """
|
37 |
+
try:
|
38 |
+
from IPython.lib.latextools import latex_to_png
|
39 |
+
except ImportError:
|
40 |
+
pass
|
41 |
+
|
42 |
+
# Guess best font color if none was given based on the ip.colors string.
|
43 |
+
# From the IPython documentation:
|
44 |
+
# It has four case-insensitive values: 'nocolor', 'neutral', 'linux',
|
45 |
+
# 'lightbg'. The default is neutral, which should be legible on either
|
46 |
+
# dark or light terminal backgrounds. linux is optimised for dark
|
47 |
+
# backgrounds and lightbg for light ones.
|
48 |
+
if forecolor is None:
|
49 |
+
color = ip.colors.lower()
|
50 |
+
if color == 'lightbg':
|
51 |
+
forecolor = 'Black'
|
52 |
+
elif color == 'linux':
|
53 |
+
forecolor = 'White'
|
54 |
+
else:
|
55 |
+
# No idea, go with gray.
|
56 |
+
forecolor = 'Gray'
|
57 |
+
debug("init_printing: Automatic foreground color:", forecolor)
|
58 |
+
|
59 |
+
if use_latex == "svg":
|
60 |
+
extra_preamble = "\n\\special{color %s}" % forecolor
|
61 |
+
else:
|
62 |
+
extra_preamble = ""
|
63 |
+
|
64 |
+
imagesize = 'tight'
|
65 |
+
offset = "0cm,0cm"
|
66 |
+
resolution = round(150*scale)
|
67 |
+
dvi = r"-T %s -D %d -bg %s -fg %s -O %s" % (
|
68 |
+
imagesize, resolution, backcolor, forecolor, offset)
|
69 |
+
dvioptions = dvi.split()
|
70 |
+
|
71 |
+
svg_scale = 150/72*scale
|
72 |
+
dvioptions_svg = ["--no-fonts", "--scale={}".format(svg_scale)]
|
73 |
+
|
74 |
+
debug("init_printing: DVIOPTIONS:", dvioptions)
|
75 |
+
debug("init_printing: DVIOPTIONS_SVG:", dvioptions_svg)
|
76 |
+
|
77 |
+
latex = latex_printer or default_latex
|
78 |
+
|
79 |
+
def _print_plain(arg, p, cycle):
|
80 |
+
"""caller for pretty, for use in IPython 0.11"""
|
81 |
+
if _can_print(arg):
|
82 |
+
p.text(stringify_func(arg))
|
83 |
+
else:
|
84 |
+
p.text(IPython.lib.pretty.pretty(arg))
|
85 |
+
|
86 |
+
def _preview_wrapper(o):
|
87 |
+
exprbuffer = BytesIO()
|
88 |
+
try:
|
89 |
+
preview(o, output='png', viewer='BytesIO', euler=euler,
|
90 |
+
outputbuffer=exprbuffer, extra_preamble=extra_preamble,
|
91 |
+
dvioptions=dvioptions, fontsize=fontsize)
|
92 |
+
except Exception as e:
|
93 |
+
# IPython swallows exceptions
|
94 |
+
debug("png printing:", "_preview_wrapper exception raised:",
|
95 |
+
repr(e))
|
96 |
+
raise
|
97 |
+
return exprbuffer.getvalue()
|
98 |
+
|
99 |
+
def _svg_wrapper(o):
|
100 |
+
exprbuffer = BytesIO()
|
101 |
+
try:
|
102 |
+
preview(o, output='svg', viewer='BytesIO', euler=euler,
|
103 |
+
outputbuffer=exprbuffer, extra_preamble=extra_preamble,
|
104 |
+
dvioptions=dvioptions_svg, fontsize=fontsize)
|
105 |
+
except Exception as e:
|
106 |
+
# IPython swallows exceptions
|
107 |
+
debug("svg printing:", "_preview_wrapper exception raised:",
|
108 |
+
repr(e))
|
109 |
+
raise
|
110 |
+
return exprbuffer.getvalue().decode('utf-8')
|
111 |
+
|
112 |
+
def _matplotlib_wrapper(o):
|
113 |
+
# mathtext can't render some LaTeX commands. For example, it can't
|
114 |
+
# render any LaTeX environments such as array or matrix. So here we
|
115 |
+
# ensure that if mathtext fails to render, we return None.
|
116 |
+
try:
|
117 |
+
try:
|
118 |
+
return latex_to_png(o, color=forecolor, scale=scale)
|
119 |
+
except TypeError: # Old IPython version without color and scale
|
120 |
+
return latex_to_png(o)
|
121 |
+
except ValueError as e:
|
122 |
+
debug('matplotlib exception caught:', repr(e))
|
123 |
+
return None
|
124 |
+
|
125 |
+
|
126 |
+
# Hook methods for builtin SymPy printers
|
127 |
+
printing_hooks = ('_latex', '_sympystr', '_pretty', '_sympyrepr')
|
128 |
+
|
129 |
+
|
130 |
+
def _can_print(o):
|
131 |
+
"""Return True if type o can be printed with one of the SymPy printers.
|
132 |
+
|
133 |
+
If o is a container type, this is True if and only if every element of
|
134 |
+
o can be printed in this way.
|
135 |
+
"""
|
136 |
+
|
137 |
+
try:
|
138 |
+
# If you're adding another type, make sure you add it to printable_types
|
139 |
+
# later in this file as well
|
140 |
+
|
141 |
+
builtin_types = (list, tuple, set, frozenset)
|
142 |
+
if isinstance(o, builtin_types):
|
143 |
+
# If the object is a custom subclass with a custom str or
|
144 |
+
# repr, use that instead.
|
145 |
+
if (type(o).__str__ not in (i.__str__ for i in builtin_types) or
|
146 |
+
type(o).__repr__ not in (i.__repr__ for i in builtin_types)):
|
147 |
+
return False
|
148 |
+
return all(_can_print(i) for i in o)
|
149 |
+
elif isinstance(o, dict):
|
150 |
+
return all(_can_print(i) and _can_print(o[i]) for i in o)
|
151 |
+
elif isinstance(o, bool):
|
152 |
+
return False
|
153 |
+
elif isinstance(o, Printable):
|
154 |
+
# types known to SymPy
|
155 |
+
return True
|
156 |
+
elif any(hasattr(o, hook) for hook in printing_hooks):
|
157 |
+
# types which add support themselves
|
158 |
+
return True
|
159 |
+
elif isinstance(o, (float, int)) and print_builtin:
|
160 |
+
return True
|
161 |
+
return False
|
162 |
+
except RuntimeError:
|
163 |
+
return False
|
164 |
+
# This is in case maximum recursion depth is reached.
|
165 |
+
# Since RecursionError is for versions of Python 3.5+
|
166 |
+
# so this is to guard against RecursionError for older versions.
|
167 |
+
|
168 |
+
def _print_latex_png(o):
|
169 |
+
"""
|
170 |
+
A function that returns a png rendered by an external latex
|
171 |
+
distribution, falling back to matplotlib rendering
|
172 |
+
"""
|
173 |
+
if _can_print(o):
|
174 |
+
s = latex(o, mode=latex_mode, **settings)
|
175 |
+
if latex_mode == 'plain':
|
176 |
+
s = '$\\displaystyle %s$' % s
|
177 |
+
try:
|
178 |
+
return _preview_wrapper(s)
|
179 |
+
except RuntimeError as e:
|
180 |
+
debug('preview failed with:', repr(e),
|
181 |
+
' Falling back to matplotlib backend')
|
182 |
+
if latex_mode != 'inline':
|
183 |
+
s = latex(o, mode='inline', **settings)
|
184 |
+
return _matplotlib_wrapper(s)
|
185 |
+
|
186 |
+
def _print_latex_svg(o):
|
187 |
+
"""
|
188 |
+
A function that returns a svg rendered by an external latex
|
189 |
+
distribution, no fallback available.
|
190 |
+
"""
|
191 |
+
if _can_print(o):
|
192 |
+
s = latex(o, mode=latex_mode, **settings)
|
193 |
+
if latex_mode == 'plain':
|
194 |
+
s = '$\\displaystyle %s$' % s
|
195 |
+
try:
|
196 |
+
return _svg_wrapper(s)
|
197 |
+
except RuntimeError as e:
|
198 |
+
debug('preview failed with:', repr(e),
|
199 |
+
' No fallback available.')
|
200 |
+
|
201 |
+
def _print_latex_matplotlib(o):
|
202 |
+
"""
|
203 |
+
A function that returns a png rendered by mathtext
|
204 |
+
"""
|
205 |
+
if _can_print(o):
|
206 |
+
s = latex(o, mode='inline', **settings)
|
207 |
+
return _matplotlib_wrapper(s)
|
208 |
+
|
209 |
+
def _print_latex_text(o):
|
210 |
+
"""
|
211 |
+
A function to generate the latex representation of SymPy expressions.
|
212 |
+
"""
|
213 |
+
if _can_print(o):
|
214 |
+
s = latex(o, mode=latex_mode, **settings)
|
215 |
+
if latex_mode == 'plain':
|
216 |
+
return '$\\displaystyle %s$' % s
|
217 |
+
return s
|
218 |
+
|
219 |
+
def _result_display(self, arg):
|
220 |
+
"""IPython's pretty-printer display hook, for use in IPython 0.10
|
221 |
+
|
222 |
+
This function was adapted from:
|
223 |
+
|
224 |
+
ipython/IPython/hooks.py:155
|
225 |
+
|
226 |
+
"""
|
227 |
+
if self.rc.pprint:
|
228 |
+
out = stringify_func(arg)
|
229 |
+
|
230 |
+
if '\n' in out:
|
231 |
+
print()
|
232 |
+
|
233 |
+
print(out)
|
234 |
+
else:
|
235 |
+
print(repr(arg))
|
236 |
+
|
237 |
+
import IPython
|
238 |
+
if version_tuple(IPython.__version__) >= version_tuple('0.11'):
|
239 |
+
|
240 |
+
# Printable is our own type, so we handle it with methods instead of
|
241 |
+
# the approach required by builtin types. This allows downstream
|
242 |
+
# packages to override the methods in their own subclasses of Printable,
|
243 |
+
# which avoids the effects of gh-16002.
|
244 |
+
printable_types = [float, tuple, list, set, frozenset, dict, int]
|
245 |
+
|
246 |
+
plaintext_formatter = ip.display_formatter.formatters['text/plain']
|
247 |
+
|
248 |
+
# Exception to the rule above: IPython has better dispatching rules
|
249 |
+
# for plaintext printing (xref ipython/ipython#8938), and we can't
|
250 |
+
# use `_repr_pretty_` without hitting a recursion error in _print_plain.
|
251 |
+
for cls in printable_types + [Printable]:
|
252 |
+
plaintext_formatter.for_type(cls, _print_plain)
|
253 |
+
|
254 |
+
svg_formatter = ip.display_formatter.formatters['image/svg+xml']
|
255 |
+
if use_latex in ('svg', ):
|
256 |
+
debug("init_printing: using svg formatter")
|
257 |
+
for cls in printable_types:
|
258 |
+
svg_formatter.for_type(cls, _print_latex_svg)
|
259 |
+
Printable._repr_svg_ = _print_latex_svg
|
260 |
+
else:
|
261 |
+
debug("init_printing: not using any svg formatter")
|
262 |
+
for cls in printable_types:
|
263 |
+
# Better way to set this, but currently does not work in IPython
|
264 |
+
#png_formatter.for_type(cls, None)
|
265 |
+
if cls in svg_formatter.type_printers:
|
266 |
+
svg_formatter.type_printers.pop(cls)
|
267 |
+
Printable._repr_svg_ = Printable._repr_disabled
|
268 |
+
|
269 |
+
png_formatter = ip.display_formatter.formatters['image/png']
|
270 |
+
if use_latex in (True, 'png'):
|
271 |
+
debug("init_printing: using png formatter")
|
272 |
+
for cls in printable_types:
|
273 |
+
png_formatter.for_type(cls, _print_latex_png)
|
274 |
+
Printable._repr_png_ = _print_latex_png
|
275 |
+
elif use_latex == 'matplotlib':
|
276 |
+
debug("init_printing: using matplotlib formatter")
|
277 |
+
for cls in printable_types:
|
278 |
+
png_formatter.for_type(cls, _print_latex_matplotlib)
|
279 |
+
Printable._repr_png_ = _print_latex_matplotlib
|
280 |
+
else:
|
281 |
+
debug("init_printing: not using any png formatter")
|
282 |
+
for cls in printable_types:
|
283 |
+
# Better way to set this, but currently does not work in IPython
|
284 |
+
#png_formatter.for_type(cls, None)
|
285 |
+
if cls in png_formatter.type_printers:
|
286 |
+
png_formatter.type_printers.pop(cls)
|
287 |
+
Printable._repr_png_ = Printable._repr_disabled
|
288 |
+
|
289 |
+
latex_formatter = ip.display_formatter.formatters['text/latex']
|
290 |
+
if use_latex in (True, 'mathjax'):
|
291 |
+
debug("init_printing: using mathjax formatter")
|
292 |
+
for cls in printable_types:
|
293 |
+
latex_formatter.for_type(cls, _print_latex_text)
|
294 |
+
Printable._repr_latex_ = _print_latex_text
|
295 |
+
else:
|
296 |
+
debug("init_printing: not using text/latex formatter")
|
297 |
+
for cls in printable_types:
|
298 |
+
# Better way to set this, but currently does not work in IPython
|
299 |
+
#latex_formatter.for_type(cls, None)
|
300 |
+
if cls in latex_formatter.type_printers:
|
301 |
+
latex_formatter.type_printers.pop(cls)
|
302 |
+
Printable._repr_latex_ = Printable._repr_disabled
|
303 |
+
|
304 |
+
else:
|
305 |
+
ip.set_hook('result_display', _result_display)
|
306 |
+
|
307 |
+
def _is_ipython(shell):
|
308 |
+
"""Is a shell instance an IPython shell?"""
|
309 |
+
# shortcut, so we don't import IPython if we don't have to
|
310 |
+
from sys import modules
|
311 |
+
if 'IPython' not in modules:
|
312 |
+
return False
|
313 |
+
try:
|
314 |
+
from IPython.core.interactiveshell import InteractiveShell
|
315 |
+
except ImportError:
|
316 |
+
# IPython < 0.11
|
317 |
+
try:
|
318 |
+
from IPython.iplib import InteractiveShell
|
319 |
+
except ImportError:
|
320 |
+
# Reaching this points means IPython has changed in a backward-incompatible way
|
321 |
+
# that we don't know about. Warn?
|
322 |
+
return False
|
323 |
+
return isinstance(shell, InteractiveShell)
|
324 |
+
|
325 |
+
# Used by the doctester to override the default for no_global
|
326 |
+
NO_GLOBAL = False
|
327 |
+
|
328 |
+
def init_printing(pretty_print=True, order=None, use_unicode=None,
|
329 |
+
use_latex=None, wrap_line=None, num_columns=None,
|
330 |
+
no_global=False, ip=None, euler=False, forecolor=None,
|
331 |
+
backcolor='Transparent', fontsize='10pt',
|
332 |
+
latex_mode='plain', print_builtin=True,
|
333 |
+
str_printer=None, pretty_printer=None,
|
334 |
+
latex_printer=None, scale=1.0, **settings):
|
335 |
+
r"""
|
336 |
+
Initializes pretty-printer depending on the environment.
|
337 |
+
|
338 |
+
Parameters
|
339 |
+
==========
|
340 |
+
|
341 |
+
pretty_print : bool, default=True
|
342 |
+
If ``True``, use :func:`~.pretty_print` to stringify or the provided pretty
|
343 |
+
printer; if ``False``, use :func:`~.sstrrepr` to stringify or the provided string
|
344 |
+
printer.
|
345 |
+
order : string or None, default='lex'
|
346 |
+
There are a few different settings for this parameter:
|
347 |
+
``'lex'`` (default), which is lexographic order;
|
348 |
+
``'grlex'``, which is graded lexographic order;
|
349 |
+
``'grevlex'``, which is reversed graded lexographic order;
|
350 |
+
``'old'``, which is used for compatibility reasons and for long expressions;
|
351 |
+
``None``, which sets it to lex.
|
352 |
+
use_unicode : bool or None, default=None
|
353 |
+
If ``True``, use unicode characters;
|
354 |
+
if ``False``, do not use unicode characters;
|
355 |
+
if ``None``, make a guess based on the environment.
|
356 |
+
use_latex : string, bool, or None, default=None
|
357 |
+
If ``True``, use default LaTeX rendering in GUI interfaces (png and
|
358 |
+
mathjax);
|
359 |
+
if ``False``, do not use LaTeX rendering;
|
360 |
+
if ``None``, make a guess based on the environment;
|
361 |
+
if ``'png'``, enable LaTeX rendering with an external LaTeX compiler,
|
362 |
+
falling back to matplotlib if external compilation fails;
|
363 |
+
if ``'matplotlib'``, enable LaTeX rendering with matplotlib;
|
364 |
+
if ``'mathjax'``, enable LaTeX text generation, for example MathJax
|
365 |
+
rendering in IPython notebook or text rendering in LaTeX documents;
|
366 |
+
if ``'svg'``, enable LaTeX rendering with an external latex compiler,
|
367 |
+
no fallback
|
368 |
+
wrap_line : bool
|
369 |
+
If True, lines will wrap at the end; if False, they will not wrap
|
370 |
+
but continue as one line. This is only relevant if ``pretty_print`` is
|
371 |
+
True.
|
372 |
+
num_columns : int or None, default=None
|
373 |
+
If ``int``, number of columns before wrapping is set to num_columns; if
|
374 |
+
``None``, number of columns before wrapping is set to terminal width.
|
375 |
+
This is only relevant if ``pretty_print`` is ``True``.
|
376 |
+
no_global : bool, default=False
|
377 |
+
If ``True``, the settings become system wide;
|
378 |
+
if ``False``, use just for this console/session.
|
379 |
+
ip : An interactive console
|
380 |
+
This can either be an instance of IPython,
|
381 |
+
or a class that derives from code.InteractiveConsole.
|
382 |
+
euler : bool, optional, default=False
|
383 |
+
Loads the euler package in the LaTeX preamble for handwritten style
|
384 |
+
fonts (https://www.ctan.org/pkg/euler).
|
385 |
+
forecolor : string or None, optional, default=None
|
386 |
+
DVI setting for foreground color. ``None`` means that either ``'Black'``,
|
387 |
+
``'White'``, or ``'Gray'`` will be selected based on a guess of the IPython
|
388 |
+
terminal color setting. See notes.
|
389 |
+
backcolor : string, optional, default='Transparent'
|
390 |
+
DVI setting for background color. See notes.
|
391 |
+
fontsize : string or int, optional, default='10pt'
|
392 |
+
A font size to pass to the LaTeX documentclass function in the
|
393 |
+
preamble. Note that the options are limited by the documentclass.
|
394 |
+
Consider using scale instead.
|
395 |
+
latex_mode : string, optional, default='plain'
|
396 |
+
The mode used in the LaTeX printer. Can be one of:
|
397 |
+
``{'inline'|'plain'|'equation'|'equation*'}``.
|
398 |
+
print_builtin : boolean, optional, default=True
|
399 |
+
If ``True`` then floats and integers will be printed. If ``False`` the
|
400 |
+
printer will only print SymPy types.
|
401 |
+
str_printer : function, optional, default=None
|
402 |
+
A custom string printer function. This should mimic
|
403 |
+
:func:`~.sstrrepr()`.
|
404 |
+
pretty_printer : function, optional, default=None
|
405 |
+
A custom pretty printer. This should mimic :func:`~.pretty()`.
|
406 |
+
latex_printer : function, optional, default=None
|
407 |
+
A custom LaTeX printer. This should mimic :func:`~.latex()`.
|
408 |
+
scale : float, optional, default=1.0
|
409 |
+
Scale the LaTeX output when using the ``'png'`` or ``'svg'`` backends.
|
410 |
+
Useful for high dpi screens.
|
411 |
+
settings :
|
412 |
+
Any additional settings for the ``latex`` and ``pretty`` commands can
|
413 |
+
be used to fine-tune the output.
|
414 |
+
|
415 |
+
Examples
|
416 |
+
========
|
417 |
+
|
418 |
+
>>> from sympy.interactive import init_printing
|
419 |
+
>>> from sympy import Symbol, sqrt
|
420 |
+
>>> from sympy.abc import x, y
|
421 |
+
>>> sqrt(5)
|
422 |
+
sqrt(5)
|
423 |
+
>>> init_printing(pretty_print=True) # doctest: +SKIP
|
424 |
+
>>> sqrt(5) # doctest: +SKIP
|
425 |
+
___
|
426 |
+
\/ 5
|
427 |
+
>>> theta = Symbol('theta') # doctest: +SKIP
|
428 |
+
>>> init_printing(use_unicode=True) # doctest: +SKIP
|
429 |
+
>>> theta # doctest: +SKIP
|
430 |
+
\u03b8
|
431 |
+
>>> init_printing(use_unicode=False) # doctest: +SKIP
|
432 |
+
>>> theta # doctest: +SKIP
|
433 |
+
theta
|
434 |
+
>>> init_printing(order='lex') # doctest: +SKIP
|
435 |
+
>>> str(y + x + y**2 + x**2) # doctest: +SKIP
|
436 |
+
x**2 + x + y**2 + y
|
437 |
+
>>> init_printing(order='grlex') # doctest: +SKIP
|
438 |
+
>>> str(y + x + y**2 + x**2) # doctest: +SKIP
|
439 |
+
x**2 + x + y**2 + y
|
440 |
+
>>> init_printing(order='grevlex') # doctest: +SKIP
|
441 |
+
>>> str(y * x**2 + x * y**2) # doctest: +SKIP
|
442 |
+
x**2*y + x*y**2
|
443 |
+
>>> init_printing(order='old') # doctest: +SKIP
|
444 |
+
>>> str(x**2 + y**2 + x + y) # doctest: +SKIP
|
445 |
+
x**2 + x + y**2 + y
|
446 |
+
>>> init_printing(num_columns=10) # doctest: +SKIP
|
447 |
+
>>> x**2 + x + y**2 + y # doctest: +SKIP
|
448 |
+
x + y +
|
449 |
+
x**2 + y**2
|
450 |
+
|
451 |
+
Notes
|
452 |
+
=====
|
453 |
+
|
454 |
+
The foreground and background colors can be selected when using ``'png'`` or
|
455 |
+
``'svg'`` LaTeX rendering. Note that before the ``init_printing`` command is
|
456 |
+
executed, the LaTeX rendering is handled by the IPython console and not SymPy.
|
457 |
+
|
458 |
+
The colors can be selected among the 68 standard colors known to ``dvips``,
|
459 |
+
for a list see [1]_. In addition, the background color can be
|
460 |
+
set to ``'Transparent'`` (which is the default value).
|
461 |
+
|
462 |
+
When using the ``'Auto'`` foreground color, the guess is based on the
|
463 |
+
``colors`` variable in the IPython console, see [2]_. Hence, if
|
464 |
+
that variable is set correctly in your IPython console, there is a high
|
465 |
+
chance that the output will be readable, although manual settings may be
|
466 |
+
needed.
|
467 |
+
|
468 |
+
|
469 |
+
References
|
470 |
+
==========
|
471 |
+
|
472 |
+
.. [1] https://en.wikibooks.org/wiki/LaTeX/Colors#The_68_standard_colors_known_to_dvips
|
473 |
+
|
474 |
+
.. [2] https://ipython.readthedocs.io/en/stable/config/details.html#terminal-colors
|
475 |
+
|
476 |
+
See Also
|
477 |
+
========
|
478 |
+
|
479 |
+
sympy.printing.latex
|
480 |
+
sympy.printing.pretty
|
481 |
+
|
482 |
+
"""
|
483 |
+
import sys
|
484 |
+
from sympy.printing.printer import Printer
|
485 |
+
|
486 |
+
if pretty_print:
|
487 |
+
if pretty_printer is not None:
|
488 |
+
stringify_func = pretty_printer
|
489 |
+
else:
|
490 |
+
from sympy.printing import pretty as stringify_func
|
491 |
+
else:
|
492 |
+
if str_printer is not None:
|
493 |
+
stringify_func = str_printer
|
494 |
+
else:
|
495 |
+
from sympy.printing import sstrrepr as stringify_func
|
496 |
+
|
497 |
+
# Even if ip is not passed, double check that not in IPython shell
|
498 |
+
in_ipython = False
|
499 |
+
if ip is None:
|
500 |
+
try:
|
501 |
+
ip = get_ipython()
|
502 |
+
except NameError:
|
503 |
+
pass
|
504 |
+
else:
|
505 |
+
in_ipython = (ip is not None)
|
506 |
+
|
507 |
+
if ip and not in_ipython:
|
508 |
+
in_ipython = _is_ipython(ip)
|
509 |
+
|
510 |
+
if in_ipython and pretty_print:
|
511 |
+
try:
|
512 |
+
import IPython
|
513 |
+
# IPython 1.0 deprecates the frontend module, so we import directly
|
514 |
+
# from the terminal module to prevent a deprecation message from being
|
515 |
+
# shown.
|
516 |
+
if version_tuple(IPython.__version__) >= version_tuple('1.0'):
|
517 |
+
from IPython.terminal.interactiveshell import TerminalInteractiveShell
|
518 |
+
else:
|
519 |
+
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
|
520 |
+
from code import InteractiveConsole
|
521 |
+
except ImportError:
|
522 |
+
pass
|
523 |
+
else:
|
524 |
+
# This will be True if we are in the qtconsole or notebook
|
525 |
+
if not isinstance(ip, (InteractiveConsole, TerminalInteractiveShell)) \
|
526 |
+
and 'ipython-console' not in ''.join(sys.argv):
|
527 |
+
if use_unicode is None:
|
528 |
+
debug("init_printing: Setting use_unicode to True")
|
529 |
+
use_unicode = True
|
530 |
+
if use_latex is None:
|
531 |
+
debug("init_printing: Setting use_latex to True")
|
532 |
+
use_latex = True
|
533 |
+
|
534 |
+
if not NO_GLOBAL and not no_global:
|
535 |
+
Printer.set_global_settings(order=order, use_unicode=use_unicode,
|
536 |
+
wrap_line=wrap_line, num_columns=num_columns)
|
537 |
+
else:
|
538 |
+
_stringify_func = stringify_func
|
539 |
+
|
540 |
+
if pretty_print:
|
541 |
+
stringify_func = lambda expr, **settings: \
|
542 |
+
_stringify_func(expr, order=order,
|
543 |
+
use_unicode=use_unicode,
|
544 |
+
wrap_line=wrap_line,
|
545 |
+
num_columns=num_columns,
|
546 |
+
**settings)
|
547 |
+
else:
|
548 |
+
stringify_func = \
|
549 |
+
lambda expr, **settings: _stringify_func(
|
550 |
+
expr, order=order, **settings)
|
551 |
+
|
552 |
+
if in_ipython:
|
553 |
+
mode_in_settings = settings.pop("mode", None)
|
554 |
+
if mode_in_settings:
|
555 |
+
debug("init_printing: Mode is not able to be set due to internals"
|
556 |
+
"of IPython printing")
|
557 |
+
_init_ipython_printing(ip, stringify_func, use_latex, euler,
|
558 |
+
forecolor, backcolor, fontsize, latex_mode,
|
559 |
+
print_builtin, latex_printer, scale,
|
560 |
+
**settings)
|
561 |
+
else:
|
562 |
+
_init_python_printing(stringify_func, **settings)
|
llmeval-env/lib/python3.10/site-packages/sympy/interactive/session.py
ADDED
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tools for setting up interactive sessions. """
|
2 |
+
|
3 |
+
from sympy.external.gmpy import GROUND_TYPES
|
4 |
+
from sympy.external.importtools import version_tuple
|
5 |
+
|
6 |
+
from sympy.interactive.printing import init_printing
|
7 |
+
|
8 |
+
from sympy.utilities.misc import ARCH
|
9 |
+
|
10 |
+
preexec_source = """\
|
11 |
+
from sympy import *
|
12 |
+
x, y, z, t = symbols('x y z t')
|
13 |
+
k, m, n = symbols('k m n', integer=True)
|
14 |
+
f, g, h = symbols('f g h', cls=Function)
|
15 |
+
init_printing()
|
16 |
+
"""
|
17 |
+
|
18 |
+
verbose_message = """\
|
19 |
+
These commands were executed:
|
20 |
+
%(source)s
|
21 |
+
Documentation can be found at https://docs.sympy.org/%(version)s
|
22 |
+
"""
|
23 |
+
|
24 |
+
no_ipython = """\
|
25 |
+
Could not locate IPython. Having IPython installed is greatly recommended.
|
26 |
+
See http://ipython.scipy.org for more details. If you use Debian/Ubuntu,
|
27 |
+
just install the 'ipython' package and start isympy again.
|
28 |
+
"""
|
29 |
+
|
30 |
+
|
31 |
+
def _make_message(ipython=True, quiet=False, source=None):
|
32 |
+
"""Create a banner for an interactive session. """
|
33 |
+
from sympy import __version__ as sympy_version
|
34 |
+
from sympy import SYMPY_DEBUG
|
35 |
+
|
36 |
+
import sys
|
37 |
+
import os
|
38 |
+
|
39 |
+
if quiet:
|
40 |
+
return ""
|
41 |
+
|
42 |
+
python_version = "%d.%d.%d" % sys.version_info[:3]
|
43 |
+
|
44 |
+
if ipython:
|
45 |
+
shell_name = "IPython"
|
46 |
+
else:
|
47 |
+
shell_name = "Python"
|
48 |
+
|
49 |
+
info = ['ground types: %s' % GROUND_TYPES]
|
50 |
+
|
51 |
+
cache = os.getenv('SYMPY_USE_CACHE')
|
52 |
+
|
53 |
+
if cache is not None and cache.lower() == 'no':
|
54 |
+
info.append('cache: off')
|
55 |
+
|
56 |
+
if SYMPY_DEBUG:
|
57 |
+
info.append('debugging: on')
|
58 |
+
|
59 |
+
args = shell_name, sympy_version, python_version, ARCH, ', '.join(info)
|
60 |
+
message = "%s console for SymPy %s (Python %s-%s) (%s)\n" % args
|
61 |
+
|
62 |
+
if source is None:
|
63 |
+
source = preexec_source
|
64 |
+
|
65 |
+
_source = ""
|
66 |
+
|
67 |
+
for line in source.split('\n')[:-1]:
|
68 |
+
if not line:
|
69 |
+
_source += '\n'
|
70 |
+
else:
|
71 |
+
_source += '>>> ' + line + '\n'
|
72 |
+
|
73 |
+
doc_version = sympy_version
|
74 |
+
if 'dev' in doc_version:
|
75 |
+
doc_version = "dev"
|
76 |
+
else:
|
77 |
+
doc_version = "%s/" % doc_version
|
78 |
+
|
79 |
+
message += '\n' + verbose_message % {'source': _source,
|
80 |
+
'version': doc_version}
|
81 |
+
|
82 |
+
return message
|
83 |
+
|
84 |
+
|
85 |
+
def int_to_Integer(s):
|
86 |
+
"""
|
87 |
+
Wrap integer literals with Integer.
|
88 |
+
|
89 |
+
This is based on the decistmt example from
|
90 |
+
https://docs.python.org/3/library/tokenize.html.
|
91 |
+
|
92 |
+
Only integer literals are converted. Float literals are left alone.
|
93 |
+
|
94 |
+
Examples
|
95 |
+
========
|
96 |
+
|
97 |
+
>>> from sympy import Integer # noqa: F401
|
98 |
+
>>> from sympy.interactive.session import int_to_Integer
|
99 |
+
>>> s = '1.2 + 1/2 - 0x12 + a1'
|
100 |
+
>>> int_to_Integer(s)
|
101 |
+
'1.2 +Integer (1 )/Integer (2 )-Integer (0x12 )+a1 '
|
102 |
+
>>> s = 'print (1/2)'
|
103 |
+
>>> int_to_Integer(s)
|
104 |
+
'print (Integer (1 )/Integer (2 ))'
|
105 |
+
>>> exec(s)
|
106 |
+
0.5
|
107 |
+
>>> exec(int_to_Integer(s))
|
108 |
+
1/2
|
109 |
+
"""
|
110 |
+
from tokenize import generate_tokens, untokenize, NUMBER, NAME, OP
|
111 |
+
from io import StringIO
|
112 |
+
|
113 |
+
def _is_int(num):
|
114 |
+
"""
|
115 |
+
Returns true if string value num (with token NUMBER) represents an integer.
|
116 |
+
"""
|
117 |
+
# XXX: Is there something in the standard library that will do this?
|
118 |
+
if '.' in num or 'j' in num.lower() or 'e' in num.lower():
|
119 |
+
return False
|
120 |
+
return True
|
121 |
+
|
122 |
+
result = []
|
123 |
+
g = generate_tokens(StringIO(s).readline) # tokenize the string
|
124 |
+
for toknum, tokval, _, _, _ in g:
|
125 |
+
if toknum == NUMBER and _is_int(tokval): # replace NUMBER tokens
|
126 |
+
result.extend([
|
127 |
+
(NAME, 'Integer'),
|
128 |
+
(OP, '('),
|
129 |
+
(NUMBER, tokval),
|
130 |
+
(OP, ')')
|
131 |
+
])
|
132 |
+
else:
|
133 |
+
result.append((toknum, tokval))
|
134 |
+
return untokenize(result)
|
135 |
+
|
136 |
+
|
137 |
+
def enable_automatic_int_sympification(shell):
|
138 |
+
"""
|
139 |
+
Allow IPython to automatically convert integer literals to Integer.
|
140 |
+
"""
|
141 |
+
import ast
|
142 |
+
old_run_cell = shell.run_cell
|
143 |
+
|
144 |
+
def my_run_cell(cell, *args, **kwargs):
|
145 |
+
try:
|
146 |
+
# Check the cell for syntax errors. This way, the syntax error
|
147 |
+
# will show the original input, not the transformed input. The
|
148 |
+
# downside here is that IPython magic like %timeit will not work
|
149 |
+
# with transformed input (but on the other hand, IPython magic
|
150 |
+
# that doesn't expect transformed input will continue to work).
|
151 |
+
ast.parse(cell)
|
152 |
+
except SyntaxError:
|
153 |
+
pass
|
154 |
+
else:
|
155 |
+
cell = int_to_Integer(cell)
|
156 |
+
return old_run_cell(cell, *args, **kwargs)
|
157 |
+
|
158 |
+
shell.run_cell = my_run_cell
|
159 |
+
|
160 |
+
|
161 |
+
def enable_automatic_symbols(shell):
|
162 |
+
"""Allow IPython to automatically create symbols (``isympy -a``). """
|
163 |
+
# XXX: This should perhaps use tokenize, like int_to_Integer() above.
|
164 |
+
# This would avoid re-executing the code, which can lead to subtle
|
165 |
+
# issues. For example:
|
166 |
+
#
|
167 |
+
# In [1]: a = 1
|
168 |
+
#
|
169 |
+
# In [2]: for i in range(10):
|
170 |
+
# ...: a += 1
|
171 |
+
# ...:
|
172 |
+
#
|
173 |
+
# In [3]: a
|
174 |
+
# Out[3]: 11
|
175 |
+
#
|
176 |
+
# In [4]: a = 1
|
177 |
+
#
|
178 |
+
# In [5]: for i in range(10):
|
179 |
+
# ...: a += 1
|
180 |
+
# ...: print b
|
181 |
+
# ...:
|
182 |
+
# b
|
183 |
+
# b
|
184 |
+
# b
|
185 |
+
# b
|
186 |
+
# b
|
187 |
+
# b
|
188 |
+
# b
|
189 |
+
# b
|
190 |
+
# b
|
191 |
+
# b
|
192 |
+
#
|
193 |
+
# In [6]: a
|
194 |
+
# Out[6]: 12
|
195 |
+
#
|
196 |
+
# Note how the for loop is executed again because `b` was not defined, but `a`
|
197 |
+
# was already incremented once, so the result is that it is incremented
|
198 |
+
# multiple times.
|
199 |
+
|
200 |
+
import re
|
201 |
+
re_nameerror = re.compile(
|
202 |
+
"name '(?P<symbol>[A-Za-z_][A-Za-z0-9_]*)' is not defined")
|
203 |
+
|
204 |
+
def _handler(self, etype, value, tb, tb_offset=None):
|
205 |
+
"""Handle :exc:`NameError` exception and allow injection of missing symbols. """
|
206 |
+
if etype is NameError and tb.tb_next and not tb.tb_next.tb_next:
|
207 |
+
match = re_nameerror.match(str(value))
|
208 |
+
|
209 |
+
if match is not None:
|
210 |
+
# XXX: Make sure Symbol is in scope. Otherwise you'll get infinite recursion.
|
211 |
+
self.run_cell("%(symbol)s = Symbol('%(symbol)s')" %
|
212 |
+
{'symbol': match.group("symbol")}, store_history=False)
|
213 |
+
|
214 |
+
try:
|
215 |
+
code = self.user_ns['In'][-1]
|
216 |
+
except (KeyError, IndexError):
|
217 |
+
pass
|
218 |
+
else:
|
219 |
+
self.run_cell(code, store_history=False)
|
220 |
+
return None
|
221 |
+
finally:
|
222 |
+
self.run_cell("del %s" % match.group("symbol"),
|
223 |
+
store_history=False)
|
224 |
+
|
225 |
+
stb = self.InteractiveTB.structured_traceback(
|
226 |
+
etype, value, tb, tb_offset=tb_offset)
|
227 |
+
self._showtraceback(etype, value, stb)
|
228 |
+
|
229 |
+
shell.set_custom_exc((NameError,), _handler)
|
230 |
+
|
231 |
+
|
232 |
+
def init_ipython_session(shell=None, argv=[], auto_symbols=False, auto_int_to_Integer=False):
|
233 |
+
"""Construct new IPython session. """
|
234 |
+
import IPython
|
235 |
+
|
236 |
+
if version_tuple(IPython.__version__) >= version_tuple('0.11'):
|
237 |
+
if not shell:
|
238 |
+
# use an app to parse the command line, and init config
|
239 |
+
# IPython 1.0 deprecates the frontend module, so we import directly
|
240 |
+
# from the terminal module to prevent a deprecation message from being
|
241 |
+
# shown.
|
242 |
+
if version_tuple(IPython.__version__) >= version_tuple('1.0'):
|
243 |
+
from IPython.terminal import ipapp
|
244 |
+
else:
|
245 |
+
from IPython.frontend.terminal import ipapp
|
246 |
+
app = ipapp.TerminalIPythonApp()
|
247 |
+
|
248 |
+
# don't draw IPython banner during initialization:
|
249 |
+
app.display_banner = False
|
250 |
+
app.initialize(argv)
|
251 |
+
|
252 |
+
shell = app.shell
|
253 |
+
|
254 |
+
if auto_symbols:
|
255 |
+
enable_automatic_symbols(shell)
|
256 |
+
if auto_int_to_Integer:
|
257 |
+
enable_automatic_int_sympification(shell)
|
258 |
+
|
259 |
+
return shell
|
260 |
+
else:
|
261 |
+
from IPython.Shell import make_IPython
|
262 |
+
return make_IPython(argv)
|
263 |
+
|
264 |
+
|
265 |
+
def init_python_session():
|
266 |
+
"""Construct new Python session. """
|
267 |
+
from code import InteractiveConsole
|
268 |
+
|
269 |
+
class SymPyConsole(InteractiveConsole):
|
270 |
+
"""An interactive console with readline support. """
|
271 |
+
|
272 |
+
def __init__(self):
|
273 |
+
ns_locals = {}
|
274 |
+
InteractiveConsole.__init__(self, locals=ns_locals)
|
275 |
+
try:
|
276 |
+
import rlcompleter
|
277 |
+
import readline
|
278 |
+
except ImportError:
|
279 |
+
pass
|
280 |
+
else:
|
281 |
+
import os
|
282 |
+
import atexit
|
283 |
+
|
284 |
+
readline.set_completer(rlcompleter.Completer(ns_locals).complete)
|
285 |
+
readline.parse_and_bind('tab: complete')
|
286 |
+
|
287 |
+
if hasattr(readline, 'read_history_file'):
|
288 |
+
history = os.path.expanduser('~/.sympy-history')
|
289 |
+
|
290 |
+
try:
|
291 |
+
readline.read_history_file(history)
|
292 |
+
except OSError:
|
293 |
+
pass
|
294 |
+
|
295 |
+
atexit.register(readline.write_history_file, history)
|
296 |
+
|
297 |
+
return SymPyConsole()
|
298 |
+
|
299 |
+
|
300 |
+
def init_session(ipython=None, pretty_print=True, order=None,
|
301 |
+
use_unicode=None, use_latex=None, quiet=False, auto_symbols=False,
|
302 |
+
auto_int_to_Integer=False, str_printer=None, pretty_printer=None,
|
303 |
+
latex_printer=None, argv=[]):
|
304 |
+
"""
|
305 |
+
Initialize an embedded IPython or Python session. The IPython session is
|
306 |
+
initiated with the --pylab option, without the numpy imports, so that
|
307 |
+
matplotlib plotting can be interactive.
|
308 |
+
|
309 |
+
Parameters
|
310 |
+
==========
|
311 |
+
|
312 |
+
pretty_print: boolean
|
313 |
+
If True, use pretty_print to stringify;
|
314 |
+
if False, use sstrrepr to stringify.
|
315 |
+
order: string or None
|
316 |
+
There are a few different settings for this parameter:
|
317 |
+
lex (default), which is lexographic order;
|
318 |
+
grlex, which is graded lexographic order;
|
319 |
+
grevlex, which is reversed graded lexographic order;
|
320 |
+
old, which is used for compatibility reasons and for long expressions;
|
321 |
+
None, which sets it to lex.
|
322 |
+
use_unicode: boolean or None
|
323 |
+
If True, use unicode characters;
|
324 |
+
if False, do not use unicode characters.
|
325 |
+
use_latex: boolean or None
|
326 |
+
If True, use latex rendering if IPython GUI's;
|
327 |
+
if False, do not use latex rendering.
|
328 |
+
quiet: boolean
|
329 |
+
If True, init_session will not print messages regarding its status;
|
330 |
+
if False, init_session will print messages regarding its status.
|
331 |
+
auto_symbols: boolean
|
332 |
+
If True, IPython will automatically create symbols for you.
|
333 |
+
If False, it will not.
|
334 |
+
The default is False.
|
335 |
+
auto_int_to_Integer: boolean
|
336 |
+
If True, IPython will automatically wrap int literals with Integer, so
|
337 |
+
that things like 1/2 give Rational(1, 2).
|
338 |
+
If False, it will not.
|
339 |
+
The default is False.
|
340 |
+
ipython: boolean or None
|
341 |
+
If True, printing will initialize for an IPython console;
|
342 |
+
if False, printing will initialize for a normal console;
|
343 |
+
The default is None, which automatically determines whether we are in
|
344 |
+
an ipython instance or not.
|
345 |
+
str_printer: function, optional, default=None
|
346 |
+
A custom string printer function. This should mimic
|
347 |
+
sympy.printing.sstrrepr().
|
348 |
+
pretty_printer: function, optional, default=None
|
349 |
+
A custom pretty printer. This should mimic sympy.printing.pretty().
|
350 |
+
latex_printer: function, optional, default=None
|
351 |
+
A custom LaTeX printer. This should mimic sympy.printing.latex()
|
352 |
+
This should mimic sympy.printing.latex().
|
353 |
+
argv: list of arguments for IPython
|
354 |
+
See sympy.bin.isympy for options that can be used to initialize IPython.
|
355 |
+
|
356 |
+
See Also
|
357 |
+
========
|
358 |
+
|
359 |
+
sympy.interactive.printing.init_printing: for examples and the rest of the parameters.
|
360 |
+
|
361 |
+
|
362 |
+
Examples
|
363 |
+
========
|
364 |
+
|
365 |
+
>>> from sympy import init_session, Symbol, sin, sqrt
|
366 |
+
>>> sin(x) #doctest: +SKIP
|
367 |
+
NameError: name 'x' is not defined
|
368 |
+
>>> init_session() #doctest: +SKIP
|
369 |
+
>>> sin(x) #doctest: +SKIP
|
370 |
+
sin(x)
|
371 |
+
>>> sqrt(5) #doctest: +SKIP
|
372 |
+
___
|
373 |
+
\\/ 5
|
374 |
+
>>> init_session(pretty_print=False) #doctest: +SKIP
|
375 |
+
>>> sqrt(5) #doctest: +SKIP
|
376 |
+
sqrt(5)
|
377 |
+
>>> y + x + y**2 + x**2 #doctest: +SKIP
|
378 |
+
x**2 + x + y**2 + y
|
379 |
+
>>> init_session(order='grlex') #doctest: +SKIP
|
380 |
+
>>> y + x + y**2 + x**2 #doctest: +SKIP
|
381 |
+
x**2 + y**2 + x + y
|
382 |
+
>>> init_session(order='grevlex') #doctest: +SKIP
|
383 |
+
>>> y * x**2 + x * y**2 #doctest: +SKIP
|
384 |
+
x**2*y + x*y**2
|
385 |
+
>>> init_session(order='old') #doctest: +SKIP
|
386 |
+
>>> x**2 + y**2 + x + y #doctest: +SKIP
|
387 |
+
x + y + x**2 + y**2
|
388 |
+
>>> theta = Symbol('theta') #doctest: +SKIP
|
389 |
+
>>> theta #doctest: +SKIP
|
390 |
+
theta
|
391 |
+
>>> init_session(use_unicode=True) #doctest: +SKIP
|
392 |
+
>>> theta # doctest: +SKIP
|
393 |
+
\u03b8
|
394 |
+
"""
|
395 |
+
import sys
|
396 |
+
|
397 |
+
in_ipython = False
|
398 |
+
|
399 |
+
if ipython is not False:
|
400 |
+
try:
|
401 |
+
import IPython
|
402 |
+
except ImportError:
|
403 |
+
if ipython is True:
|
404 |
+
raise RuntimeError("IPython is not available on this system")
|
405 |
+
ip = None
|
406 |
+
else:
|
407 |
+
try:
|
408 |
+
from IPython import get_ipython
|
409 |
+
ip = get_ipython()
|
410 |
+
except ImportError:
|
411 |
+
ip = None
|
412 |
+
in_ipython = bool(ip)
|
413 |
+
if ipython is None:
|
414 |
+
ipython = in_ipython
|
415 |
+
|
416 |
+
if ipython is False:
|
417 |
+
ip = init_python_session()
|
418 |
+
mainloop = ip.interact
|
419 |
+
else:
|
420 |
+
ip = init_ipython_session(ip, argv=argv, auto_symbols=auto_symbols,
|
421 |
+
auto_int_to_Integer=auto_int_to_Integer)
|
422 |
+
|
423 |
+
if version_tuple(IPython.__version__) >= version_tuple('0.11'):
|
424 |
+
# runsource is gone, use run_cell instead, which doesn't
|
425 |
+
# take a symbol arg. The second arg is `store_history`,
|
426 |
+
# and False means don't add the line to IPython's history.
|
427 |
+
ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
|
428 |
+
|
429 |
+
# Enable interactive plotting using pylab.
|
430 |
+
try:
|
431 |
+
ip.enable_pylab(import_all=False)
|
432 |
+
except Exception:
|
433 |
+
# Causes an import error if matplotlib is not installed.
|
434 |
+
# Causes other errors (depending on the backend) if there
|
435 |
+
# is no display, or if there is some problem in the
|
436 |
+
# backend, so we have a bare "except Exception" here
|
437 |
+
pass
|
438 |
+
if not in_ipython:
|
439 |
+
mainloop = ip.mainloop
|
440 |
+
|
441 |
+
if auto_symbols and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')):
|
442 |
+
raise RuntimeError("automatic construction of symbols is possible only in IPython 0.11 or above")
|
443 |
+
if auto_int_to_Integer and (not ipython or version_tuple(IPython.__version__) < version_tuple('0.11')):
|
444 |
+
raise RuntimeError("automatic int to Integer transformation is possible only in IPython 0.11 or above")
|
445 |
+
|
446 |
+
_preexec_source = preexec_source
|
447 |
+
|
448 |
+
ip.runsource(_preexec_source, symbol='exec')
|
449 |
+
init_printing(pretty_print=pretty_print, order=order,
|
450 |
+
use_unicode=use_unicode, use_latex=use_latex, ip=ip,
|
451 |
+
str_printer=str_printer, pretty_printer=pretty_printer,
|
452 |
+
latex_printer=latex_printer)
|
453 |
+
|
454 |
+
message = _make_message(ipython, quiet, _preexec_source)
|
455 |
+
|
456 |
+
if not in_ipython:
|
457 |
+
print(message)
|
458 |
+
mainloop()
|
459 |
+
sys.exit('Exiting ...')
|
460 |
+
else:
|
461 |
+
print(message)
|
462 |
+
import atexit
|
463 |
+
atexit.register(lambda: print("Exiting ...\n"))
|
llmeval-env/lib/python3.10/site-packages/sympy/interactive/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/interactive/traversal.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from sympy.core.basic import Basic
|
2 |
+
from sympy.printing import pprint
|
3 |
+
|
4 |
+
import random
|
5 |
+
|
6 |
+
def interactive_traversal(expr):
|
7 |
+
"""Traverse a tree asking a user which branch to choose. """
|
8 |
+
|
9 |
+
RED, BRED = '\033[0;31m', '\033[1;31m'
|
10 |
+
GREEN, BGREEN = '\033[0;32m', '\033[1;32m'
|
11 |
+
YELLOW, BYELLOW = '\033[0;33m', '\033[1;33m' # noqa
|
12 |
+
BLUE, BBLUE = '\033[0;34m', '\033[1;34m' # noqa
|
13 |
+
MAGENTA, BMAGENTA = '\033[0;35m', '\033[1;35m'# noqa
|
14 |
+
CYAN, BCYAN = '\033[0;36m', '\033[1;36m' # noqa
|
15 |
+
END = '\033[0m'
|
16 |
+
|
17 |
+
def cprint(*args):
|
18 |
+
print("".join(map(str, args)) + END)
|
19 |
+
|
20 |
+
def _interactive_traversal(expr, stage):
|
21 |
+
if stage > 0:
|
22 |
+
print()
|
23 |
+
|
24 |
+
cprint("Current expression (stage ", BYELLOW, stage, END, "):")
|
25 |
+
print(BCYAN)
|
26 |
+
pprint(expr)
|
27 |
+
print(END)
|
28 |
+
|
29 |
+
if isinstance(expr, Basic):
|
30 |
+
if expr.is_Add:
|
31 |
+
args = expr.as_ordered_terms()
|
32 |
+
elif expr.is_Mul:
|
33 |
+
args = expr.as_ordered_factors()
|
34 |
+
else:
|
35 |
+
args = expr.args
|
36 |
+
elif hasattr(expr, "__iter__"):
|
37 |
+
args = list(expr)
|
38 |
+
else:
|
39 |
+
return expr
|
40 |
+
|
41 |
+
n_args = len(args)
|
42 |
+
|
43 |
+
if not n_args:
|
44 |
+
return expr
|
45 |
+
|
46 |
+
for i, arg in enumerate(args):
|
47 |
+
cprint(GREEN, "[", BGREEN, i, GREEN, "] ", BLUE, type(arg), END)
|
48 |
+
pprint(arg)
|
49 |
+
print()
|
50 |
+
|
51 |
+
if n_args == 1:
|
52 |
+
choices = '0'
|
53 |
+
else:
|
54 |
+
choices = '0-%d' % (n_args - 1)
|
55 |
+
|
56 |
+
try:
|
57 |
+
choice = input("Your choice [%s,f,l,r,d,?]: " % choices)
|
58 |
+
except EOFError:
|
59 |
+
result = expr
|
60 |
+
print()
|
61 |
+
else:
|
62 |
+
if choice == '?':
|
63 |
+
cprint(RED, "%s - select subexpression with the given index" %
|
64 |
+
choices)
|
65 |
+
cprint(RED, "f - select the first subexpression")
|
66 |
+
cprint(RED, "l - select the last subexpression")
|
67 |
+
cprint(RED, "r - select a random subexpression")
|
68 |
+
cprint(RED, "d - done\n")
|
69 |
+
|
70 |
+
result = _interactive_traversal(expr, stage)
|
71 |
+
elif choice in ('d', ''):
|
72 |
+
result = expr
|
73 |
+
elif choice == 'f':
|
74 |
+
result = _interactive_traversal(args[0], stage + 1)
|
75 |
+
elif choice == 'l':
|
76 |
+
result = _interactive_traversal(args[-1], stage + 1)
|
77 |
+
elif choice == 'r':
|
78 |
+
result = _interactive_traversal(random.choice(args), stage + 1)
|
79 |
+
else:
|
80 |
+
try:
|
81 |
+
choice = int(choice)
|
82 |
+
except ValueError:
|
83 |
+
cprint(BRED,
|
84 |
+
"Choice must be a number in %s range\n" % choices)
|
85 |
+
result = _interactive_traversal(expr, stage)
|
86 |
+
else:
|
87 |
+
if choice < 0 or choice >= n_args:
|
88 |
+
cprint(BRED, "Choice must be in %s range\n" % choices)
|
89 |
+
result = _interactive_traversal(expr, stage)
|
90 |
+
else:
|
91 |
+
result = _interactive_traversal(args[choice], stage + 1)
|
92 |
+
|
93 |
+
return result
|
94 |
+
|
95 |
+
return _interactive_traversal(expr, 0)
|
llmeval-env/lib/python3.10/site-packages/sympy/simplify/tests/__pycache__/test_combsimp.cpython-310.pyc
ADDED
Binary file (2.76 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/compound_rv.cpython-310.pyc
ADDED
Binary file (8.3 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/crv.cpython-310.pyc
ADDED
Binary file (20.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/crv_types.cpython-310.pyc
ADDED
Binary file (127 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/drv.cpython-310.pyc
ADDED
Binary file (13.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/drv_types.cpython-310.pyc
ADDED
Binary file (21.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/error_prop.cpython-310.pyc
ADDED
Binary file (3.42 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/frv.cpython-310.pyc
ADDED
Binary file (23.2 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/frv_types.cpython-310.pyc
ADDED
Binary file (27.6 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv.cpython-310.pyc
ADDED
Binary file (18.7 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/joint_rv_types.cpython-310.pyc
ADDED
Binary file (31.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/matrix_distributions.cpython-310.pyc
ADDED
Binary file (19 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix.cpython-310.pyc
ADDED
Binary file (1.45 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/random_matrix_models.cpython-310.pyc
ADDED
Binary file (16.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/rv.cpython-310.pyc
ADDED
Binary file (55.9 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/rv_interface.cpython-310.pyc
ADDED
Binary file (14 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process.cpython-310.pyc
ADDED
Binary file (2.73 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/stochastic_process_types.cpython-310.pyc
ADDED
Binary file (77.8 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_multivariate_probability.cpython-310.pyc
ADDED
Binary file (9.5 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/__pycache__/symbolic_probability.cpython-310.pyc
ADDED
Binary file (20.8 kB). View file
|
|
llmeval-env/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()
|
llmeval-env/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)
|
llmeval-env/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
|
llmeval-env/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)
|
llmeval-env/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 {k: self.p for k in self.set}
|
153 |
+
|
154 |
+
@property
|
155 |
+
def set(self):
|
156 |
+
return set(self.args)
|
157 |
+
|
158 |
+
def pmf(self, x):
|
159 |
+
if x in self.args:
|
160 |
+
return self.p
|
161 |
+
else:
|
162 |
+
return S.Zero
|
163 |
+
|
164 |
+
|
165 |
+
def DiscreteUniform(name, items):
|
166 |
+
r"""
|
167 |
+
Create a Finite Random Variable representing a uniform distribution over
|
168 |
+
the input set.
|
169 |
+
|
170 |
+
Parameters
|
171 |
+
==========
|
172 |
+
|
173 |
+
items : list/tuple
|
174 |
+
Items over which Uniform distribution is to be made
|
175 |
+
|
176 |
+
Examples
|
177 |
+
========
|
178 |
+
|
179 |
+
>>> from sympy.stats import DiscreteUniform, density
|
180 |
+
>>> from sympy import symbols
|
181 |
+
|
182 |
+
>>> X = DiscreteUniform('X', symbols('a b c')) # equally likely over a, b, c
|
183 |
+
>>> density(X).dict
|
184 |
+
{a: 1/3, b: 1/3, c: 1/3}
|
185 |
+
|
186 |
+
>>> Y = DiscreteUniform('Y', list(range(5))) # distribution over a range
|
187 |
+
>>> density(Y).dict
|
188 |
+
{0: 1/5, 1: 1/5, 2: 1/5, 3: 1/5, 4: 1/5}
|
189 |
+
|
190 |
+
Returns
|
191 |
+
=======
|
192 |
+
|
193 |
+
RandomSymbol
|
194 |
+
|
195 |
+
References
|
196 |
+
==========
|
197 |
+
|
198 |
+
.. [1] https://en.wikipedia.org/wiki/Discrete_uniform_distribution
|
199 |
+
.. [2] https://mathworld.wolfram.com/DiscreteUniformDistribution.html
|
200 |
+
|
201 |
+
"""
|
202 |
+
return rv(name, DiscreteUniformDistribution, *items)
|
203 |
+
|
204 |
+
|
205 |
+
class DieDistribution(SingleFiniteDistribution):
|
206 |
+
_argnames = ('sides',)
|
207 |
+
|
208 |
+
@staticmethod
|
209 |
+
def check(sides):
|
210 |
+
_value_check((sides.is_positive, sides.is_integer),
|
211 |
+
"number of sides must be a positive integer.")
|
212 |
+
|
213 |
+
@property
|
214 |
+
def is_symbolic(self):
|
215 |
+
return not self.sides.is_number
|
216 |
+
|
217 |
+
@property
|
218 |
+
def high(self):
|
219 |
+
return self.sides
|
220 |
+
|
221 |
+
@property
|
222 |
+
def low(self):
|
223 |
+
return S.One
|
224 |
+
|
225 |
+
@property
|
226 |
+
def set(self):
|
227 |
+
if self.is_symbolic:
|
228 |
+
return Intersection(S.Naturals0, Interval(0, self.sides))
|
229 |
+
return set(map(Integer, range(1, self.sides + 1)))
|
230 |
+
|
231 |
+
def pmf(self, x):
|
232 |
+
x = sympify(x)
|
233 |
+
if not (x.is_number or x.is_Symbol or is_random(x)):
|
234 |
+
raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or "
|
235 |
+
"'RandomSymbol' not %s" % (type(x)))
|
236 |
+
cond = Ge(x, 1) & Le(x, self.sides) & Contains(x, S.Integers)
|
237 |
+
return Piecewise((S.One/self.sides, cond), (S.Zero, True))
|
238 |
+
|
239 |
+
def Die(name, sides=6):
|
240 |
+
r"""
|
241 |
+
Create a Finite Random Variable representing a fair die.
|
242 |
+
|
243 |
+
Parameters
|
244 |
+
==========
|
245 |
+
|
246 |
+
sides : Integer
|
247 |
+
Represents the number of sides of the Die, by default is 6
|
248 |
+
|
249 |
+
Examples
|
250 |
+
========
|
251 |
+
|
252 |
+
>>> from sympy.stats import Die, density
|
253 |
+
>>> from sympy import Symbol
|
254 |
+
|
255 |
+
>>> D6 = Die('D6', 6) # Six sided Die
|
256 |
+
>>> density(D6).dict
|
257 |
+
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
|
258 |
+
|
259 |
+
>>> D4 = Die('D4', 4) # Four sided Die
|
260 |
+
>>> density(D4).dict
|
261 |
+
{1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4}
|
262 |
+
|
263 |
+
>>> n = Symbol('n', positive=True, integer=True)
|
264 |
+
>>> Dn = Die('Dn', n) # n sided Die
|
265 |
+
>>> density(Dn).dict
|
266 |
+
Density(DieDistribution(n))
|
267 |
+
>>> density(Dn).dict.subs(n, 4).doit()
|
268 |
+
{1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4}
|
269 |
+
|
270 |
+
Returns
|
271 |
+
=======
|
272 |
+
|
273 |
+
RandomSymbol
|
274 |
+
"""
|
275 |
+
|
276 |
+
return rv(name, DieDistribution, sides)
|
277 |
+
|
278 |
+
|
279 |
+
class BernoulliDistribution(SingleFiniteDistribution):
|
280 |
+
_argnames = ('p', 'succ', 'fail')
|
281 |
+
|
282 |
+
@staticmethod
|
283 |
+
def check(p, succ, fail):
|
284 |
+
_value_check((p >= 0, p <= 1),
|
285 |
+
"p should be in range [0, 1].")
|
286 |
+
|
287 |
+
@property
|
288 |
+
def set(self):
|
289 |
+
return {self.succ, self.fail}
|
290 |
+
|
291 |
+
def pmf(self, x):
|
292 |
+
if isinstance(self.succ, Symbol) and isinstance(self.fail, Symbol):
|
293 |
+
return Piecewise((self.p, x == self.succ),
|
294 |
+
(1 - self.p, x == self.fail),
|
295 |
+
(S.Zero, True))
|
296 |
+
return Piecewise((self.p, Eq(x, self.succ)),
|
297 |
+
(1 - self.p, Eq(x, self.fail)),
|
298 |
+
(S.Zero, True))
|
299 |
+
|
300 |
+
|
301 |
+
def Bernoulli(name, p, succ=1, fail=0):
|
302 |
+
r"""
|
303 |
+
Create a Finite Random Variable representing a Bernoulli process.
|
304 |
+
|
305 |
+
Parameters
|
306 |
+
==========
|
307 |
+
|
308 |
+
p : Rational number between 0 and 1
|
309 |
+
Represents probability of success
|
310 |
+
succ : Integer/symbol/string
|
311 |
+
Represents event of success
|
312 |
+
fail : Integer/symbol/string
|
313 |
+
Represents event of failure
|
314 |
+
|
315 |
+
Examples
|
316 |
+
========
|
317 |
+
|
318 |
+
>>> from sympy.stats import Bernoulli, density
|
319 |
+
>>> from sympy import S
|
320 |
+
|
321 |
+
>>> X = Bernoulli('X', S(3)/4) # 1-0 Bernoulli variable, probability = 3/4
|
322 |
+
>>> density(X).dict
|
323 |
+
{0: 1/4, 1: 3/4}
|
324 |
+
|
325 |
+
>>> X = Bernoulli('X', S.Half, 'Heads', 'Tails') # A fair coin toss
|
326 |
+
>>> density(X).dict
|
327 |
+
{Heads: 1/2, Tails: 1/2}
|
328 |
+
|
329 |
+
Returns
|
330 |
+
=======
|
331 |
+
|
332 |
+
RandomSymbol
|
333 |
+
|
334 |
+
References
|
335 |
+
==========
|
336 |
+
|
337 |
+
.. [1] https://en.wikipedia.org/wiki/Bernoulli_distribution
|
338 |
+
.. [2] https://mathworld.wolfram.com/BernoulliDistribution.html
|
339 |
+
|
340 |
+
"""
|
341 |
+
|
342 |
+
return rv(name, BernoulliDistribution, p, succ, fail)
|
343 |
+
|
344 |
+
|
345 |
+
def Coin(name, p=S.Half):
|
346 |
+
r"""
|
347 |
+
Create a Finite Random Variable representing a Coin toss.
|
348 |
+
|
349 |
+
Parameters
|
350 |
+
==========
|
351 |
+
|
352 |
+
p : Rational Number between 0 and 1
|
353 |
+
Represents probability of getting "Heads", by default is Half
|
354 |
+
|
355 |
+
Examples
|
356 |
+
========
|
357 |
+
|
358 |
+
>>> from sympy.stats import Coin, density
|
359 |
+
>>> from sympy import Rational
|
360 |
+
|
361 |
+
>>> C = Coin('C') # A fair coin toss
|
362 |
+
>>> density(C).dict
|
363 |
+
{H: 1/2, T: 1/2}
|
364 |
+
|
365 |
+
>>> C2 = Coin('C2', Rational(3, 5)) # An unfair coin
|
366 |
+
>>> density(C2).dict
|
367 |
+
{H: 3/5, T: 2/5}
|
368 |
+
|
369 |
+
Returns
|
370 |
+
=======
|
371 |
+
|
372 |
+
RandomSymbol
|
373 |
+
|
374 |
+
See Also
|
375 |
+
========
|
376 |
+
|
377 |
+
sympy.stats.Binomial
|
378 |
+
|
379 |
+
References
|
380 |
+
==========
|
381 |
+
|
382 |
+
.. [1] https://en.wikipedia.org/wiki/Coin_flipping
|
383 |
+
|
384 |
+
"""
|
385 |
+
return rv(name, BernoulliDistribution, p, 'H', 'T')
|
386 |
+
|
387 |
+
|
388 |
+
class BinomialDistribution(SingleFiniteDistribution):
|
389 |
+
_argnames = ('n', 'p', 'succ', 'fail')
|
390 |
+
|
391 |
+
@staticmethod
|
392 |
+
def check(n, p, succ, fail):
|
393 |
+
_value_check((n.is_integer, n.is_nonnegative),
|
394 |
+
"'n' must be nonnegative integer.")
|
395 |
+
_value_check((p <= 1, p >= 0),
|
396 |
+
"p should be in range [0, 1].")
|
397 |
+
|
398 |
+
@property
|
399 |
+
def high(self):
|
400 |
+
return self.n
|
401 |
+
|
402 |
+
@property
|
403 |
+
def low(self):
|
404 |
+
return S.Zero
|
405 |
+
|
406 |
+
@property
|
407 |
+
def is_symbolic(self):
|
408 |
+
return not self.n.is_number
|
409 |
+
|
410 |
+
@property
|
411 |
+
def set(self):
|
412 |
+
if self.is_symbolic:
|
413 |
+
return Intersection(S.Naturals0, Interval(0, self.n))
|
414 |
+
return set(self.dict.keys())
|
415 |
+
|
416 |
+
def pmf(self, x):
|
417 |
+
n, p = self.n, self.p
|
418 |
+
x = sympify(x)
|
419 |
+
if not (x.is_number or x.is_Symbol or is_random(x)):
|
420 |
+
raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or "
|
421 |
+
"'RandomSymbol' not %s" % (type(x)))
|
422 |
+
cond = Ge(x, 0) & Le(x, n) & Contains(x, S.Integers)
|
423 |
+
return Piecewise((binomial(n, x) * p**x * (1 - p)**(n - x), cond), (S.Zero, True))
|
424 |
+
|
425 |
+
@property # type: ignore
|
426 |
+
@cacheit
|
427 |
+
def dict(self):
|
428 |
+
if self.is_symbolic:
|
429 |
+
return Density(self)
|
430 |
+
return {k*self.succ + (self.n-k)*self.fail: self.pmf(k)
|
431 |
+
for k in range(0, self.n + 1)}
|
432 |
+
|
433 |
+
|
434 |
+
def Binomial(name, n, p, succ=1, fail=0):
|
435 |
+
r"""
|
436 |
+
Create a Finite Random Variable representing a binomial distribution.
|
437 |
+
|
438 |
+
Parameters
|
439 |
+
==========
|
440 |
+
|
441 |
+
n : Positive Integer
|
442 |
+
Represents number of trials
|
443 |
+
p : Rational Number between 0 and 1
|
444 |
+
Represents probability of success
|
445 |
+
succ : Integer/symbol/string
|
446 |
+
Represents event of success, by default is 1
|
447 |
+
fail : Integer/symbol/string
|
448 |
+
Represents event of failure, by default is 0
|
449 |
+
|
450 |
+
Examples
|
451 |
+
========
|
452 |
+
|
453 |
+
>>> from sympy.stats import Binomial, density
|
454 |
+
>>> from sympy import S, Symbol
|
455 |
+
|
456 |
+
>>> X = Binomial('X', 4, S.Half) # Four "coin flips"
|
457 |
+
>>> density(X).dict
|
458 |
+
{0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16}
|
459 |
+
|
460 |
+
>>> n = Symbol('n', positive=True, integer=True)
|
461 |
+
>>> p = Symbol('p', positive=True)
|
462 |
+
>>> X = Binomial('X', n, S.Half) # n "coin flips"
|
463 |
+
>>> density(X).dict
|
464 |
+
Density(BinomialDistribution(n, 1/2, 1, 0))
|
465 |
+
>>> density(X).dict.subs(n, 4).doit()
|
466 |
+
{0: 1/16, 1: 1/4, 2: 3/8, 3: 1/4, 4: 1/16}
|
467 |
+
|
468 |
+
Returns
|
469 |
+
=======
|
470 |
+
|
471 |
+
RandomSymbol
|
472 |
+
|
473 |
+
References
|
474 |
+
==========
|
475 |
+
|
476 |
+
.. [1] https://en.wikipedia.org/wiki/Binomial_distribution
|
477 |
+
.. [2] https://mathworld.wolfram.com/BinomialDistribution.html
|
478 |
+
|
479 |
+
"""
|
480 |
+
|
481 |
+
return rv(name, BinomialDistribution, n, p, succ, fail)
|
482 |
+
|
483 |
+
#-------------------------------------------------------------------------------
|
484 |
+
# Beta-binomial distribution ----------------------------------------------------------
|
485 |
+
|
486 |
+
class BetaBinomialDistribution(SingleFiniteDistribution):
|
487 |
+
_argnames = ('n', 'alpha', 'beta')
|
488 |
+
|
489 |
+
@staticmethod
|
490 |
+
def check(n, alpha, beta):
|
491 |
+
_value_check((n.is_integer, n.is_nonnegative),
|
492 |
+
"'n' must be nonnegative integer. n = %s." % str(n))
|
493 |
+
_value_check((alpha > 0),
|
494 |
+
"'alpha' must be: alpha > 0 . alpha = %s" % str(alpha))
|
495 |
+
_value_check((beta > 0),
|
496 |
+
"'beta' must be: beta > 0 . beta = %s" % str(beta))
|
497 |
+
|
498 |
+
@property
|
499 |
+
def high(self):
|
500 |
+
return self.n
|
501 |
+
|
502 |
+
@property
|
503 |
+
def low(self):
|
504 |
+
return S.Zero
|
505 |
+
|
506 |
+
@property
|
507 |
+
def is_symbolic(self):
|
508 |
+
return not self.n.is_number
|
509 |
+
|
510 |
+
@property
|
511 |
+
def set(self):
|
512 |
+
if self.is_symbolic:
|
513 |
+
return Intersection(S.Naturals0, Interval(0, self.n))
|
514 |
+
return set(map(Integer, range(self.n + 1)))
|
515 |
+
|
516 |
+
def pmf(self, k):
|
517 |
+
n, a, b = self.n, self.alpha, self.beta
|
518 |
+
return binomial(n, k) * beta_fn(k + a, n - k + b) / beta_fn(a, b)
|
519 |
+
|
520 |
+
|
521 |
+
def BetaBinomial(name, n, alpha, beta):
|
522 |
+
r"""
|
523 |
+
Create a Finite Random Variable representing a Beta-binomial distribution.
|
524 |
+
|
525 |
+
Parameters
|
526 |
+
==========
|
527 |
+
|
528 |
+
n : Positive Integer
|
529 |
+
Represents number of trials
|
530 |
+
alpha : Real positive number
|
531 |
+
beta : Real positive number
|
532 |
+
|
533 |
+
Examples
|
534 |
+
========
|
535 |
+
|
536 |
+
>>> from sympy.stats import BetaBinomial, density
|
537 |
+
|
538 |
+
>>> X = BetaBinomial('X', 2, 1, 1)
|
539 |
+
>>> density(X).dict
|
540 |
+
{0: 1/3, 1: 2*beta(2, 2), 2: 1/3}
|
541 |
+
|
542 |
+
Returns
|
543 |
+
=======
|
544 |
+
|
545 |
+
RandomSymbol
|
546 |
+
|
547 |
+
References
|
548 |
+
==========
|
549 |
+
|
550 |
+
.. [1] https://en.wikipedia.org/wiki/Beta-binomial_distribution
|
551 |
+
.. [2] https://mathworld.wolfram.com/BetaBinomialDistribution.html
|
552 |
+
|
553 |
+
"""
|
554 |
+
|
555 |
+
return rv(name, BetaBinomialDistribution, n, alpha, beta)
|
556 |
+
|
557 |
+
|
558 |
+
class HypergeometricDistribution(SingleFiniteDistribution):
|
559 |
+
_argnames = ('N', 'm', 'n')
|
560 |
+
|
561 |
+
@staticmethod
|
562 |
+
def check(n, N, m):
|
563 |
+
_value_check((N.is_integer, N.is_nonnegative),
|
564 |
+
"'N' must be nonnegative integer. N = %s." % str(n))
|
565 |
+
_value_check((n.is_integer, n.is_nonnegative),
|
566 |
+
"'n' must be nonnegative integer. n = %s." % str(n))
|
567 |
+
_value_check((m.is_integer, m.is_nonnegative),
|
568 |
+
"'m' must be nonnegative integer. m = %s." % str(n))
|
569 |
+
|
570 |
+
@property
|
571 |
+
def is_symbolic(self):
|
572 |
+
return not all(x.is_number for x in (self.N, self.m, self.n))
|
573 |
+
|
574 |
+
@property
|
575 |
+
def high(self):
|
576 |
+
return Piecewise((self.n, Lt(self.n, self.m) != False), (self.m, True))
|
577 |
+
|
578 |
+
@property
|
579 |
+
def low(self):
|
580 |
+
return Piecewise((0, Gt(0, self.n + self.m - self.N) != False), (self.n + self.m - self.N, True))
|
581 |
+
|
582 |
+
@property
|
583 |
+
def set(self):
|
584 |
+
N, m, n = self.N, self.m, self.n
|
585 |
+
if self.is_symbolic:
|
586 |
+
return Intersection(S.Naturals0, Interval(self.low, self.high))
|
587 |
+
return set(range(max(0, n + m - N), min(n, m) + 1))
|
588 |
+
|
589 |
+
def pmf(self, k):
|
590 |
+
N, m, n = self.N, self.m, self.n
|
591 |
+
return S(binomial(m, k) * binomial(N - m, n - k))/binomial(N, n)
|
592 |
+
|
593 |
+
|
594 |
+
def Hypergeometric(name, N, m, n):
|
595 |
+
r"""
|
596 |
+
Create a Finite Random Variable representing a hypergeometric distribution.
|
597 |
+
|
598 |
+
Parameters
|
599 |
+
==========
|
600 |
+
|
601 |
+
N : Positive Integer
|
602 |
+
Represents finite population of size N.
|
603 |
+
m : Positive Integer
|
604 |
+
Represents number of trials with required feature.
|
605 |
+
n : Positive Integer
|
606 |
+
Represents numbers of draws.
|
607 |
+
|
608 |
+
|
609 |
+
Examples
|
610 |
+
========
|
611 |
+
|
612 |
+
>>> from sympy.stats import Hypergeometric, density
|
613 |
+
|
614 |
+
>>> X = Hypergeometric('X', 10, 5, 3) # 10 marbles, 5 white (success), 3 draws
|
615 |
+
>>> density(X).dict
|
616 |
+
{0: 1/12, 1: 5/12, 2: 5/12, 3: 1/12}
|
617 |
+
|
618 |
+
Returns
|
619 |
+
=======
|
620 |
+
|
621 |
+
RandomSymbol
|
622 |
+
|
623 |
+
References
|
624 |
+
==========
|
625 |
+
|
626 |
+
.. [1] https://en.wikipedia.org/wiki/Hypergeometric_distribution
|
627 |
+
.. [2] https://mathworld.wolfram.com/HypergeometricDistribution.html
|
628 |
+
|
629 |
+
"""
|
630 |
+
return rv(name, HypergeometricDistribution, N, m, n)
|
631 |
+
|
632 |
+
|
633 |
+
class RademacherDistribution(SingleFiniteDistribution):
|
634 |
+
|
635 |
+
@property
|
636 |
+
def set(self):
|
637 |
+
return {-1, 1}
|
638 |
+
|
639 |
+
@property
|
640 |
+
def pmf(self):
|
641 |
+
k = Dummy('k')
|
642 |
+
return Lambda(k, Piecewise((S.Half, Or(Eq(k, -1), Eq(k, 1))), (S.Zero, True)))
|
643 |
+
|
644 |
+
def Rademacher(name):
|
645 |
+
r"""
|
646 |
+
Create a Finite Random Variable representing a Rademacher distribution.
|
647 |
+
|
648 |
+
Examples
|
649 |
+
========
|
650 |
+
|
651 |
+
>>> from sympy.stats import Rademacher, density
|
652 |
+
|
653 |
+
>>> X = Rademacher('X')
|
654 |
+
>>> density(X).dict
|
655 |
+
{-1: 1/2, 1: 1/2}
|
656 |
+
|
657 |
+
Returns
|
658 |
+
=======
|
659 |
+
|
660 |
+
RandomSymbol
|
661 |
+
|
662 |
+
See Also
|
663 |
+
========
|
664 |
+
|
665 |
+
sympy.stats.Bernoulli
|
666 |
+
|
667 |
+
References
|
668 |
+
==========
|
669 |
+
|
670 |
+
.. [1] https://en.wikipedia.org/wiki/Rademacher_distribution
|
671 |
+
|
672 |
+
"""
|
673 |
+
return rv(name, RademacherDistribution)
|
674 |
+
|
675 |
+
class IdealSolitonDistribution(SingleFiniteDistribution):
|
676 |
+
_argnames = ('k',)
|
677 |
+
|
678 |
+
@staticmethod
|
679 |
+
def check(k):
|
680 |
+
_value_check(k.is_integer and k.is_positive,
|
681 |
+
"'k' must be a positive integer.")
|
682 |
+
|
683 |
+
@property
|
684 |
+
def low(self):
|
685 |
+
return S.One
|
686 |
+
|
687 |
+
@property
|
688 |
+
def high(self):
|
689 |
+
return self.k
|
690 |
+
|
691 |
+
@property
|
692 |
+
def set(self):
|
693 |
+
return set(map(Integer, range(1, self.k + 1)))
|
694 |
+
|
695 |
+
@property # type: ignore
|
696 |
+
@cacheit
|
697 |
+
def dict(self):
|
698 |
+
if self.k.is_Symbol:
|
699 |
+
return Density(self)
|
700 |
+
d = {1: Rational(1, self.k)}
|
701 |
+
d.update({i: Rational(1, i*(i - 1)) for i in range(2, self.k + 1)})
|
702 |
+
return d
|
703 |
+
|
704 |
+
def pmf(self, x):
|
705 |
+
x = sympify(x)
|
706 |
+
if not (x.is_number or x.is_Symbol or is_random(x)):
|
707 |
+
raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or "
|
708 |
+
"'RandomSymbol' not %s" % (type(x)))
|
709 |
+
cond1 = Eq(x, 1) & x.is_integer
|
710 |
+
cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer
|
711 |
+
return Piecewise((1/self.k, cond1), (1/(x*(x - 1)), cond2), (S.Zero, True))
|
712 |
+
|
713 |
+
def IdealSoliton(name, k):
|
714 |
+
r"""
|
715 |
+
Create a Finite Random Variable of Ideal Soliton Distribution
|
716 |
+
|
717 |
+
Parameters
|
718 |
+
==========
|
719 |
+
|
720 |
+
k : Positive Integer
|
721 |
+
Represents the number of input symbols in an LT (Luby Transform) code.
|
722 |
+
|
723 |
+
Examples
|
724 |
+
========
|
725 |
+
|
726 |
+
>>> from sympy.stats import IdealSoliton, density, P, E
|
727 |
+
>>> sol = IdealSoliton('sol', 5)
|
728 |
+
>>> density(sol).dict
|
729 |
+
{1: 1/5, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20}
|
730 |
+
>>> density(sol).set
|
731 |
+
{1, 2, 3, 4, 5}
|
732 |
+
|
733 |
+
>>> from sympy import Symbol
|
734 |
+
>>> k = Symbol('k', positive=True, integer=True)
|
735 |
+
>>> sol = IdealSoliton('sol', k)
|
736 |
+
>>> density(sol).dict
|
737 |
+
Density(IdealSolitonDistribution(k))
|
738 |
+
>>> density(sol).dict.subs(k, 10).doit()
|
739 |
+
{1: 1/10, 2: 1/2, 3: 1/6, 4: 1/12, 5: 1/20, 6: 1/30, 7: 1/42, 8: 1/56, 9: 1/72, 10: 1/90}
|
740 |
+
|
741 |
+
>>> E(sol.subs(k, 10))
|
742 |
+
7381/2520
|
743 |
+
|
744 |
+
>>> P(sol.subs(k, 4) > 2)
|
745 |
+
1/4
|
746 |
+
|
747 |
+
Returns
|
748 |
+
=======
|
749 |
+
|
750 |
+
RandomSymbol
|
751 |
+
|
752 |
+
References
|
753 |
+
==========
|
754 |
+
|
755 |
+
.. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Ideal_distribution
|
756 |
+
.. [2] https://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf
|
757 |
+
|
758 |
+
"""
|
759 |
+
return rv(name, IdealSolitonDistribution, k)
|
760 |
+
|
761 |
+
class RobustSolitonDistribution(SingleFiniteDistribution):
|
762 |
+
_argnames= ('k', 'delta', 'c')
|
763 |
+
|
764 |
+
@staticmethod
|
765 |
+
def check(k, delta, c):
|
766 |
+
_value_check(k.is_integer and k.is_positive,
|
767 |
+
"'k' must be a positive integer")
|
768 |
+
_value_check(Gt(delta, 0) and Le(delta, 1),
|
769 |
+
"'delta' must be a real number in the interval (0,1)")
|
770 |
+
_value_check(c.is_positive,
|
771 |
+
"'c' must be a positive real number.")
|
772 |
+
|
773 |
+
@property
|
774 |
+
def R(self):
|
775 |
+
return self.c * log(self.k/self.delta) * self.k**0.5
|
776 |
+
|
777 |
+
@property
|
778 |
+
def Z(self):
|
779 |
+
z = 0
|
780 |
+
for i in Range(1, round(self.k/self.R)):
|
781 |
+
z += (1/i)
|
782 |
+
z += log(self.R/self.delta)
|
783 |
+
return 1 + z * self.R/self.k
|
784 |
+
|
785 |
+
@property
|
786 |
+
def low(self):
|
787 |
+
return S.One
|
788 |
+
|
789 |
+
@property
|
790 |
+
def high(self):
|
791 |
+
return self.k
|
792 |
+
|
793 |
+
@property
|
794 |
+
def set(self):
|
795 |
+
return set(map(Integer, range(1, self.k + 1)))
|
796 |
+
|
797 |
+
@property
|
798 |
+
def is_symbolic(self):
|
799 |
+
return not (self.k.is_number and self.c.is_number and self.delta.is_number)
|
800 |
+
|
801 |
+
def pmf(self, x):
|
802 |
+
x = sympify(x)
|
803 |
+
if not (x.is_number or x.is_Symbol or is_random(x)):
|
804 |
+
raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or "
|
805 |
+
"'RandomSymbol' not %s" % (type(x)))
|
806 |
+
|
807 |
+
cond1 = Eq(x, 1) & x.is_integer
|
808 |
+
cond2 = Ge(x, 1) & Le(x, self.k) & x.is_integer
|
809 |
+
rho = Piecewise((Rational(1, self.k), cond1), (Rational(1, x*(x-1)), cond2), (S.Zero, True))
|
810 |
+
|
811 |
+
cond1 = Ge(x, 1) & Le(x, round(self.k/self.R)-1)
|
812 |
+
cond2 = Eq(x, round(self.k/self.R))
|
813 |
+
tau = Piecewise((self.R/(self.k * x), cond1), (self.R * log(self.R/self.delta)/self.k, cond2), (S.Zero, True))
|
814 |
+
|
815 |
+
return (rho + tau)/self.Z
|
816 |
+
|
817 |
+
def RobustSoliton(name, k, delta, c):
|
818 |
+
r'''
|
819 |
+
Create a Finite Random Variable of Robust Soliton Distribution
|
820 |
+
|
821 |
+
Parameters
|
822 |
+
==========
|
823 |
+
|
824 |
+
k : Positive Integer
|
825 |
+
Represents the number of input symbols in an LT (Luby Transform) code.
|
826 |
+
delta : Positive Rational Number
|
827 |
+
Represents the failure probability. Must be in the interval (0,1).
|
828 |
+
c : Positive Rational Number
|
829 |
+
Constant of proportionality. Values close to 1 are recommended
|
830 |
+
|
831 |
+
Examples
|
832 |
+
========
|
833 |
+
|
834 |
+
>>> from sympy.stats import RobustSoliton, density, P, E
|
835 |
+
>>> robSol = RobustSoliton('robSol', 5, 0.5, 0.01)
|
836 |
+
>>> density(robSol).dict
|
837 |
+
{1: 0.204253668152708, 2: 0.490631107897393, 3: 0.165210624506162, 4: 0.0834387731899302, 5: 0.0505633404760675}
|
838 |
+
>>> density(robSol).set
|
839 |
+
{1, 2, 3, 4, 5}
|
840 |
+
|
841 |
+
>>> from sympy import Symbol
|
842 |
+
>>> k = Symbol('k', positive=True, integer=True)
|
843 |
+
>>> c = Symbol('c', positive=True)
|
844 |
+
>>> robSol = RobustSoliton('robSol', k, 0.5, c)
|
845 |
+
>>> density(robSol).dict
|
846 |
+
Density(RobustSolitonDistribution(k, 0.5, c))
|
847 |
+
>>> density(robSol).dict.subs(k, 10).subs(c, 0.03).doit()
|
848 |
+
{1: 0.116641095387194, 2: 0.467045731687165, 3: 0.159984123349381, 4: 0.0821431680681869, 5: 0.0505765646770100,
|
849 |
+
6: 0.0345781523420719, 7: 0.0253132820710503, 8: 0.0194459129233227, 9: 0.0154831166726115, 10: 0.0126733075238887}
|
850 |
+
|
851 |
+
>>> E(robSol.subs(k, 10).subs(c, 0.05))
|
852 |
+
2.91358846104106
|
853 |
+
|
854 |
+
>>> P(robSol.subs(k, 4).subs(c, 0.1) > 2)
|
855 |
+
0.243650614389834
|
856 |
+
|
857 |
+
Returns
|
858 |
+
=======
|
859 |
+
|
860 |
+
RandomSymbol
|
861 |
+
|
862 |
+
References
|
863 |
+
==========
|
864 |
+
|
865 |
+
.. [1] https://en.wikipedia.org/wiki/Soliton_distribution#Robust_distribution
|
866 |
+
.. [2] https://www.inference.org.uk/mackay/itprnn/ps/588.596.pdf
|
867 |
+
.. [3] https://pages.cs.wisc.edu/~suman/courses/740/papers/luby02lt.pdf
|
868 |
+
|
869 |
+
'''
|
870 |
+
return rv(name, RobustSolitonDistribution, k, delta, c)
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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)
|
llmeval-env/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()
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/rv.py
ADDED
@@ -0,0 +1,1792 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Main Random Variables Module
|
3 |
+
|
4 |
+
Defines abstract random variable type.
|
5 |
+
Contains interfaces for probability space object (PSpace) as well as standard
|
6 |
+
operators, P, E, sample, density, where, quantile
|
7 |
+
|
8 |
+
See Also
|
9 |
+
========
|
10 |
+
|
11 |
+
sympy.stats.crv
|
12 |
+
sympy.stats.frv
|
13 |
+
sympy.stats.rv_interface
|
14 |
+
"""
|
15 |
+
|
16 |
+
from __future__ import annotations
|
17 |
+
from functools import singledispatch
|
18 |
+
from math import prod
|
19 |
+
|
20 |
+
from sympy.core.add import Add
|
21 |
+
from sympy.core.basic import Basic
|
22 |
+
from sympy.core.containers import Tuple
|
23 |
+
from sympy.core.expr import Expr
|
24 |
+
from sympy.core.function import (Function, Lambda)
|
25 |
+
from sympy.core.logic import fuzzy_and
|
26 |
+
from sympy.core.mul import Mul
|
27 |
+
from sympy.core.relational import (Eq, Ne)
|
28 |
+
from sympy.core.singleton import S
|
29 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
30 |
+
from sympy.core.sympify import sympify
|
31 |
+
from sympy.functions.special.delta_functions import DiracDelta
|
32 |
+
from sympy.functions.special.tensor_functions import KroneckerDelta
|
33 |
+
from sympy.logic.boolalg import (And, Or)
|
34 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
35 |
+
from sympy.tensor.indexed import Indexed
|
36 |
+
from sympy.utilities.lambdify import lambdify
|
37 |
+
from sympy.core.relational import Relational
|
38 |
+
from sympy.core.sympify import _sympify
|
39 |
+
from sympy.sets.sets import FiniteSet, ProductSet, Intersection
|
40 |
+
from sympy.solvers.solveset import solveset
|
41 |
+
from sympy.external import import_module
|
42 |
+
from sympy.utilities.decorator import doctest_depends_on
|
43 |
+
from sympy.utilities.exceptions import sympy_deprecation_warning
|
44 |
+
from sympy.utilities.iterables import iterable
|
45 |
+
|
46 |
+
|
47 |
+
x = Symbol('x')
|
48 |
+
|
49 |
+
@singledispatch
|
50 |
+
def is_random(x):
|
51 |
+
return False
|
52 |
+
|
53 |
+
@is_random.register(Basic)
|
54 |
+
def _(x):
|
55 |
+
atoms = x.free_symbols
|
56 |
+
return any(is_random(i) for i in atoms)
|
57 |
+
|
58 |
+
class RandomDomain(Basic):
|
59 |
+
"""
|
60 |
+
Represents a set of variables and the values which they can take.
|
61 |
+
|
62 |
+
See Also
|
63 |
+
========
|
64 |
+
|
65 |
+
sympy.stats.crv.ContinuousDomain
|
66 |
+
sympy.stats.frv.FiniteDomain
|
67 |
+
"""
|
68 |
+
|
69 |
+
is_ProductDomain = False
|
70 |
+
is_Finite = False
|
71 |
+
is_Continuous = False
|
72 |
+
is_Discrete = False
|
73 |
+
|
74 |
+
def __new__(cls, symbols, *args):
|
75 |
+
symbols = FiniteSet(*symbols)
|
76 |
+
return Basic.__new__(cls, symbols, *args)
|
77 |
+
|
78 |
+
@property
|
79 |
+
def symbols(self):
|
80 |
+
return self.args[0]
|
81 |
+
|
82 |
+
@property
|
83 |
+
def set(self):
|
84 |
+
return self.args[1]
|
85 |
+
|
86 |
+
def __contains__(self, other):
|
87 |
+
raise NotImplementedError()
|
88 |
+
|
89 |
+
def compute_expectation(self, expr):
|
90 |
+
raise NotImplementedError()
|
91 |
+
|
92 |
+
|
93 |
+
class SingleDomain(RandomDomain):
|
94 |
+
"""
|
95 |
+
A single variable and its domain.
|
96 |
+
|
97 |
+
See Also
|
98 |
+
========
|
99 |
+
|
100 |
+
sympy.stats.crv.SingleContinuousDomain
|
101 |
+
sympy.stats.frv.SingleFiniteDomain
|
102 |
+
"""
|
103 |
+
def __new__(cls, symbol, set):
|
104 |
+
assert symbol.is_Symbol
|
105 |
+
return Basic.__new__(cls, symbol, set)
|
106 |
+
|
107 |
+
@property
|
108 |
+
def symbol(self):
|
109 |
+
return self.args[0]
|
110 |
+
|
111 |
+
@property
|
112 |
+
def symbols(self):
|
113 |
+
return FiniteSet(self.symbol)
|
114 |
+
|
115 |
+
def __contains__(self, other):
|
116 |
+
if len(other) != 1:
|
117 |
+
return False
|
118 |
+
sym, val = tuple(other)[0]
|
119 |
+
return self.symbol == sym and val in self.set
|
120 |
+
|
121 |
+
|
122 |
+
class MatrixDomain(RandomDomain):
|
123 |
+
"""
|
124 |
+
A Random Matrix variable and its domain.
|
125 |
+
|
126 |
+
"""
|
127 |
+
def __new__(cls, symbol, set):
|
128 |
+
symbol, set = _symbol_converter(symbol), _sympify(set)
|
129 |
+
return Basic.__new__(cls, symbol, set)
|
130 |
+
|
131 |
+
@property
|
132 |
+
def symbol(self):
|
133 |
+
return self.args[0]
|
134 |
+
|
135 |
+
@property
|
136 |
+
def symbols(self):
|
137 |
+
return FiniteSet(self.symbol)
|
138 |
+
|
139 |
+
|
140 |
+
class ConditionalDomain(RandomDomain):
|
141 |
+
"""
|
142 |
+
A RandomDomain with an attached condition.
|
143 |
+
|
144 |
+
See Also
|
145 |
+
========
|
146 |
+
|
147 |
+
sympy.stats.crv.ConditionalContinuousDomain
|
148 |
+
sympy.stats.frv.ConditionalFiniteDomain
|
149 |
+
"""
|
150 |
+
def __new__(cls, fulldomain, condition):
|
151 |
+
condition = condition.xreplace({rs: rs.symbol
|
152 |
+
for rs in random_symbols(condition)})
|
153 |
+
return Basic.__new__(cls, fulldomain, condition)
|
154 |
+
|
155 |
+
@property
|
156 |
+
def symbols(self):
|
157 |
+
return self.fulldomain.symbols
|
158 |
+
|
159 |
+
@property
|
160 |
+
def fulldomain(self):
|
161 |
+
return self.args[0]
|
162 |
+
|
163 |
+
@property
|
164 |
+
def condition(self):
|
165 |
+
return self.args[1]
|
166 |
+
|
167 |
+
@property
|
168 |
+
def set(self):
|
169 |
+
raise NotImplementedError("Set of Conditional Domain not Implemented")
|
170 |
+
|
171 |
+
def as_boolean(self):
|
172 |
+
return And(self.fulldomain.as_boolean(), self.condition)
|
173 |
+
|
174 |
+
|
175 |
+
class PSpace(Basic):
|
176 |
+
"""
|
177 |
+
A Probability Space.
|
178 |
+
|
179 |
+
Explanation
|
180 |
+
===========
|
181 |
+
|
182 |
+
Probability Spaces encode processes that equal different values
|
183 |
+
probabilistically. These underly Random Symbols which occur in SymPy
|
184 |
+
expressions and contain the mechanics to evaluate statistical statements.
|
185 |
+
|
186 |
+
See Also
|
187 |
+
========
|
188 |
+
|
189 |
+
sympy.stats.crv.ContinuousPSpace
|
190 |
+
sympy.stats.frv.FinitePSpace
|
191 |
+
"""
|
192 |
+
|
193 |
+
is_Finite = None # type: bool
|
194 |
+
is_Continuous = None # type: bool
|
195 |
+
is_Discrete = None # type: bool
|
196 |
+
is_real = None # type: bool
|
197 |
+
|
198 |
+
@property
|
199 |
+
def domain(self):
|
200 |
+
return self.args[0]
|
201 |
+
|
202 |
+
@property
|
203 |
+
def density(self):
|
204 |
+
return self.args[1]
|
205 |
+
|
206 |
+
@property
|
207 |
+
def values(self):
|
208 |
+
return frozenset(RandomSymbol(sym, self) for sym in self.symbols)
|
209 |
+
|
210 |
+
@property
|
211 |
+
def symbols(self):
|
212 |
+
return self.domain.symbols
|
213 |
+
|
214 |
+
def where(self, condition):
|
215 |
+
raise NotImplementedError()
|
216 |
+
|
217 |
+
def compute_density(self, expr):
|
218 |
+
raise NotImplementedError()
|
219 |
+
|
220 |
+
def sample(self, size=(), library='scipy', seed=None):
|
221 |
+
raise NotImplementedError()
|
222 |
+
|
223 |
+
def probability(self, condition):
|
224 |
+
raise NotImplementedError()
|
225 |
+
|
226 |
+
def compute_expectation(self, expr):
|
227 |
+
raise NotImplementedError()
|
228 |
+
|
229 |
+
|
230 |
+
class SinglePSpace(PSpace):
|
231 |
+
"""
|
232 |
+
Represents the probabilities of a set of random events that can be
|
233 |
+
attributed to a single variable/symbol.
|
234 |
+
"""
|
235 |
+
def __new__(cls, s, distribution):
|
236 |
+
s = _symbol_converter(s)
|
237 |
+
return Basic.__new__(cls, s, distribution)
|
238 |
+
|
239 |
+
@property
|
240 |
+
def value(self):
|
241 |
+
return RandomSymbol(self.symbol, self)
|
242 |
+
|
243 |
+
@property
|
244 |
+
def symbol(self):
|
245 |
+
return self.args[0]
|
246 |
+
|
247 |
+
@property
|
248 |
+
def distribution(self):
|
249 |
+
return self.args[1]
|
250 |
+
|
251 |
+
@property
|
252 |
+
def pdf(self):
|
253 |
+
return self.distribution.pdf(self.symbol)
|
254 |
+
|
255 |
+
|
256 |
+
class RandomSymbol(Expr):
|
257 |
+
"""
|
258 |
+
Random Symbols represent ProbabilitySpaces in SymPy Expressions.
|
259 |
+
In principle they can take on any value that their symbol can take on
|
260 |
+
within the associated PSpace with probability determined by the PSpace
|
261 |
+
Density.
|
262 |
+
|
263 |
+
Explanation
|
264 |
+
===========
|
265 |
+
|
266 |
+
Random Symbols contain pspace and symbol properties.
|
267 |
+
The pspace property points to the represented Probability Space
|
268 |
+
The symbol is a standard SymPy Symbol that is used in that probability space
|
269 |
+
for example in defining a density.
|
270 |
+
|
271 |
+
You can form normal SymPy expressions using RandomSymbols and operate on
|
272 |
+
those expressions with the Functions
|
273 |
+
|
274 |
+
E - Expectation of a random expression
|
275 |
+
P - Probability of a condition
|
276 |
+
density - Probability Density of an expression
|
277 |
+
given - A new random expression (with new random symbols) given a condition
|
278 |
+
|
279 |
+
An object of the RandomSymbol type should almost never be created by the
|
280 |
+
user. They tend to be created instead by the PSpace class's value method.
|
281 |
+
Traditionally a user does not even do this but instead calls one of the
|
282 |
+
convenience functions Normal, Exponential, Coin, Die, FiniteRV, etc....
|
283 |
+
"""
|
284 |
+
|
285 |
+
def __new__(cls, symbol, pspace=None):
|
286 |
+
from sympy.stats.joint_rv import JointRandomSymbol
|
287 |
+
if pspace is None:
|
288 |
+
# Allow single arg, representing pspace == PSpace()
|
289 |
+
pspace = PSpace()
|
290 |
+
symbol = _symbol_converter(symbol)
|
291 |
+
if not isinstance(pspace, PSpace):
|
292 |
+
raise TypeError("pspace variable should be of type PSpace")
|
293 |
+
if cls == JointRandomSymbol and isinstance(pspace, SinglePSpace):
|
294 |
+
cls = RandomSymbol
|
295 |
+
return Basic.__new__(cls, symbol, pspace)
|
296 |
+
|
297 |
+
is_finite = True
|
298 |
+
is_symbol = True
|
299 |
+
is_Atom = True
|
300 |
+
|
301 |
+
_diff_wrt = True
|
302 |
+
|
303 |
+
pspace = property(lambda self: self.args[1])
|
304 |
+
symbol = property(lambda self: self.args[0])
|
305 |
+
name = property(lambda self: self.symbol.name)
|
306 |
+
|
307 |
+
def _eval_is_positive(self):
|
308 |
+
return self.symbol.is_positive
|
309 |
+
|
310 |
+
def _eval_is_integer(self):
|
311 |
+
return self.symbol.is_integer
|
312 |
+
|
313 |
+
def _eval_is_real(self):
|
314 |
+
return self.symbol.is_real or self.pspace.is_real
|
315 |
+
|
316 |
+
@property
|
317 |
+
def is_commutative(self):
|
318 |
+
return self.symbol.is_commutative
|
319 |
+
|
320 |
+
@property
|
321 |
+
def free_symbols(self):
|
322 |
+
return {self}
|
323 |
+
|
324 |
+
class RandomIndexedSymbol(RandomSymbol):
|
325 |
+
|
326 |
+
def __new__(cls, idx_obj, pspace=None):
|
327 |
+
if pspace is None:
|
328 |
+
# Allow single arg, representing pspace == PSpace()
|
329 |
+
pspace = PSpace()
|
330 |
+
if not isinstance(idx_obj, (Indexed, Function)):
|
331 |
+
raise TypeError("An Function or Indexed object is expected not %s"%(idx_obj))
|
332 |
+
return Basic.__new__(cls, idx_obj, pspace)
|
333 |
+
|
334 |
+
symbol = property(lambda self: self.args[0])
|
335 |
+
name = property(lambda self: str(self.args[0]))
|
336 |
+
|
337 |
+
@property
|
338 |
+
def key(self):
|
339 |
+
if isinstance(self.symbol, Indexed):
|
340 |
+
return self.symbol.args[1]
|
341 |
+
elif isinstance(self.symbol, Function):
|
342 |
+
return self.symbol.args[0]
|
343 |
+
|
344 |
+
@property
|
345 |
+
def free_symbols(self):
|
346 |
+
if self.key.free_symbols:
|
347 |
+
free_syms = self.key.free_symbols
|
348 |
+
free_syms.add(self)
|
349 |
+
return free_syms
|
350 |
+
return {self}
|
351 |
+
|
352 |
+
@property
|
353 |
+
def pspace(self):
|
354 |
+
return self.args[1]
|
355 |
+
|
356 |
+
class RandomMatrixSymbol(RandomSymbol, MatrixSymbol): # type: ignore
|
357 |
+
def __new__(cls, symbol, n, m, pspace=None):
|
358 |
+
n, m = _sympify(n), _sympify(m)
|
359 |
+
symbol = _symbol_converter(symbol)
|
360 |
+
if pspace is None:
|
361 |
+
# Allow single arg, representing pspace == PSpace()
|
362 |
+
pspace = PSpace()
|
363 |
+
return Basic.__new__(cls, symbol, n, m, pspace)
|
364 |
+
|
365 |
+
symbol = property(lambda self: self.args[0])
|
366 |
+
pspace = property(lambda self: self.args[3])
|
367 |
+
|
368 |
+
|
369 |
+
class ProductPSpace(PSpace):
|
370 |
+
"""
|
371 |
+
Abstract class for representing probability spaces with multiple random
|
372 |
+
variables.
|
373 |
+
|
374 |
+
See Also
|
375 |
+
========
|
376 |
+
|
377 |
+
sympy.stats.rv.IndependentProductPSpace
|
378 |
+
sympy.stats.joint_rv.JointPSpace
|
379 |
+
"""
|
380 |
+
pass
|
381 |
+
|
382 |
+
class IndependentProductPSpace(ProductPSpace):
|
383 |
+
"""
|
384 |
+
A probability space resulting from the merger of two independent probability
|
385 |
+
spaces.
|
386 |
+
|
387 |
+
Often created using the function, pspace.
|
388 |
+
"""
|
389 |
+
|
390 |
+
def __new__(cls, *spaces):
|
391 |
+
rs_space_dict = {}
|
392 |
+
for space in spaces:
|
393 |
+
for value in space.values:
|
394 |
+
rs_space_dict[value] = space
|
395 |
+
|
396 |
+
symbols = FiniteSet(*[val.symbol for val in rs_space_dict.keys()])
|
397 |
+
|
398 |
+
# Overlapping symbols
|
399 |
+
from sympy.stats.joint_rv import MarginalDistribution
|
400 |
+
from sympy.stats.compound_rv import CompoundDistribution
|
401 |
+
if len(symbols) < sum(len(space.symbols) for space in spaces if not
|
402 |
+
isinstance(space.distribution, (
|
403 |
+
CompoundDistribution, MarginalDistribution))):
|
404 |
+
raise ValueError("Overlapping Random Variables")
|
405 |
+
|
406 |
+
if all(space.is_Finite for space in spaces):
|
407 |
+
from sympy.stats.frv import ProductFinitePSpace
|
408 |
+
cls = ProductFinitePSpace
|
409 |
+
|
410 |
+
obj = Basic.__new__(cls, *FiniteSet(*spaces))
|
411 |
+
|
412 |
+
return obj
|
413 |
+
|
414 |
+
@property
|
415 |
+
def pdf(self):
|
416 |
+
p = Mul(*[space.pdf for space in self.spaces])
|
417 |
+
return p.subs({rv: rv.symbol for rv in self.values})
|
418 |
+
|
419 |
+
@property
|
420 |
+
def rs_space_dict(self):
|
421 |
+
d = {}
|
422 |
+
for space in self.spaces:
|
423 |
+
for value in space.values:
|
424 |
+
d[value] = space
|
425 |
+
return d
|
426 |
+
|
427 |
+
@property
|
428 |
+
def symbols(self):
|
429 |
+
return FiniteSet(*[val.symbol for val in self.rs_space_dict.keys()])
|
430 |
+
|
431 |
+
@property
|
432 |
+
def spaces(self):
|
433 |
+
return FiniteSet(*self.args)
|
434 |
+
|
435 |
+
@property
|
436 |
+
def values(self):
|
437 |
+
return sumsets(space.values for space in self.spaces)
|
438 |
+
|
439 |
+
def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
|
440 |
+
rvs = rvs or self.values
|
441 |
+
rvs = frozenset(rvs)
|
442 |
+
for space in self.spaces:
|
443 |
+
expr = space.compute_expectation(expr, rvs & space.values, evaluate=False, **kwargs)
|
444 |
+
if evaluate and hasattr(expr, 'doit'):
|
445 |
+
return expr.doit(**kwargs)
|
446 |
+
return expr
|
447 |
+
|
448 |
+
@property
|
449 |
+
def domain(self):
|
450 |
+
return ProductDomain(*[space.domain for space in self.spaces])
|
451 |
+
|
452 |
+
@property
|
453 |
+
def density(self):
|
454 |
+
raise NotImplementedError("Density not available for ProductSpaces")
|
455 |
+
|
456 |
+
def sample(self, size=(), library='scipy', seed=None):
|
457 |
+
return {k: v for space in self.spaces
|
458 |
+
for k, v in space.sample(size=size, library=library, seed=seed).items()}
|
459 |
+
|
460 |
+
|
461 |
+
def probability(self, condition, **kwargs):
|
462 |
+
cond_inv = False
|
463 |
+
if isinstance(condition, Ne):
|
464 |
+
condition = Eq(condition.args[0], condition.args[1])
|
465 |
+
cond_inv = True
|
466 |
+
elif isinstance(condition, And): # they are independent
|
467 |
+
return Mul(*[self.probability(arg) for arg in condition.args])
|
468 |
+
elif isinstance(condition, Or): # they are independent
|
469 |
+
return Add(*[self.probability(arg) for arg in condition.args])
|
470 |
+
expr = condition.lhs - condition.rhs
|
471 |
+
rvs = random_symbols(expr)
|
472 |
+
dens = self.compute_density(expr)
|
473 |
+
if any(pspace(rv).is_Continuous for rv in rvs):
|
474 |
+
from sympy.stats.crv import SingleContinuousPSpace
|
475 |
+
from sympy.stats.crv_types import ContinuousDistributionHandmade
|
476 |
+
if expr in self.values:
|
477 |
+
# Marginalize all other random symbols out of the density
|
478 |
+
randomsymbols = tuple(set(self.values) - frozenset([expr]))
|
479 |
+
symbols = tuple(rs.symbol for rs in randomsymbols)
|
480 |
+
pdf = self.domain.integrate(self.pdf, symbols, **kwargs)
|
481 |
+
return Lambda(expr.symbol, pdf)
|
482 |
+
dens = ContinuousDistributionHandmade(dens)
|
483 |
+
z = Dummy('z', real=True)
|
484 |
+
space = SingleContinuousPSpace(z, dens)
|
485 |
+
result = space.probability(condition.__class__(space.value, 0))
|
486 |
+
else:
|
487 |
+
from sympy.stats.drv import SingleDiscretePSpace
|
488 |
+
from sympy.stats.drv_types import DiscreteDistributionHandmade
|
489 |
+
dens = DiscreteDistributionHandmade(dens)
|
490 |
+
z = Dummy('z', integer=True)
|
491 |
+
space = SingleDiscretePSpace(z, dens)
|
492 |
+
result = space.probability(condition.__class__(space.value, 0))
|
493 |
+
return result if not cond_inv else S.One - result
|
494 |
+
|
495 |
+
def compute_density(self, expr, **kwargs):
|
496 |
+
rvs = random_symbols(expr)
|
497 |
+
if any(pspace(rv).is_Continuous for rv in rvs):
|
498 |
+
z = Dummy('z', real=True)
|
499 |
+
expr = self.compute_expectation(DiracDelta(expr - z),
|
500 |
+
**kwargs)
|
501 |
+
else:
|
502 |
+
z = Dummy('z', integer=True)
|
503 |
+
expr = self.compute_expectation(KroneckerDelta(expr, z),
|
504 |
+
**kwargs)
|
505 |
+
return Lambda(z, expr)
|
506 |
+
|
507 |
+
def compute_cdf(self, expr, **kwargs):
|
508 |
+
raise ValueError("CDF not well defined on multivariate expressions")
|
509 |
+
|
510 |
+
def conditional_space(self, condition, normalize=True, **kwargs):
|
511 |
+
rvs = random_symbols(condition)
|
512 |
+
condition = condition.xreplace({rv: rv.symbol for rv in self.values})
|
513 |
+
pspaces = [pspace(rv) for rv in rvs]
|
514 |
+
if any(ps.is_Continuous for ps in pspaces):
|
515 |
+
from sympy.stats.crv import (ConditionalContinuousDomain,
|
516 |
+
ContinuousPSpace)
|
517 |
+
space = ContinuousPSpace
|
518 |
+
domain = ConditionalContinuousDomain(self.domain, condition)
|
519 |
+
elif any(ps.is_Discrete for ps in pspaces):
|
520 |
+
from sympy.stats.drv import (ConditionalDiscreteDomain,
|
521 |
+
DiscretePSpace)
|
522 |
+
space = DiscretePSpace
|
523 |
+
domain = ConditionalDiscreteDomain(self.domain, condition)
|
524 |
+
elif all(ps.is_Finite for ps in pspaces):
|
525 |
+
from sympy.stats.frv import FinitePSpace
|
526 |
+
return FinitePSpace.conditional_space(self, condition)
|
527 |
+
if normalize:
|
528 |
+
replacement = {rv: Dummy(str(rv)) for rv in self.symbols}
|
529 |
+
norm = domain.compute_expectation(self.pdf, **kwargs)
|
530 |
+
pdf = self.pdf / norm.xreplace(replacement)
|
531 |
+
# XXX: Converting symbols from set to tuple. The order matters to
|
532 |
+
# Lambda though so we shouldn't be starting with a set here...
|
533 |
+
density = Lambda(tuple(domain.symbols), pdf)
|
534 |
+
|
535 |
+
return space(domain, density)
|
536 |
+
|
537 |
+
class ProductDomain(RandomDomain):
|
538 |
+
"""
|
539 |
+
A domain resulting from the merger of two independent domains.
|
540 |
+
|
541 |
+
See Also
|
542 |
+
========
|
543 |
+
sympy.stats.crv.ProductContinuousDomain
|
544 |
+
sympy.stats.frv.ProductFiniteDomain
|
545 |
+
"""
|
546 |
+
is_ProductDomain = True
|
547 |
+
|
548 |
+
def __new__(cls, *domains):
|
549 |
+
# Flatten any product of products
|
550 |
+
domains2 = []
|
551 |
+
for domain in domains:
|
552 |
+
if not domain.is_ProductDomain:
|
553 |
+
domains2.append(domain)
|
554 |
+
else:
|
555 |
+
domains2.extend(domain.domains)
|
556 |
+
domains2 = FiniteSet(*domains2)
|
557 |
+
|
558 |
+
if all(domain.is_Finite for domain in domains2):
|
559 |
+
from sympy.stats.frv import ProductFiniteDomain
|
560 |
+
cls = ProductFiniteDomain
|
561 |
+
if all(domain.is_Continuous for domain in domains2):
|
562 |
+
from sympy.stats.crv import ProductContinuousDomain
|
563 |
+
cls = ProductContinuousDomain
|
564 |
+
if all(domain.is_Discrete for domain in domains2):
|
565 |
+
from sympy.stats.drv import ProductDiscreteDomain
|
566 |
+
cls = ProductDiscreteDomain
|
567 |
+
|
568 |
+
return Basic.__new__(cls, *domains2)
|
569 |
+
|
570 |
+
@property
|
571 |
+
def sym_domain_dict(self):
|
572 |
+
return {symbol: domain for domain in self.domains
|
573 |
+
for symbol in domain.symbols}
|
574 |
+
|
575 |
+
@property
|
576 |
+
def symbols(self):
|
577 |
+
return FiniteSet(*[sym for domain in self.domains
|
578 |
+
for sym in domain.symbols])
|
579 |
+
|
580 |
+
@property
|
581 |
+
def domains(self):
|
582 |
+
return self.args
|
583 |
+
|
584 |
+
@property
|
585 |
+
def set(self):
|
586 |
+
return ProductSet(*(domain.set for domain in self.domains))
|
587 |
+
|
588 |
+
def __contains__(self, other):
|
589 |
+
# Split event into each subdomain
|
590 |
+
for domain in self.domains:
|
591 |
+
# Collect the parts of this event which associate to this domain
|
592 |
+
elem = frozenset([item for item in other
|
593 |
+
if sympify(domain.symbols.contains(item[0]))
|
594 |
+
is S.true])
|
595 |
+
# Test this sub-event
|
596 |
+
if elem not in domain:
|
597 |
+
return False
|
598 |
+
# All subevents passed
|
599 |
+
return True
|
600 |
+
|
601 |
+
def as_boolean(self):
|
602 |
+
return And(*[domain.as_boolean() for domain in self.domains])
|
603 |
+
|
604 |
+
|
605 |
+
def random_symbols(expr):
|
606 |
+
"""
|
607 |
+
Returns all RandomSymbols within a SymPy Expression.
|
608 |
+
"""
|
609 |
+
atoms = getattr(expr, 'atoms', None)
|
610 |
+
if atoms is not None:
|
611 |
+
comp = lambda rv: rv.symbol.name
|
612 |
+
l = list(atoms(RandomSymbol))
|
613 |
+
return sorted(l, key=comp)
|
614 |
+
else:
|
615 |
+
return []
|
616 |
+
|
617 |
+
|
618 |
+
def pspace(expr):
|
619 |
+
"""
|
620 |
+
Returns the underlying Probability Space of a random expression.
|
621 |
+
|
622 |
+
For internal use.
|
623 |
+
|
624 |
+
Examples
|
625 |
+
========
|
626 |
+
|
627 |
+
>>> from sympy.stats import pspace, Normal
|
628 |
+
>>> X = Normal('X', 0, 1)
|
629 |
+
>>> pspace(2*X + 1) == X.pspace
|
630 |
+
True
|
631 |
+
"""
|
632 |
+
expr = sympify(expr)
|
633 |
+
if isinstance(expr, RandomSymbol) and expr.pspace is not None:
|
634 |
+
return expr.pspace
|
635 |
+
if expr.has(RandomMatrixSymbol):
|
636 |
+
rm = list(expr.atoms(RandomMatrixSymbol))[0]
|
637 |
+
return rm.pspace
|
638 |
+
|
639 |
+
rvs = random_symbols(expr)
|
640 |
+
if not rvs:
|
641 |
+
raise ValueError("Expression containing Random Variable expected, not %s" % (expr))
|
642 |
+
# If only one space present
|
643 |
+
if all(rv.pspace == rvs[0].pspace for rv in rvs):
|
644 |
+
return rvs[0].pspace
|
645 |
+
from sympy.stats.compound_rv import CompoundPSpace
|
646 |
+
from sympy.stats.stochastic_process import StochasticPSpace
|
647 |
+
for rv in rvs:
|
648 |
+
if isinstance(rv.pspace, (CompoundPSpace, StochasticPSpace)):
|
649 |
+
return rv.pspace
|
650 |
+
# Otherwise make a product space
|
651 |
+
return IndependentProductPSpace(*[rv.pspace for rv in rvs])
|
652 |
+
|
653 |
+
|
654 |
+
def sumsets(sets):
|
655 |
+
"""
|
656 |
+
Union of sets
|
657 |
+
"""
|
658 |
+
return frozenset().union(*sets)
|
659 |
+
|
660 |
+
|
661 |
+
def rs_swap(a, b):
|
662 |
+
"""
|
663 |
+
Build a dictionary to swap RandomSymbols based on their underlying symbol.
|
664 |
+
|
665 |
+
i.e.
|
666 |
+
if ``X = ('x', pspace1)``
|
667 |
+
and ``Y = ('x', pspace2)``
|
668 |
+
then ``X`` and ``Y`` match and the key, value pair
|
669 |
+
``{X:Y}`` will appear in the result
|
670 |
+
|
671 |
+
Inputs: collections a and b of random variables which share common symbols
|
672 |
+
Output: dict mapping RVs in a to RVs in b
|
673 |
+
"""
|
674 |
+
d = {}
|
675 |
+
for rsa in a:
|
676 |
+
d[rsa] = [rsb for rsb in b if rsa.symbol == rsb.symbol][0]
|
677 |
+
return d
|
678 |
+
|
679 |
+
|
680 |
+
def given(expr, condition=None, **kwargs):
|
681 |
+
r""" Conditional Random Expression.
|
682 |
+
|
683 |
+
Explanation
|
684 |
+
===========
|
685 |
+
|
686 |
+
From a random expression and a condition on that expression creates a new
|
687 |
+
probability space from the condition and returns the same expression on that
|
688 |
+
conditional probability space.
|
689 |
+
|
690 |
+
Examples
|
691 |
+
========
|
692 |
+
|
693 |
+
>>> from sympy.stats import given, density, Die
|
694 |
+
>>> X = Die('X', 6)
|
695 |
+
>>> Y = given(X, X > 3)
|
696 |
+
>>> density(Y).dict
|
697 |
+
{4: 1/3, 5: 1/3, 6: 1/3}
|
698 |
+
|
699 |
+
Following convention, if the condition is a random symbol then that symbol
|
700 |
+
is considered fixed.
|
701 |
+
|
702 |
+
>>> from sympy.stats import Normal
|
703 |
+
>>> from sympy import pprint
|
704 |
+
>>> from sympy.abc import z
|
705 |
+
|
706 |
+
>>> X = Normal('X', 0, 1)
|
707 |
+
>>> Y = Normal('Y', 0, 1)
|
708 |
+
>>> pprint(density(X + Y, Y)(z), use_unicode=False)
|
709 |
+
2
|
710 |
+
-(-Y + z)
|
711 |
+
-----------
|
712 |
+
___ 2
|
713 |
+
\/ 2 *e
|
714 |
+
------------------
|
715 |
+
____
|
716 |
+
2*\/ pi
|
717 |
+
"""
|
718 |
+
|
719 |
+
if not is_random(condition) or pspace_independent(expr, condition):
|
720 |
+
return expr
|
721 |
+
|
722 |
+
if isinstance(condition, RandomSymbol):
|
723 |
+
condition = Eq(condition, condition.symbol)
|
724 |
+
|
725 |
+
condsymbols = random_symbols(condition)
|
726 |
+
if (isinstance(condition, Eq) and len(condsymbols) == 1 and
|
727 |
+
not isinstance(pspace(expr).domain, ConditionalDomain)):
|
728 |
+
rv = tuple(condsymbols)[0]
|
729 |
+
|
730 |
+
results = solveset(condition, rv)
|
731 |
+
if isinstance(results, Intersection) and S.Reals in results.args:
|
732 |
+
results = list(results.args[1])
|
733 |
+
|
734 |
+
sums = 0
|
735 |
+
for res in results:
|
736 |
+
temp = expr.subs(rv, res)
|
737 |
+
if temp == True:
|
738 |
+
return True
|
739 |
+
if temp != False:
|
740 |
+
# XXX: This seems nonsensical but preserves existing behaviour
|
741 |
+
# after the change that Relational is no longer a subclass of
|
742 |
+
# Expr. Here expr is sometimes Relational and sometimes Expr
|
743 |
+
# but we are trying to add them with +=. This needs to be
|
744 |
+
# fixed somehow.
|
745 |
+
if sums == 0 and isinstance(expr, Relational):
|
746 |
+
sums = expr.subs(rv, res)
|
747 |
+
else:
|
748 |
+
sums += expr.subs(rv, res)
|
749 |
+
if sums == 0:
|
750 |
+
return False
|
751 |
+
return sums
|
752 |
+
|
753 |
+
# Get full probability space of both the expression and the condition
|
754 |
+
fullspace = pspace(Tuple(expr, condition))
|
755 |
+
# Build new space given the condition
|
756 |
+
space = fullspace.conditional_space(condition, **kwargs)
|
757 |
+
# Dictionary to swap out RandomSymbols in expr with new RandomSymbols
|
758 |
+
# That point to the new conditional space
|
759 |
+
swapdict = rs_swap(fullspace.values, space.values)
|
760 |
+
# Swap random variables in the expression
|
761 |
+
expr = expr.xreplace(swapdict)
|
762 |
+
return expr
|
763 |
+
|
764 |
+
|
765 |
+
def expectation(expr, condition=None, numsamples=None, evaluate=True, **kwargs):
|
766 |
+
"""
|
767 |
+
Returns the expected value of a random expression.
|
768 |
+
|
769 |
+
Parameters
|
770 |
+
==========
|
771 |
+
|
772 |
+
expr : Expr containing RandomSymbols
|
773 |
+
The expression of which you want to compute the expectation value
|
774 |
+
given : Expr containing RandomSymbols
|
775 |
+
A conditional expression. E(X, X>0) is expectation of X given X > 0
|
776 |
+
numsamples : int
|
777 |
+
Enables sampling and approximates the expectation with this many samples
|
778 |
+
evalf : Bool (defaults to True)
|
779 |
+
If sampling return a number rather than a complex expression
|
780 |
+
evaluate : Bool (defaults to True)
|
781 |
+
In case of continuous systems return unevaluated integral
|
782 |
+
|
783 |
+
Examples
|
784 |
+
========
|
785 |
+
|
786 |
+
>>> from sympy.stats import E, Die
|
787 |
+
>>> X = Die('X', 6)
|
788 |
+
>>> E(X)
|
789 |
+
7/2
|
790 |
+
>>> E(2*X + 1)
|
791 |
+
8
|
792 |
+
|
793 |
+
>>> E(X, X > 3) # Expectation of X given that it is above 3
|
794 |
+
5
|
795 |
+
"""
|
796 |
+
|
797 |
+
if not is_random(expr): # expr isn't random?
|
798 |
+
return expr
|
799 |
+
kwargs['numsamples'] = numsamples
|
800 |
+
from sympy.stats.symbolic_probability import Expectation
|
801 |
+
if evaluate:
|
802 |
+
return Expectation(expr, condition).doit(**kwargs)
|
803 |
+
return Expectation(expr, condition)
|
804 |
+
|
805 |
+
|
806 |
+
def probability(condition, given_condition=None, numsamples=None,
|
807 |
+
evaluate=True, **kwargs):
|
808 |
+
"""
|
809 |
+
Probability that a condition is true, optionally given a second condition.
|
810 |
+
|
811 |
+
Parameters
|
812 |
+
==========
|
813 |
+
|
814 |
+
condition : Combination of Relationals containing RandomSymbols
|
815 |
+
The condition of which you want to compute the probability
|
816 |
+
given_condition : Combination of Relationals containing RandomSymbols
|
817 |
+
A conditional expression. P(X > 1, X > 0) is expectation of X > 1
|
818 |
+
given X > 0
|
819 |
+
numsamples : int
|
820 |
+
Enables sampling and approximates the probability with this many samples
|
821 |
+
evaluate : Bool (defaults to True)
|
822 |
+
In case of continuous systems return unevaluated integral
|
823 |
+
|
824 |
+
Examples
|
825 |
+
========
|
826 |
+
|
827 |
+
>>> from sympy.stats import P, Die
|
828 |
+
>>> from sympy import Eq
|
829 |
+
>>> X, Y = Die('X', 6), Die('Y', 6)
|
830 |
+
>>> P(X > 3)
|
831 |
+
1/2
|
832 |
+
>>> P(Eq(X, 5), X > 2) # Probability that X == 5 given that X > 2
|
833 |
+
1/4
|
834 |
+
>>> P(X > Y)
|
835 |
+
5/12
|
836 |
+
"""
|
837 |
+
|
838 |
+
kwargs['numsamples'] = numsamples
|
839 |
+
from sympy.stats.symbolic_probability import Probability
|
840 |
+
if evaluate:
|
841 |
+
return Probability(condition, given_condition).doit(**kwargs)
|
842 |
+
return Probability(condition, given_condition)
|
843 |
+
|
844 |
+
|
845 |
+
class Density(Basic):
|
846 |
+
expr = property(lambda self: self.args[0])
|
847 |
+
|
848 |
+
def __new__(cls, expr, condition = None):
|
849 |
+
expr = _sympify(expr)
|
850 |
+
if condition is None:
|
851 |
+
obj = Basic.__new__(cls, expr)
|
852 |
+
else:
|
853 |
+
condition = _sympify(condition)
|
854 |
+
obj = Basic.__new__(cls, expr, condition)
|
855 |
+
return obj
|
856 |
+
|
857 |
+
@property
|
858 |
+
def condition(self):
|
859 |
+
if len(self.args) > 1:
|
860 |
+
return self.args[1]
|
861 |
+
else:
|
862 |
+
return None
|
863 |
+
|
864 |
+
def doit(self, evaluate=True, **kwargs):
|
865 |
+
from sympy.stats.random_matrix import RandomMatrixPSpace
|
866 |
+
from sympy.stats.joint_rv import JointPSpace
|
867 |
+
from sympy.stats.matrix_distributions import MatrixPSpace
|
868 |
+
from sympy.stats.compound_rv import CompoundPSpace
|
869 |
+
from sympy.stats.frv import SingleFiniteDistribution
|
870 |
+
expr, condition = self.expr, self.condition
|
871 |
+
|
872 |
+
if isinstance(expr, SingleFiniteDistribution):
|
873 |
+
return expr.dict
|
874 |
+
if condition is not None:
|
875 |
+
# Recompute on new conditional expr
|
876 |
+
expr = given(expr, condition, **kwargs)
|
877 |
+
if not random_symbols(expr):
|
878 |
+
return Lambda(x, DiracDelta(x - expr))
|
879 |
+
if isinstance(expr, RandomSymbol):
|
880 |
+
if isinstance(expr.pspace, (SinglePSpace, JointPSpace, MatrixPSpace)) and \
|
881 |
+
hasattr(expr.pspace, 'distribution'):
|
882 |
+
return expr.pspace.distribution
|
883 |
+
elif isinstance(expr.pspace, RandomMatrixPSpace):
|
884 |
+
return expr.pspace.model
|
885 |
+
if isinstance(pspace(expr), CompoundPSpace):
|
886 |
+
kwargs['compound_evaluate'] = evaluate
|
887 |
+
result = pspace(expr).compute_density(expr, **kwargs)
|
888 |
+
|
889 |
+
if evaluate and hasattr(result, 'doit'):
|
890 |
+
return result.doit()
|
891 |
+
else:
|
892 |
+
return result
|
893 |
+
|
894 |
+
|
895 |
+
def density(expr, condition=None, evaluate=True, numsamples=None, **kwargs):
|
896 |
+
"""
|
897 |
+
Probability density of a random expression, optionally given a second
|
898 |
+
condition.
|
899 |
+
|
900 |
+
Explanation
|
901 |
+
===========
|
902 |
+
|
903 |
+
This density will take on different forms for different types of
|
904 |
+
probability spaces. Discrete variables produce Dicts. Continuous
|
905 |
+
variables produce Lambdas.
|
906 |
+
|
907 |
+
Parameters
|
908 |
+
==========
|
909 |
+
|
910 |
+
expr : Expr containing RandomSymbols
|
911 |
+
The expression of which you want to compute the density value
|
912 |
+
condition : Relational containing RandomSymbols
|
913 |
+
A conditional expression. density(X > 1, X > 0) is density of X > 1
|
914 |
+
given X > 0
|
915 |
+
numsamples : int
|
916 |
+
Enables sampling and approximates the density with this many samples
|
917 |
+
|
918 |
+
Examples
|
919 |
+
========
|
920 |
+
|
921 |
+
>>> from sympy.stats import density, Die, Normal
|
922 |
+
>>> from sympy import Symbol
|
923 |
+
|
924 |
+
>>> x = Symbol('x')
|
925 |
+
>>> D = Die('D', 6)
|
926 |
+
>>> X = Normal(x, 0, 1)
|
927 |
+
|
928 |
+
>>> density(D).dict
|
929 |
+
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
|
930 |
+
>>> density(2*D).dict
|
931 |
+
{2: 1/6, 4: 1/6, 6: 1/6, 8: 1/6, 10: 1/6, 12: 1/6}
|
932 |
+
>>> density(X)(x)
|
933 |
+
sqrt(2)*exp(-x**2/2)/(2*sqrt(pi))
|
934 |
+
"""
|
935 |
+
|
936 |
+
if numsamples:
|
937 |
+
return sampling_density(expr, condition, numsamples=numsamples,
|
938 |
+
**kwargs)
|
939 |
+
|
940 |
+
return Density(expr, condition).doit(evaluate=evaluate, **kwargs)
|
941 |
+
|
942 |
+
|
943 |
+
def cdf(expr, condition=None, evaluate=True, **kwargs):
|
944 |
+
"""
|
945 |
+
Cumulative Distribution Function of a random expression.
|
946 |
+
|
947 |
+
optionally given a second condition.
|
948 |
+
|
949 |
+
Explanation
|
950 |
+
===========
|
951 |
+
|
952 |
+
This density will take on different forms for different types of
|
953 |
+
probability spaces.
|
954 |
+
Discrete variables produce Dicts.
|
955 |
+
Continuous variables produce Lambdas.
|
956 |
+
|
957 |
+
Examples
|
958 |
+
========
|
959 |
+
|
960 |
+
>>> from sympy.stats import density, Die, Normal, cdf
|
961 |
+
|
962 |
+
>>> D = Die('D', 6)
|
963 |
+
>>> X = Normal('X', 0, 1)
|
964 |
+
|
965 |
+
>>> density(D).dict
|
966 |
+
{1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
|
967 |
+
>>> cdf(D)
|
968 |
+
{1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1}
|
969 |
+
>>> cdf(3*D, D > 2)
|
970 |
+
{9: 1/4, 12: 1/2, 15: 3/4, 18: 1}
|
971 |
+
|
972 |
+
>>> cdf(X)
|
973 |
+
Lambda(_z, erf(sqrt(2)*_z/2)/2 + 1/2)
|
974 |
+
"""
|
975 |
+
if condition is not None: # If there is a condition
|
976 |
+
# Recompute on new conditional expr
|
977 |
+
return cdf(given(expr, condition, **kwargs), **kwargs)
|
978 |
+
|
979 |
+
# Otherwise pass work off to the ProbabilitySpace
|
980 |
+
result = pspace(expr).compute_cdf(expr, **kwargs)
|
981 |
+
|
982 |
+
if evaluate and hasattr(result, 'doit'):
|
983 |
+
return result.doit()
|
984 |
+
else:
|
985 |
+
return result
|
986 |
+
|
987 |
+
|
988 |
+
def characteristic_function(expr, condition=None, evaluate=True, **kwargs):
|
989 |
+
"""
|
990 |
+
Characteristic function of a random expression, optionally given a second condition.
|
991 |
+
|
992 |
+
Returns a Lambda.
|
993 |
+
|
994 |
+
Examples
|
995 |
+
========
|
996 |
+
|
997 |
+
>>> from sympy.stats import Normal, DiscreteUniform, Poisson, characteristic_function
|
998 |
+
|
999 |
+
>>> X = Normal('X', 0, 1)
|
1000 |
+
>>> characteristic_function(X)
|
1001 |
+
Lambda(_t, exp(-_t**2/2))
|
1002 |
+
|
1003 |
+
>>> Y = DiscreteUniform('Y', [1, 2, 7])
|
1004 |
+
>>> characteristic_function(Y)
|
1005 |
+
Lambda(_t, exp(7*_t*I)/3 + exp(2*_t*I)/3 + exp(_t*I)/3)
|
1006 |
+
|
1007 |
+
>>> Z = Poisson('Z', 2)
|
1008 |
+
>>> characteristic_function(Z)
|
1009 |
+
Lambda(_t, exp(2*exp(_t*I) - 2))
|
1010 |
+
"""
|
1011 |
+
if condition is not None:
|
1012 |
+
return characteristic_function(given(expr, condition, **kwargs), **kwargs)
|
1013 |
+
|
1014 |
+
result = pspace(expr).compute_characteristic_function(expr, **kwargs)
|
1015 |
+
|
1016 |
+
if evaluate and hasattr(result, 'doit'):
|
1017 |
+
return result.doit()
|
1018 |
+
else:
|
1019 |
+
return result
|
1020 |
+
|
1021 |
+
def moment_generating_function(expr, condition=None, evaluate=True, **kwargs):
|
1022 |
+
if condition is not None:
|
1023 |
+
return moment_generating_function(given(expr, condition, **kwargs), **kwargs)
|
1024 |
+
|
1025 |
+
result = pspace(expr).compute_moment_generating_function(expr, **kwargs)
|
1026 |
+
|
1027 |
+
if evaluate and hasattr(result, 'doit'):
|
1028 |
+
return result.doit()
|
1029 |
+
else:
|
1030 |
+
return result
|
1031 |
+
|
1032 |
+
def where(condition, given_condition=None, **kwargs):
|
1033 |
+
"""
|
1034 |
+
Returns the domain where a condition is True.
|
1035 |
+
|
1036 |
+
Examples
|
1037 |
+
========
|
1038 |
+
|
1039 |
+
>>> from sympy.stats import where, Die, Normal
|
1040 |
+
>>> from sympy import And
|
1041 |
+
|
1042 |
+
>>> D1, D2 = Die('a', 6), Die('b', 6)
|
1043 |
+
>>> a, b = D1.symbol, D2.symbol
|
1044 |
+
>>> X = Normal('x', 0, 1)
|
1045 |
+
|
1046 |
+
>>> where(X**2<1)
|
1047 |
+
Domain: (-1 < x) & (x < 1)
|
1048 |
+
|
1049 |
+
>>> where(X**2<1).set
|
1050 |
+
Interval.open(-1, 1)
|
1051 |
+
|
1052 |
+
>>> where(And(D1<=D2, D2<3))
|
1053 |
+
Domain: (Eq(a, 1) & Eq(b, 1)) | (Eq(a, 1) & Eq(b, 2)) | (Eq(a, 2) & Eq(b, 2))
|
1054 |
+
"""
|
1055 |
+
if given_condition is not None: # If there is a condition
|
1056 |
+
# Recompute on new conditional expr
|
1057 |
+
return where(given(condition, given_condition, **kwargs), **kwargs)
|
1058 |
+
|
1059 |
+
# Otherwise pass work off to the ProbabilitySpace
|
1060 |
+
return pspace(condition).where(condition, **kwargs)
|
1061 |
+
|
1062 |
+
|
1063 |
+
@doctest_depends_on(modules=('scipy',))
|
1064 |
+
def sample(expr, condition=None, size=(), library='scipy',
|
1065 |
+
numsamples=1, seed=None, **kwargs):
|
1066 |
+
"""
|
1067 |
+
A realization of the random expression.
|
1068 |
+
|
1069 |
+
Parameters
|
1070 |
+
==========
|
1071 |
+
|
1072 |
+
expr : Expression of random variables
|
1073 |
+
Expression from which sample is extracted
|
1074 |
+
condition : Expr containing RandomSymbols
|
1075 |
+
A conditional expression
|
1076 |
+
size : int, tuple
|
1077 |
+
Represents size of each sample in numsamples
|
1078 |
+
library : str
|
1079 |
+
- 'scipy' : Sample using scipy
|
1080 |
+
- 'numpy' : Sample using numpy
|
1081 |
+
- 'pymc' : Sample using PyMC
|
1082 |
+
|
1083 |
+
Choose any of the available options to sample from as string,
|
1084 |
+
by default is 'scipy'
|
1085 |
+
numsamples : int
|
1086 |
+
Number of samples, each with size as ``size``.
|
1087 |
+
|
1088 |
+
.. deprecated:: 1.9
|
1089 |
+
|
1090 |
+
The ``numsamples`` parameter is deprecated and is only provided for
|
1091 |
+
compatibility with v1.8. Use a list comprehension or an additional
|
1092 |
+
dimension in ``size`` instead. See
|
1093 |
+
:ref:`deprecated-sympy-stats-numsamples` for details.
|
1094 |
+
|
1095 |
+
seed :
|
1096 |
+
An object to be used as seed by the given external library for sampling `expr`.
|
1097 |
+
Following is the list of possible types of object for the supported libraries,
|
1098 |
+
|
1099 |
+
- 'scipy': int, numpy.random.RandomState, numpy.random.Generator
|
1100 |
+
- 'numpy': int, numpy.random.RandomState, numpy.random.Generator
|
1101 |
+
- 'pymc': int
|
1102 |
+
|
1103 |
+
Optional, by default None, in which case seed settings
|
1104 |
+
related to the given library will be used.
|
1105 |
+
No modifications to environment's global seed settings
|
1106 |
+
are done by this argument.
|
1107 |
+
|
1108 |
+
Returns
|
1109 |
+
=======
|
1110 |
+
|
1111 |
+
sample: float/list/numpy.ndarray
|
1112 |
+
one sample or a collection of samples of the random expression.
|
1113 |
+
|
1114 |
+
- sample(X) returns float/numpy.float64/numpy.int64 object.
|
1115 |
+
- sample(X, size=int/tuple) returns numpy.ndarray object.
|
1116 |
+
|
1117 |
+
Examples
|
1118 |
+
========
|
1119 |
+
|
1120 |
+
>>> from sympy.stats import Die, sample, Normal, Geometric
|
1121 |
+
>>> X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) # Finite Random Variable
|
1122 |
+
>>> die_roll = sample(X + Y + Z)
|
1123 |
+
>>> die_roll # doctest: +SKIP
|
1124 |
+
3
|
1125 |
+
>>> N = Normal('N', 3, 4) # Continuous Random Variable
|
1126 |
+
>>> samp = sample(N)
|
1127 |
+
>>> samp in N.pspace.domain.set
|
1128 |
+
True
|
1129 |
+
>>> samp = sample(N, N>0)
|
1130 |
+
>>> samp > 0
|
1131 |
+
True
|
1132 |
+
>>> samp_list = sample(N, size=4)
|
1133 |
+
>>> [sam in N.pspace.domain.set for sam in samp_list]
|
1134 |
+
[True, True, True, True]
|
1135 |
+
>>> sample(N, size = (2,3)) # doctest: +SKIP
|
1136 |
+
array([[5.42519758, 6.40207856, 4.94991743],
|
1137 |
+
[1.85819627, 6.83403519, 1.9412172 ]])
|
1138 |
+
>>> G = Geometric('G', 0.5) # Discrete Random Variable
|
1139 |
+
>>> samp_list = sample(G, size=3)
|
1140 |
+
>>> samp_list # doctest: +SKIP
|
1141 |
+
[1, 3, 2]
|
1142 |
+
>>> [sam in G.pspace.domain.set for sam in samp_list]
|
1143 |
+
[True, True, True]
|
1144 |
+
>>> MN = Normal("MN", [3, 4], [[2, 1], [1, 2]]) # Joint Random Variable
|
1145 |
+
>>> samp_list = sample(MN, size=4)
|
1146 |
+
>>> samp_list # doctest: +SKIP
|
1147 |
+
[array([2.85768055, 3.38954165]),
|
1148 |
+
array([4.11163337, 4.3176591 ]),
|
1149 |
+
array([0.79115232, 1.63232916]),
|
1150 |
+
array([4.01747268, 3.96716083])]
|
1151 |
+
>>> [tuple(sam) in MN.pspace.domain.set for sam in samp_list]
|
1152 |
+
[True, True, True, True]
|
1153 |
+
|
1154 |
+
.. versionchanged:: 1.7.0
|
1155 |
+
sample used to return an iterator containing the samples instead of value.
|
1156 |
+
|
1157 |
+
.. versionchanged:: 1.9.0
|
1158 |
+
sample returns values or array of values instead of an iterator and numsamples is deprecated.
|
1159 |
+
|
1160 |
+
"""
|
1161 |
+
|
1162 |
+
iterator = sample_iter(expr, condition, size=size, library=library,
|
1163 |
+
numsamples=numsamples, seed=seed)
|
1164 |
+
|
1165 |
+
if numsamples != 1:
|
1166 |
+
sympy_deprecation_warning(
|
1167 |
+
f"""
|
1168 |
+
The numsamples parameter to sympy.stats.sample() is deprecated.
|
1169 |
+
Either use a list comprehension, like
|
1170 |
+
|
1171 |
+
[sample(...) for i in range({numsamples})]
|
1172 |
+
|
1173 |
+
or add a dimension to size, like
|
1174 |
+
|
1175 |
+
sample(..., size={(numsamples,) + size})
|
1176 |
+
""",
|
1177 |
+
deprecated_since_version="1.9",
|
1178 |
+
active_deprecations_target="deprecated-sympy-stats-numsamples",
|
1179 |
+
)
|
1180 |
+
return [next(iterator) for i in range(numsamples)]
|
1181 |
+
|
1182 |
+
return next(iterator)
|
1183 |
+
|
1184 |
+
|
1185 |
+
def quantile(expr, evaluate=True, **kwargs):
|
1186 |
+
r"""
|
1187 |
+
Return the :math:`p^{th}` order quantile of a probability distribution.
|
1188 |
+
|
1189 |
+
Explanation
|
1190 |
+
===========
|
1191 |
+
|
1192 |
+
Quantile is defined as the value at which the probability of the random
|
1193 |
+
variable is less than or equal to the given probability.
|
1194 |
+
|
1195 |
+
.. math::
|
1196 |
+
Q(p) = \inf\{x \in (-\infty, \infty) : p \le F(x)\}
|
1197 |
+
|
1198 |
+
Examples
|
1199 |
+
========
|
1200 |
+
|
1201 |
+
>>> from sympy.stats import quantile, Die, Exponential
|
1202 |
+
>>> from sympy import Symbol, pprint
|
1203 |
+
>>> p = Symbol("p")
|
1204 |
+
|
1205 |
+
>>> l = Symbol("lambda", positive=True)
|
1206 |
+
>>> X = Exponential("x", l)
|
1207 |
+
>>> quantile(X)(p)
|
1208 |
+
-log(1 - p)/lambda
|
1209 |
+
|
1210 |
+
>>> D = Die("d", 6)
|
1211 |
+
>>> pprint(quantile(D)(p), use_unicode=False)
|
1212 |
+
/nan for Or(p > 1, p < 0)
|
1213 |
+
|
|
1214 |
+
| 1 for p <= 1/6
|
1215 |
+
|
|
1216 |
+
| 2 for p <= 1/3
|
1217 |
+
|
|
1218 |
+
< 3 for p <= 1/2
|
1219 |
+
|
|
1220 |
+
| 4 for p <= 2/3
|
1221 |
+
|
|
1222 |
+
| 5 for p <= 5/6
|
1223 |
+
|
|
1224 |
+
\ 6 for p <= 1
|
1225 |
+
|
1226 |
+
"""
|
1227 |
+
result = pspace(expr).compute_quantile(expr, **kwargs)
|
1228 |
+
|
1229 |
+
if evaluate and hasattr(result, 'doit'):
|
1230 |
+
return result.doit()
|
1231 |
+
else:
|
1232 |
+
return result
|
1233 |
+
|
1234 |
+
def sample_iter(expr, condition=None, size=(), library='scipy',
|
1235 |
+
numsamples=S.Infinity, seed=None, **kwargs):
|
1236 |
+
|
1237 |
+
"""
|
1238 |
+
Returns an iterator of realizations from the expression given a condition.
|
1239 |
+
|
1240 |
+
Parameters
|
1241 |
+
==========
|
1242 |
+
|
1243 |
+
expr: Expr
|
1244 |
+
Random expression to be realized
|
1245 |
+
condition: Expr, optional
|
1246 |
+
A conditional expression
|
1247 |
+
size : int, tuple
|
1248 |
+
Represents size of each sample in numsamples
|
1249 |
+
numsamples: integer, optional
|
1250 |
+
Length of the iterator (defaults to infinity)
|
1251 |
+
seed :
|
1252 |
+
An object to be used as seed by the given external library for sampling `expr`.
|
1253 |
+
Following is the list of possible types of object for the supported libraries,
|
1254 |
+
|
1255 |
+
- 'scipy': int, numpy.random.RandomState, numpy.random.Generator
|
1256 |
+
- 'numpy': int, numpy.random.RandomState, numpy.random.Generator
|
1257 |
+
- 'pymc': int
|
1258 |
+
|
1259 |
+
Optional, by default None, in which case seed settings
|
1260 |
+
related to the given library will be used.
|
1261 |
+
No modifications to environment's global seed settings
|
1262 |
+
are done by this argument.
|
1263 |
+
|
1264 |
+
Examples
|
1265 |
+
========
|
1266 |
+
|
1267 |
+
>>> from sympy.stats import Normal, sample_iter
|
1268 |
+
>>> X = Normal('X', 0, 1)
|
1269 |
+
>>> expr = X*X + 3
|
1270 |
+
>>> iterator = sample_iter(expr, numsamples=3) # doctest: +SKIP
|
1271 |
+
>>> list(iterator) # doctest: +SKIP
|
1272 |
+
[12, 4, 7]
|
1273 |
+
|
1274 |
+
Returns
|
1275 |
+
=======
|
1276 |
+
|
1277 |
+
sample_iter: iterator object
|
1278 |
+
iterator object containing the sample/samples of given expr
|
1279 |
+
|
1280 |
+
See Also
|
1281 |
+
========
|
1282 |
+
|
1283 |
+
sample
|
1284 |
+
sampling_P
|
1285 |
+
sampling_E
|
1286 |
+
|
1287 |
+
"""
|
1288 |
+
from sympy.stats.joint_rv import JointRandomSymbol
|
1289 |
+
if not import_module(library):
|
1290 |
+
raise ValueError("Failed to import %s" % library)
|
1291 |
+
|
1292 |
+
if condition is not None:
|
1293 |
+
ps = pspace(Tuple(expr, condition))
|
1294 |
+
else:
|
1295 |
+
ps = pspace(expr)
|
1296 |
+
|
1297 |
+
rvs = list(ps.values)
|
1298 |
+
if isinstance(expr, JointRandomSymbol):
|
1299 |
+
expr = expr.subs({expr: RandomSymbol(expr.symbol, expr.pspace)})
|
1300 |
+
else:
|
1301 |
+
sub = {}
|
1302 |
+
for arg in expr.args:
|
1303 |
+
if isinstance(arg, JointRandomSymbol):
|
1304 |
+
sub[arg] = RandomSymbol(arg.symbol, arg.pspace)
|
1305 |
+
expr = expr.subs(sub)
|
1306 |
+
|
1307 |
+
def fn_subs(*args):
|
1308 |
+
return expr.subs({rv: arg for rv, arg in zip(rvs, args)})
|
1309 |
+
|
1310 |
+
def given_fn_subs(*args):
|
1311 |
+
if condition is not None:
|
1312 |
+
return condition.subs({rv: arg for rv, arg in zip(rvs, args)})
|
1313 |
+
return False
|
1314 |
+
|
1315 |
+
if library in ('pymc', 'pymc3'):
|
1316 |
+
# Currently unable to lambdify in pymc
|
1317 |
+
# TODO : Remove when lambdify accepts 'pymc' as module
|
1318 |
+
fn = lambdify(rvs, expr, **kwargs)
|
1319 |
+
else:
|
1320 |
+
fn = lambdify(rvs, expr, modules=library, **kwargs)
|
1321 |
+
|
1322 |
+
|
1323 |
+
if condition is not None:
|
1324 |
+
given_fn = lambdify(rvs, condition, **kwargs)
|
1325 |
+
|
1326 |
+
def return_generator_infinite():
|
1327 |
+
count = 0
|
1328 |
+
_size = (1,)+((size,) if isinstance(size, int) else size)
|
1329 |
+
while count < numsamples:
|
1330 |
+
d = ps.sample(size=_size, library=library, seed=seed) # a dictionary that maps RVs to values
|
1331 |
+
args = [d[rv][0] for rv in rvs]
|
1332 |
+
|
1333 |
+
if condition is not None: # Check that these values satisfy the condition
|
1334 |
+
# TODO: Replace the try-except block with only given_fn(*args)
|
1335 |
+
# once lambdify works with unevaluated SymPy objects.
|
1336 |
+
try:
|
1337 |
+
gd = given_fn(*args)
|
1338 |
+
except (NameError, TypeError):
|
1339 |
+
gd = given_fn_subs(*args)
|
1340 |
+
if gd != True and gd != False:
|
1341 |
+
raise ValueError(
|
1342 |
+
"Conditions must not contain free symbols")
|
1343 |
+
if not gd: # If the values don't satisfy then try again
|
1344 |
+
continue
|
1345 |
+
|
1346 |
+
yield fn(*args)
|
1347 |
+
count += 1
|
1348 |
+
|
1349 |
+
def return_generator_finite():
|
1350 |
+
faulty = True
|
1351 |
+
while faulty:
|
1352 |
+
d = ps.sample(size=(numsamples,) + ((size,) if isinstance(size, int) else size),
|
1353 |
+
library=library, seed=seed) # a dictionary that maps RVs to values
|
1354 |
+
|
1355 |
+
faulty = False
|
1356 |
+
count = 0
|
1357 |
+
while count < numsamples and not faulty:
|
1358 |
+
args = [d[rv][count] for rv in rvs]
|
1359 |
+
if condition is not None: # Check that these values satisfy the condition
|
1360 |
+
# TODO: Replace the try-except block with only given_fn(*args)
|
1361 |
+
# once lambdify works with unevaluated SymPy objects.
|
1362 |
+
try:
|
1363 |
+
gd = given_fn(*args)
|
1364 |
+
except (NameError, TypeError):
|
1365 |
+
gd = given_fn_subs(*args)
|
1366 |
+
if gd != True and gd != False:
|
1367 |
+
raise ValueError(
|
1368 |
+
"Conditions must not contain free symbols")
|
1369 |
+
if not gd: # If the values don't satisfy then try again
|
1370 |
+
faulty = True
|
1371 |
+
|
1372 |
+
count += 1
|
1373 |
+
|
1374 |
+
count = 0
|
1375 |
+
while count < numsamples:
|
1376 |
+
args = [d[rv][count] for rv in rvs]
|
1377 |
+
# TODO: Replace the try-except block with only fn(*args)
|
1378 |
+
# once lambdify works with unevaluated SymPy objects.
|
1379 |
+
try:
|
1380 |
+
yield fn(*args)
|
1381 |
+
except (NameError, TypeError):
|
1382 |
+
yield fn_subs(*args)
|
1383 |
+
count += 1
|
1384 |
+
|
1385 |
+
if numsamples is S.Infinity:
|
1386 |
+
return return_generator_infinite()
|
1387 |
+
|
1388 |
+
return return_generator_finite()
|
1389 |
+
|
1390 |
+
def sample_iter_lambdify(expr, condition=None, size=(),
|
1391 |
+
numsamples=S.Infinity, seed=None, **kwargs):
|
1392 |
+
|
1393 |
+
return sample_iter(expr, condition=condition, size=size,
|
1394 |
+
numsamples=numsamples, seed=seed, **kwargs)
|
1395 |
+
|
1396 |
+
def sample_iter_subs(expr, condition=None, size=(),
|
1397 |
+
numsamples=S.Infinity, seed=None, **kwargs):
|
1398 |
+
|
1399 |
+
return sample_iter(expr, condition=condition, size=size,
|
1400 |
+
numsamples=numsamples, seed=seed, **kwargs)
|
1401 |
+
|
1402 |
+
|
1403 |
+
def sampling_P(condition, given_condition=None, library='scipy', numsamples=1,
|
1404 |
+
evalf=True, seed=None, **kwargs):
|
1405 |
+
"""
|
1406 |
+
Sampling version of P.
|
1407 |
+
|
1408 |
+
See Also
|
1409 |
+
========
|
1410 |
+
|
1411 |
+
P
|
1412 |
+
sampling_E
|
1413 |
+
sampling_density
|
1414 |
+
|
1415 |
+
"""
|
1416 |
+
|
1417 |
+
count_true = 0
|
1418 |
+
count_false = 0
|
1419 |
+
samples = sample_iter(condition, given_condition, library=library,
|
1420 |
+
numsamples=numsamples, seed=seed, **kwargs)
|
1421 |
+
|
1422 |
+
for sample in samples:
|
1423 |
+
if sample:
|
1424 |
+
count_true += 1
|
1425 |
+
else:
|
1426 |
+
count_false += 1
|
1427 |
+
|
1428 |
+
result = S(count_true) / numsamples
|
1429 |
+
if evalf:
|
1430 |
+
return result.evalf()
|
1431 |
+
else:
|
1432 |
+
return result
|
1433 |
+
|
1434 |
+
|
1435 |
+
def sampling_E(expr, given_condition=None, library='scipy', numsamples=1,
|
1436 |
+
evalf=True, seed=None, **kwargs):
|
1437 |
+
"""
|
1438 |
+
Sampling version of E.
|
1439 |
+
|
1440 |
+
See Also
|
1441 |
+
========
|
1442 |
+
|
1443 |
+
P
|
1444 |
+
sampling_P
|
1445 |
+
sampling_density
|
1446 |
+
"""
|
1447 |
+
samples = list(sample_iter(expr, given_condition, library=library,
|
1448 |
+
numsamples=numsamples, seed=seed, **kwargs))
|
1449 |
+
result = Add(*samples) / numsamples
|
1450 |
+
|
1451 |
+
if evalf:
|
1452 |
+
return result.evalf()
|
1453 |
+
else:
|
1454 |
+
return result
|
1455 |
+
|
1456 |
+
def sampling_density(expr, given_condition=None, library='scipy',
|
1457 |
+
numsamples=1, seed=None, **kwargs):
|
1458 |
+
"""
|
1459 |
+
Sampling version of density.
|
1460 |
+
|
1461 |
+
See Also
|
1462 |
+
========
|
1463 |
+
density
|
1464 |
+
sampling_P
|
1465 |
+
sampling_E
|
1466 |
+
"""
|
1467 |
+
|
1468 |
+
results = {}
|
1469 |
+
for result in sample_iter(expr, given_condition, library=library,
|
1470 |
+
numsamples=numsamples, seed=seed, **kwargs):
|
1471 |
+
results[result] = results.get(result, 0) + 1
|
1472 |
+
|
1473 |
+
return results
|
1474 |
+
|
1475 |
+
|
1476 |
+
def dependent(a, b):
|
1477 |
+
"""
|
1478 |
+
Dependence of two random expressions.
|
1479 |
+
|
1480 |
+
Two expressions are independent if knowledge of one does not change
|
1481 |
+
computations on the other.
|
1482 |
+
|
1483 |
+
Examples
|
1484 |
+
========
|
1485 |
+
|
1486 |
+
>>> from sympy.stats import Normal, dependent, given
|
1487 |
+
>>> from sympy import Tuple, Eq
|
1488 |
+
|
1489 |
+
>>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
|
1490 |
+
>>> dependent(X, Y)
|
1491 |
+
False
|
1492 |
+
>>> dependent(2*X + Y, -Y)
|
1493 |
+
True
|
1494 |
+
>>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
|
1495 |
+
>>> dependent(X, Y)
|
1496 |
+
True
|
1497 |
+
|
1498 |
+
See Also
|
1499 |
+
========
|
1500 |
+
|
1501 |
+
independent
|
1502 |
+
"""
|
1503 |
+
if pspace_independent(a, b):
|
1504 |
+
return False
|
1505 |
+
|
1506 |
+
z = Symbol('z', real=True)
|
1507 |
+
# Dependent if density is unchanged when one is given information about
|
1508 |
+
# the other
|
1509 |
+
return (density(a, Eq(b, z)) != density(a) or
|
1510 |
+
density(b, Eq(a, z)) != density(b))
|
1511 |
+
|
1512 |
+
|
1513 |
+
def independent(a, b):
|
1514 |
+
"""
|
1515 |
+
Independence of two random expressions.
|
1516 |
+
|
1517 |
+
Two expressions are independent if knowledge of one does not change
|
1518 |
+
computations on the other.
|
1519 |
+
|
1520 |
+
Examples
|
1521 |
+
========
|
1522 |
+
|
1523 |
+
>>> from sympy.stats import Normal, independent, given
|
1524 |
+
>>> from sympy import Tuple, Eq
|
1525 |
+
|
1526 |
+
>>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
|
1527 |
+
>>> independent(X, Y)
|
1528 |
+
True
|
1529 |
+
>>> independent(2*X + Y, -Y)
|
1530 |
+
False
|
1531 |
+
>>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
|
1532 |
+
>>> independent(X, Y)
|
1533 |
+
False
|
1534 |
+
|
1535 |
+
See Also
|
1536 |
+
========
|
1537 |
+
|
1538 |
+
dependent
|
1539 |
+
"""
|
1540 |
+
return not dependent(a, b)
|
1541 |
+
|
1542 |
+
|
1543 |
+
def pspace_independent(a, b):
|
1544 |
+
"""
|
1545 |
+
Tests for independence between a and b by checking if their PSpaces have
|
1546 |
+
overlapping symbols. This is a sufficient but not necessary condition for
|
1547 |
+
independence and is intended to be used internally.
|
1548 |
+
|
1549 |
+
Notes
|
1550 |
+
=====
|
1551 |
+
|
1552 |
+
pspace_independent(a, b) implies independent(a, b)
|
1553 |
+
independent(a, b) does not imply pspace_independent(a, b)
|
1554 |
+
"""
|
1555 |
+
a_symbols = set(pspace(b).symbols)
|
1556 |
+
b_symbols = set(pspace(a).symbols)
|
1557 |
+
|
1558 |
+
if len(set(random_symbols(a)).intersection(random_symbols(b))) != 0:
|
1559 |
+
return False
|
1560 |
+
|
1561 |
+
if len(a_symbols.intersection(b_symbols)) == 0:
|
1562 |
+
return True
|
1563 |
+
return None
|
1564 |
+
|
1565 |
+
|
1566 |
+
def rv_subs(expr, symbols=None):
|
1567 |
+
"""
|
1568 |
+
Given a random expression replace all random variables with their symbols.
|
1569 |
+
|
1570 |
+
If symbols keyword is given restrict the swap to only the symbols listed.
|
1571 |
+
"""
|
1572 |
+
if symbols is None:
|
1573 |
+
symbols = random_symbols(expr)
|
1574 |
+
if not symbols:
|
1575 |
+
return expr
|
1576 |
+
swapdict = {rv: rv.symbol for rv in symbols}
|
1577 |
+
return expr.subs(swapdict)
|
1578 |
+
|
1579 |
+
|
1580 |
+
class NamedArgsMixin:
|
1581 |
+
_argnames: tuple[str, ...] = ()
|
1582 |
+
|
1583 |
+
def __getattr__(self, attr):
|
1584 |
+
try:
|
1585 |
+
return self.args[self._argnames.index(attr)]
|
1586 |
+
except ValueError:
|
1587 |
+
raise AttributeError("'%s' object has no attribute '%s'" % (
|
1588 |
+
type(self).__name__, attr))
|
1589 |
+
|
1590 |
+
|
1591 |
+
class Distribution(Basic):
|
1592 |
+
|
1593 |
+
def sample(self, size=(), library='scipy', seed=None):
|
1594 |
+
""" A random realization from the distribution """
|
1595 |
+
|
1596 |
+
module = import_module(library)
|
1597 |
+
if library in {'scipy', 'numpy', 'pymc3', 'pymc'} and module is None:
|
1598 |
+
raise ValueError("Failed to import %s" % library)
|
1599 |
+
|
1600 |
+
if library == 'scipy':
|
1601 |
+
# scipy does not require map as it can handle using custom distributions.
|
1602 |
+
# However, we will still use a map where we can.
|
1603 |
+
|
1604 |
+
# TODO: do this for drv.py and frv.py if necessary.
|
1605 |
+
# TODO: add more distributions here if there are more
|
1606 |
+
# See links below referring to sections beginning with "A common parametrization..."
|
1607 |
+
# I will remove all these comments if everything is ok.
|
1608 |
+
|
1609 |
+
from sympy.stats.sampling.sample_scipy import do_sample_scipy
|
1610 |
+
import numpy
|
1611 |
+
if seed is None or isinstance(seed, int):
|
1612 |
+
rand_state = numpy.random.default_rng(seed=seed)
|
1613 |
+
else:
|
1614 |
+
rand_state = seed
|
1615 |
+
samps = do_sample_scipy(self, size, rand_state)
|
1616 |
+
|
1617 |
+
elif library == 'numpy':
|
1618 |
+
from sympy.stats.sampling.sample_numpy import do_sample_numpy
|
1619 |
+
import numpy
|
1620 |
+
if seed is None or isinstance(seed, int):
|
1621 |
+
rand_state = numpy.random.default_rng(seed=seed)
|
1622 |
+
else:
|
1623 |
+
rand_state = seed
|
1624 |
+
_size = None if size == () else size
|
1625 |
+
samps = do_sample_numpy(self, _size, rand_state)
|
1626 |
+
elif library in ('pymc', 'pymc3'):
|
1627 |
+
from sympy.stats.sampling.sample_pymc import do_sample_pymc
|
1628 |
+
import logging
|
1629 |
+
logging.getLogger("pymc").setLevel(logging.ERROR)
|
1630 |
+
try:
|
1631 |
+
import pymc
|
1632 |
+
except ImportError:
|
1633 |
+
import pymc3 as pymc
|
1634 |
+
|
1635 |
+
with pymc.Model():
|
1636 |
+
if do_sample_pymc(self):
|
1637 |
+
samps = pymc.sample(draws=prod(size), chains=1, compute_convergence_checks=False,
|
1638 |
+
progressbar=False, random_seed=seed, return_inferencedata=False)[:]['X']
|
1639 |
+
samps = samps.reshape(size)
|
1640 |
+
else:
|
1641 |
+
samps = None
|
1642 |
+
|
1643 |
+
else:
|
1644 |
+
raise NotImplementedError("Sampling from %s is not supported yet."
|
1645 |
+
% str(library))
|
1646 |
+
|
1647 |
+
if samps is not None:
|
1648 |
+
return samps
|
1649 |
+
raise NotImplementedError(
|
1650 |
+
"Sampling for %s is not currently implemented from %s"
|
1651 |
+
% (self, library))
|
1652 |
+
|
1653 |
+
|
1654 |
+
def _value_check(condition, message):
|
1655 |
+
"""
|
1656 |
+
Raise a ValueError with message if condition is False, else
|
1657 |
+
return True if all conditions were True, else False.
|
1658 |
+
|
1659 |
+
Examples
|
1660 |
+
========
|
1661 |
+
|
1662 |
+
>>> from sympy.stats.rv import _value_check
|
1663 |
+
>>> from sympy.abc import a, b, c
|
1664 |
+
>>> from sympy import And, Dummy
|
1665 |
+
|
1666 |
+
>>> _value_check(2 < 3, '')
|
1667 |
+
True
|
1668 |
+
|
1669 |
+
Here, the condition is not False, but it does not evaluate to True
|
1670 |
+
so False is returned (but no error is raised). So checking if the
|
1671 |
+
return value is True or False will tell you if all conditions were
|
1672 |
+
evaluated.
|
1673 |
+
|
1674 |
+
>>> _value_check(a < b, '')
|
1675 |
+
False
|
1676 |
+
|
1677 |
+
In this case the condition is False so an error is raised:
|
1678 |
+
|
1679 |
+
>>> r = Dummy(real=True)
|
1680 |
+
>>> _value_check(r < r - 1, 'condition is not true')
|
1681 |
+
Traceback (most recent call last):
|
1682 |
+
...
|
1683 |
+
ValueError: condition is not true
|
1684 |
+
|
1685 |
+
If no condition of many conditions must be False, they can be
|
1686 |
+
checked by passing them as an iterable:
|
1687 |
+
|
1688 |
+
>>> _value_check((a < 0, b < 0, c < 0), '')
|
1689 |
+
False
|
1690 |
+
|
1691 |
+
The iterable can be a generator, too:
|
1692 |
+
|
1693 |
+
>>> _value_check((i < 0 for i in (a, b, c)), '')
|
1694 |
+
False
|
1695 |
+
|
1696 |
+
The following are equivalent to the above but do not pass
|
1697 |
+
an iterable:
|
1698 |
+
|
1699 |
+
>>> all(_value_check(i < 0, '') for i in (a, b, c))
|
1700 |
+
False
|
1701 |
+
>>> _value_check(And(a < 0, b < 0, c < 0), '')
|
1702 |
+
False
|
1703 |
+
"""
|
1704 |
+
if not iterable(condition):
|
1705 |
+
condition = [condition]
|
1706 |
+
truth = fuzzy_and(condition)
|
1707 |
+
if truth == False:
|
1708 |
+
raise ValueError(message)
|
1709 |
+
return truth == True
|
1710 |
+
|
1711 |
+
def _symbol_converter(sym):
|
1712 |
+
"""
|
1713 |
+
Casts the parameter to Symbol if it is 'str'
|
1714 |
+
otherwise no operation is performed on it.
|
1715 |
+
|
1716 |
+
Parameters
|
1717 |
+
==========
|
1718 |
+
|
1719 |
+
sym
|
1720 |
+
The parameter to be converted.
|
1721 |
+
|
1722 |
+
Returns
|
1723 |
+
=======
|
1724 |
+
|
1725 |
+
Symbol
|
1726 |
+
the parameter converted to Symbol.
|
1727 |
+
|
1728 |
+
Raises
|
1729 |
+
======
|
1730 |
+
|
1731 |
+
TypeError
|
1732 |
+
If the parameter is not an instance of both str and
|
1733 |
+
Symbol.
|
1734 |
+
|
1735 |
+
Examples
|
1736 |
+
========
|
1737 |
+
|
1738 |
+
>>> from sympy import Symbol
|
1739 |
+
>>> from sympy.stats.rv import _symbol_converter
|
1740 |
+
>>> s = _symbol_converter('s')
|
1741 |
+
>>> isinstance(s, Symbol)
|
1742 |
+
True
|
1743 |
+
>>> _symbol_converter(1)
|
1744 |
+
Traceback (most recent call last):
|
1745 |
+
...
|
1746 |
+
TypeError: 1 is neither a Symbol nor a string
|
1747 |
+
>>> r = Symbol('r')
|
1748 |
+
>>> isinstance(r, Symbol)
|
1749 |
+
True
|
1750 |
+
"""
|
1751 |
+
if isinstance(sym, str):
|
1752 |
+
sym = Symbol(sym)
|
1753 |
+
if not isinstance(sym, Symbol):
|
1754 |
+
raise TypeError("%s is neither a Symbol nor a string"%(sym))
|
1755 |
+
return sym
|
1756 |
+
|
1757 |
+
def sample_stochastic_process(process):
|
1758 |
+
"""
|
1759 |
+
This function is used to sample from stochastic process.
|
1760 |
+
|
1761 |
+
Parameters
|
1762 |
+
==========
|
1763 |
+
|
1764 |
+
process: StochasticProcess
|
1765 |
+
Process used to extract the samples. It must be an instance of
|
1766 |
+
StochasticProcess
|
1767 |
+
|
1768 |
+
Examples
|
1769 |
+
========
|
1770 |
+
|
1771 |
+
>>> from sympy.stats import sample_stochastic_process, DiscreteMarkovChain
|
1772 |
+
>>> from sympy import Matrix
|
1773 |
+
>>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
|
1774 |
+
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
|
1775 |
+
>>> next(sample_stochastic_process(Y)) in Y.state_space
|
1776 |
+
True
|
1777 |
+
>>> next(sample_stochastic_process(Y)) # doctest: +SKIP
|
1778 |
+
0
|
1779 |
+
>>> next(sample_stochastic_process(Y)) # doctest: +SKIP
|
1780 |
+
2
|
1781 |
+
|
1782 |
+
Returns
|
1783 |
+
=======
|
1784 |
+
|
1785 |
+
sample: iterator object
|
1786 |
+
iterator object containing the sample of given process
|
1787 |
+
|
1788 |
+
"""
|
1789 |
+
from sympy.stats.stochastic_process_types import StochasticProcess
|
1790 |
+
if not isinstance(process, StochasticProcess):
|
1791 |
+
raise ValueError("Process must be an instance of Stochastic Process")
|
1792 |
+
return process.sample()
|
llmeval-env/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
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (193 Bytes). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_numpy.cpython-310.pyc
ADDED
Binary file (3.94 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_pymc.cpython-310.pyc
ADDED
Binary file (3.37 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/__pycache__/sample_scipy.cpython-310.pyc
ADDED
Binary file (5.82 kB). View file
|
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/sample_numpy.py
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import singledispatch
|
2 |
+
|
3 |
+
from sympy.external import import_module
|
4 |
+
from sympy.stats.crv_types import BetaDistribution, ChiSquaredDistribution, ExponentialDistribution, GammaDistribution, \
|
5 |
+
LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution, FDistributionDistribution, GumbelDistribution, LaplaceDistribution, \
|
6 |
+
LogisticDistribution, RayleighDistribution, TriangularDistribution
|
7 |
+
from sympy.stats.drv_types import GeometricDistribution, PoissonDistribution, ZetaDistribution
|
8 |
+
from sympy.stats.frv_types import BinomialDistribution, HypergeometricDistribution
|
9 |
+
|
10 |
+
|
11 |
+
numpy = import_module('numpy')
|
12 |
+
|
13 |
+
|
14 |
+
@singledispatch
|
15 |
+
def do_sample_numpy(dist, size, rand_state):
|
16 |
+
return None
|
17 |
+
|
18 |
+
|
19 |
+
# CRV:
|
20 |
+
|
21 |
+
@do_sample_numpy.register(BetaDistribution)
|
22 |
+
def _(dist: BetaDistribution, size, rand_state):
|
23 |
+
return rand_state.beta(a=float(dist.alpha), b=float(dist.beta), size=size)
|
24 |
+
|
25 |
+
|
26 |
+
@do_sample_numpy.register(ChiSquaredDistribution)
|
27 |
+
def _(dist: ChiSquaredDistribution, size, rand_state):
|
28 |
+
return rand_state.chisquare(df=float(dist.k), size=size)
|
29 |
+
|
30 |
+
|
31 |
+
@do_sample_numpy.register(ExponentialDistribution)
|
32 |
+
def _(dist: ExponentialDistribution, size, rand_state):
|
33 |
+
return rand_state.exponential(1 / float(dist.rate), size=size)
|
34 |
+
|
35 |
+
@do_sample_numpy.register(FDistributionDistribution)
|
36 |
+
def _(dist: FDistributionDistribution, size, rand_state):
|
37 |
+
return rand_state.f(dfnum = float(dist.d1), dfden = float(dist.d2), size=size)
|
38 |
+
|
39 |
+
@do_sample_numpy.register(GammaDistribution)
|
40 |
+
def _(dist: GammaDistribution, size, rand_state):
|
41 |
+
return rand_state.gamma(shape = float(dist.k), scale = float(dist.theta), size=size)
|
42 |
+
|
43 |
+
@do_sample_numpy.register(GumbelDistribution)
|
44 |
+
def _(dist: GumbelDistribution, size, rand_state):
|
45 |
+
return rand_state.gumbel(loc = float(dist.mu), scale = float(dist.beta), size=size)
|
46 |
+
|
47 |
+
@do_sample_numpy.register(LaplaceDistribution)
|
48 |
+
def _(dist: LaplaceDistribution, size, rand_state):
|
49 |
+
return rand_state.laplace(loc = float(dist.mu), scale = float(dist.b), size=size)
|
50 |
+
|
51 |
+
@do_sample_numpy.register(LogisticDistribution)
|
52 |
+
def _(dist: LogisticDistribution, size, rand_state):
|
53 |
+
return rand_state.logistic(loc = float(dist.mu), scale = float(dist.s), size=size)
|
54 |
+
|
55 |
+
@do_sample_numpy.register(LogNormalDistribution)
|
56 |
+
def _(dist: LogNormalDistribution, size, rand_state):
|
57 |
+
return rand_state.lognormal(mean = float(dist.mean), sigma = float(dist.std), size=size)
|
58 |
+
|
59 |
+
@do_sample_numpy.register(NormalDistribution)
|
60 |
+
def _(dist: NormalDistribution, size, rand_state):
|
61 |
+
return rand_state.normal(loc = float(dist.mean), scale = float(dist.std), size=size)
|
62 |
+
|
63 |
+
@do_sample_numpy.register(RayleighDistribution)
|
64 |
+
def _(dist: RayleighDistribution, size, rand_state):
|
65 |
+
return rand_state.rayleigh(scale = float(dist.sigma), size=size)
|
66 |
+
|
67 |
+
@do_sample_numpy.register(ParetoDistribution)
|
68 |
+
def _(dist: ParetoDistribution, size, rand_state):
|
69 |
+
return (numpy.random.pareto(a=float(dist.alpha), size=size) + 1) * float(dist.xm)
|
70 |
+
|
71 |
+
@do_sample_numpy.register(TriangularDistribution)
|
72 |
+
def _(dist: TriangularDistribution, size, rand_state):
|
73 |
+
return rand_state.triangular(left = float(dist.a), mode = float(dist.b), right = float(dist.c), size=size)
|
74 |
+
|
75 |
+
@do_sample_numpy.register(UniformDistribution)
|
76 |
+
def _(dist: UniformDistribution, size, rand_state):
|
77 |
+
return rand_state.uniform(low=float(dist.left), high=float(dist.right), size=size)
|
78 |
+
|
79 |
+
|
80 |
+
# DRV:
|
81 |
+
|
82 |
+
@do_sample_numpy.register(GeometricDistribution)
|
83 |
+
def _(dist: GeometricDistribution, size, rand_state):
|
84 |
+
return rand_state.geometric(p=float(dist.p), size=size)
|
85 |
+
|
86 |
+
|
87 |
+
@do_sample_numpy.register(PoissonDistribution)
|
88 |
+
def _(dist: PoissonDistribution, size, rand_state):
|
89 |
+
return rand_state.poisson(lam=float(dist.lamda), size=size)
|
90 |
+
|
91 |
+
|
92 |
+
@do_sample_numpy.register(ZetaDistribution)
|
93 |
+
def _(dist: ZetaDistribution, size, rand_state):
|
94 |
+
return rand_state.zipf(a=float(dist.s), size=size)
|
95 |
+
|
96 |
+
|
97 |
+
# FRV:
|
98 |
+
|
99 |
+
@do_sample_numpy.register(BinomialDistribution)
|
100 |
+
def _(dist: BinomialDistribution, size, rand_state):
|
101 |
+
return rand_state.binomial(n=int(dist.n), p=float(dist.p), size=size)
|
102 |
+
|
103 |
+
@do_sample_numpy.register(HypergeometricDistribution)
|
104 |
+
def _(dist: HypergeometricDistribution, size, rand_state):
|
105 |
+
return rand_state.hypergeometric(ngood = int(dist.N), nbad = int(dist.m), nsample = int(dist.n), size=size)
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/sample_pymc.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import singledispatch
|
2 |
+
from sympy.external import import_module
|
3 |
+
from sympy.stats.crv_types import BetaDistribution, CauchyDistribution, ChiSquaredDistribution, ExponentialDistribution, \
|
4 |
+
GammaDistribution, LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution, \
|
5 |
+
GaussianInverseDistribution
|
6 |
+
from sympy.stats.drv_types import PoissonDistribution, GeometricDistribution, NegativeBinomialDistribution
|
7 |
+
from sympy.stats.frv_types import BinomialDistribution, BernoulliDistribution
|
8 |
+
|
9 |
+
|
10 |
+
try:
|
11 |
+
import pymc
|
12 |
+
except ImportError:
|
13 |
+
pymc = import_module('pymc3')
|
14 |
+
|
15 |
+
@singledispatch
|
16 |
+
def do_sample_pymc(dist):
|
17 |
+
return None
|
18 |
+
|
19 |
+
|
20 |
+
# CRV:
|
21 |
+
|
22 |
+
@do_sample_pymc.register(BetaDistribution)
|
23 |
+
def _(dist: BetaDistribution):
|
24 |
+
return pymc.Beta('X', alpha=float(dist.alpha), beta=float(dist.beta))
|
25 |
+
|
26 |
+
|
27 |
+
@do_sample_pymc.register(CauchyDistribution)
|
28 |
+
def _(dist: CauchyDistribution):
|
29 |
+
return pymc.Cauchy('X', alpha=float(dist.x0), beta=float(dist.gamma))
|
30 |
+
|
31 |
+
|
32 |
+
@do_sample_pymc.register(ChiSquaredDistribution)
|
33 |
+
def _(dist: ChiSquaredDistribution):
|
34 |
+
return pymc.ChiSquared('X', nu=float(dist.k))
|
35 |
+
|
36 |
+
|
37 |
+
@do_sample_pymc.register(ExponentialDistribution)
|
38 |
+
def _(dist: ExponentialDistribution):
|
39 |
+
return pymc.Exponential('X', lam=float(dist.rate))
|
40 |
+
|
41 |
+
|
42 |
+
@do_sample_pymc.register(GammaDistribution)
|
43 |
+
def _(dist: GammaDistribution):
|
44 |
+
return pymc.Gamma('X', alpha=float(dist.k), beta=1 / float(dist.theta))
|
45 |
+
|
46 |
+
|
47 |
+
@do_sample_pymc.register(LogNormalDistribution)
|
48 |
+
def _(dist: LogNormalDistribution):
|
49 |
+
return pymc.Lognormal('X', mu=float(dist.mean), sigma=float(dist.std))
|
50 |
+
|
51 |
+
|
52 |
+
@do_sample_pymc.register(NormalDistribution)
|
53 |
+
def _(dist: NormalDistribution):
|
54 |
+
return pymc.Normal('X', float(dist.mean), float(dist.std))
|
55 |
+
|
56 |
+
|
57 |
+
@do_sample_pymc.register(GaussianInverseDistribution)
|
58 |
+
def _(dist: GaussianInverseDistribution):
|
59 |
+
return pymc.Wald('X', mu=float(dist.mean), lam=float(dist.shape))
|
60 |
+
|
61 |
+
|
62 |
+
@do_sample_pymc.register(ParetoDistribution)
|
63 |
+
def _(dist: ParetoDistribution):
|
64 |
+
return pymc.Pareto('X', alpha=float(dist.alpha), m=float(dist.xm))
|
65 |
+
|
66 |
+
|
67 |
+
@do_sample_pymc.register(UniformDistribution)
|
68 |
+
def _(dist: UniformDistribution):
|
69 |
+
return pymc.Uniform('X', lower=float(dist.left), upper=float(dist.right))
|
70 |
+
|
71 |
+
|
72 |
+
# DRV:
|
73 |
+
|
74 |
+
@do_sample_pymc.register(GeometricDistribution)
|
75 |
+
def _(dist: GeometricDistribution):
|
76 |
+
return pymc.Geometric('X', p=float(dist.p))
|
77 |
+
|
78 |
+
|
79 |
+
@do_sample_pymc.register(NegativeBinomialDistribution)
|
80 |
+
def _(dist: NegativeBinomialDistribution):
|
81 |
+
return pymc.NegativeBinomial('X', mu=float((dist.p * dist.r) / (1 - dist.p)),
|
82 |
+
alpha=float(dist.r))
|
83 |
+
|
84 |
+
|
85 |
+
@do_sample_pymc.register(PoissonDistribution)
|
86 |
+
def _(dist: PoissonDistribution):
|
87 |
+
return pymc.Poisson('X', mu=float(dist.lamda))
|
88 |
+
|
89 |
+
|
90 |
+
# FRV:
|
91 |
+
|
92 |
+
@do_sample_pymc.register(BernoulliDistribution)
|
93 |
+
def _(dist: BernoulliDistribution):
|
94 |
+
return pymc.Bernoulli('X', p=float(dist.p))
|
95 |
+
|
96 |
+
|
97 |
+
@do_sample_pymc.register(BinomialDistribution)
|
98 |
+
def _(dist: BinomialDistribution):
|
99 |
+
return pymc.Binomial('X', n=int(dist.n), p=float(dist.p))
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/sample_scipy.py
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import singledispatch
|
2 |
+
|
3 |
+
from sympy.core.symbol import Dummy
|
4 |
+
from sympy.functions.elementary.exponential import exp
|
5 |
+
from sympy.utilities.lambdify import lambdify
|
6 |
+
from sympy.external import import_module
|
7 |
+
from sympy.stats import DiscreteDistributionHandmade
|
8 |
+
from sympy.stats.crv import SingleContinuousDistribution
|
9 |
+
from sympy.stats.crv_types import ChiSquaredDistribution, ExponentialDistribution, GammaDistribution, \
|
10 |
+
LogNormalDistribution, NormalDistribution, ParetoDistribution, UniformDistribution, BetaDistribution, \
|
11 |
+
StudentTDistribution, CauchyDistribution
|
12 |
+
from sympy.stats.drv_types import GeometricDistribution, LogarithmicDistribution, NegativeBinomialDistribution, \
|
13 |
+
PoissonDistribution, SkellamDistribution, YuleSimonDistribution, ZetaDistribution
|
14 |
+
from sympy.stats.frv import SingleFiniteDistribution
|
15 |
+
|
16 |
+
|
17 |
+
scipy = import_module("scipy", import_kwargs={'fromlist':['stats']})
|
18 |
+
|
19 |
+
|
20 |
+
@singledispatch
|
21 |
+
def do_sample_scipy(dist, size, seed):
|
22 |
+
return None
|
23 |
+
|
24 |
+
|
25 |
+
# CRV
|
26 |
+
|
27 |
+
@do_sample_scipy.register(SingleContinuousDistribution)
|
28 |
+
def _(dist: SingleContinuousDistribution, size, seed):
|
29 |
+
# if we don't need to make a handmade pdf, we won't
|
30 |
+
import scipy.stats
|
31 |
+
|
32 |
+
z = Dummy('z')
|
33 |
+
handmade_pdf = lambdify(z, dist.pdf(z), ['numpy', 'scipy'])
|
34 |
+
|
35 |
+
class scipy_pdf(scipy.stats.rv_continuous):
|
36 |
+
def _pdf(dist, x):
|
37 |
+
return handmade_pdf(x)
|
38 |
+
|
39 |
+
scipy_rv = scipy_pdf(a=float(dist.set._inf),
|
40 |
+
b=float(dist.set._sup), name='scipy_pdf')
|
41 |
+
return scipy_rv.rvs(size=size, random_state=seed)
|
42 |
+
|
43 |
+
|
44 |
+
@do_sample_scipy.register(ChiSquaredDistribution)
|
45 |
+
def _(dist: ChiSquaredDistribution, size, seed):
|
46 |
+
# same parametrisation
|
47 |
+
return scipy.stats.chi2.rvs(df=float(dist.k), size=size, random_state=seed)
|
48 |
+
|
49 |
+
|
50 |
+
@do_sample_scipy.register(ExponentialDistribution)
|
51 |
+
def _(dist: ExponentialDistribution, size, seed):
|
52 |
+
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.expon.html#scipy.stats.expon
|
53 |
+
return scipy.stats.expon.rvs(scale=1 / float(dist.rate), size=size, random_state=seed)
|
54 |
+
|
55 |
+
|
56 |
+
@do_sample_scipy.register(GammaDistribution)
|
57 |
+
def _(dist: GammaDistribution, size, seed):
|
58 |
+
# https://stackoverflow.com/questions/42150965/how-to-plot-gamma-distribution-with-alpha-and-beta-parameters-in-python
|
59 |
+
return scipy.stats.gamma.rvs(a=float(dist.k), scale=float(dist.theta), size=size, random_state=seed)
|
60 |
+
|
61 |
+
|
62 |
+
@do_sample_scipy.register(LogNormalDistribution)
|
63 |
+
def _(dist: LogNormalDistribution, size, seed):
|
64 |
+
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html
|
65 |
+
return scipy.stats.lognorm.rvs(scale=float(exp(dist.mean)), s=float(dist.std), size=size, random_state=seed)
|
66 |
+
|
67 |
+
|
68 |
+
@do_sample_scipy.register(NormalDistribution)
|
69 |
+
def _(dist: NormalDistribution, size, seed):
|
70 |
+
return scipy.stats.norm.rvs(loc=float(dist.mean), scale=float(dist.std), size=size, random_state=seed)
|
71 |
+
|
72 |
+
|
73 |
+
@do_sample_scipy.register(ParetoDistribution)
|
74 |
+
def _(dist: ParetoDistribution, size, seed):
|
75 |
+
# https://stackoverflow.com/questions/42260519/defining-pareto-distribution-in-python-scipy
|
76 |
+
return scipy.stats.pareto.rvs(b=float(dist.alpha), scale=float(dist.xm), size=size, random_state=seed)
|
77 |
+
|
78 |
+
|
79 |
+
@do_sample_scipy.register(StudentTDistribution)
|
80 |
+
def _(dist: StudentTDistribution, size, seed):
|
81 |
+
return scipy.stats.t.rvs(df=float(dist.nu), size=size, random_state=seed)
|
82 |
+
|
83 |
+
|
84 |
+
@do_sample_scipy.register(UniformDistribution)
|
85 |
+
def _(dist: UniformDistribution, size, seed):
|
86 |
+
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.uniform.html
|
87 |
+
return scipy.stats.uniform.rvs(loc=float(dist.left), scale=float(dist.right - dist.left), size=size, random_state=seed)
|
88 |
+
|
89 |
+
|
90 |
+
@do_sample_scipy.register(BetaDistribution)
|
91 |
+
def _(dist: BetaDistribution, size, seed):
|
92 |
+
# same parametrisation
|
93 |
+
return scipy.stats.beta.rvs(a=float(dist.alpha), b=float(dist.beta), size=size, random_state=seed)
|
94 |
+
|
95 |
+
|
96 |
+
@do_sample_scipy.register(CauchyDistribution)
|
97 |
+
def _(dist: CauchyDistribution, size, seed):
|
98 |
+
return scipy.stats.cauchy.rvs(loc=float(dist.x0), scale=float(dist.gamma), size=size, random_state=seed)
|
99 |
+
|
100 |
+
|
101 |
+
# DRV:
|
102 |
+
|
103 |
+
@do_sample_scipy.register(DiscreteDistributionHandmade)
|
104 |
+
def _(dist: DiscreteDistributionHandmade, size, seed):
|
105 |
+
from scipy.stats import rv_discrete
|
106 |
+
|
107 |
+
z = Dummy('z')
|
108 |
+
handmade_pmf = lambdify(z, dist.pdf(z), ['numpy', 'scipy'])
|
109 |
+
|
110 |
+
class scipy_pmf(rv_discrete):
|
111 |
+
def _pmf(dist, x):
|
112 |
+
return handmade_pmf(x)
|
113 |
+
|
114 |
+
scipy_rv = scipy_pmf(a=float(dist.set._inf), b=float(dist.set._sup),
|
115 |
+
name='scipy_pmf')
|
116 |
+
return scipy_rv.rvs(size=size, random_state=seed)
|
117 |
+
|
118 |
+
|
119 |
+
@do_sample_scipy.register(GeometricDistribution)
|
120 |
+
def _(dist: GeometricDistribution, size, seed):
|
121 |
+
return scipy.stats.geom.rvs(p=float(dist.p), size=size, random_state=seed)
|
122 |
+
|
123 |
+
|
124 |
+
@do_sample_scipy.register(LogarithmicDistribution)
|
125 |
+
def _(dist: LogarithmicDistribution, size, seed):
|
126 |
+
return scipy.stats.logser.rvs(p=float(dist.p), size=size, random_state=seed)
|
127 |
+
|
128 |
+
|
129 |
+
@do_sample_scipy.register(NegativeBinomialDistribution)
|
130 |
+
def _(dist: NegativeBinomialDistribution, size, seed):
|
131 |
+
return scipy.stats.nbinom.rvs(n=float(dist.r), p=float(dist.p), size=size, random_state=seed)
|
132 |
+
|
133 |
+
|
134 |
+
@do_sample_scipy.register(PoissonDistribution)
|
135 |
+
def _(dist: PoissonDistribution, size, seed):
|
136 |
+
return scipy.stats.poisson.rvs(mu=float(dist.lamda), size=size, random_state=seed)
|
137 |
+
|
138 |
+
|
139 |
+
@do_sample_scipy.register(SkellamDistribution)
|
140 |
+
def _(dist: SkellamDistribution, size, seed):
|
141 |
+
return scipy.stats.skellam.rvs(mu1=float(dist.mu1), mu2=float(dist.mu2), size=size, random_state=seed)
|
142 |
+
|
143 |
+
|
144 |
+
@do_sample_scipy.register(YuleSimonDistribution)
|
145 |
+
def _(dist: YuleSimonDistribution, size, seed):
|
146 |
+
return scipy.stats.yulesimon.rvs(alpha=float(dist.rho), size=size, random_state=seed)
|
147 |
+
|
148 |
+
|
149 |
+
@do_sample_scipy.register(ZetaDistribution)
|
150 |
+
def _(dist: ZetaDistribution, size, seed):
|
151 |
+
return scipy.stats.zipf.rvs(a=float(dist.s), size=size, random_state=seed)
|
152 |
+
|
153 |
+
|
154 |
+
# FRV:
|
155 |
+
|
156 |
+
@do_sample_scipy.register(SingleFiniteDistribution)
|
157 |
+
def _(dist: SingleFiniteDistribution, size, seed):
|
158 |
+
# scipy can handle with custom distributions
|
159 |
+
|
160 |
+
from scipy.stats import rv_discrete
|
161 |
+
density_ = dist.dict
|
162 |
+
x, y = [], []
|
163 |
+
for k, v in density_.items():
|
164 |
+
x.append(int(k))
|
165 |
+
y.append(float(v))
|
166 |
+
scipy_rv = rv_discrete(name='scipy_rv', values=(x, y))
|
167 |
+
return scipy_rv.rvs(size=size, random_state=seed)
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/tests/__init__.py
ADDED
File without changes
|
llmeval-env/lib/python3.10/site-packages/sympy/stats/sampling/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (199 Bytes). View file
|
|