crv.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. """
  2. Continuous Random Variables Module
  3. See Also
  4. ========
  5. sympy.stats.crv_types
  6. sympy.stats.rv
  7. sympy.stats.frv
  8. """
  9. from sympy.core.basic import Basic
  10. from sympy.core.cache import cacheit
  11. from sympy.core.function import Lambda, PoleError
  12. from sympy.core.numbers import (I, nan, oo)
  13. from sympy.core.relational import (Eq, Ne)
  14. from sympy.core.singleton import S
  15. from sympy.core.symbol import (Dummy, symbols)
  16. from sympy.core.sympify import _sympify, sympify
  17. from sympy.functions.combinatorial.factorials import factorial
  18. from sympy.functions.elementary.exponential import exp
  19. from sympy.functions.elementary.piecewise import Piecewise
  20. from sympy.functions.special.delta_functions import DiracDelta
  21. from sympy.integrals.integrals import (Integral, integrate)
  22. from sympy.logic.boolalg import (And, Or)
  23. from sympy.polys.polyerrors import PolynomialError
  24. from sympy.polys.polytools import poly
  25. from sympy.series.series import series
  26. from sympy.sets.sets import (FiniteSet, Intersection, Interval, Union)
  27. from sympy.solvers.solveset import solveset
  28. from sympy.solvers.inequalities import reduce_rational_inequalities
  29. from sympy.stats.rv import (RandomDomain, SingleDomain, ConditionalDomain, is_random,
  30. ProductDomain, PSpace, SinglePSpace, random_symbols, NamedArgsMixin, Distribution)
  31. class ContinuousDomain(RandomDomain):
  32. """
  33. A domain with continuous support
  34. Represented using symbols and Intervals.
  35. """
  36. is_Continuous = True
  37. def as_boolean(self):
  38. raise NotImplementedError("Not Implemented for generic Domains")
  39. class SingleContinuousDomain(ContinuousDomain, SingleDomain):
  40. """
  41. A univariate domain with continuous support
  42. Represented using a single symbol and interval.
  43. """
  44. def compute_expectation(self, expr, variables=None, **kwargs):
  45. if variables is None:
  46. variables = self.symbols
  47. if not variables:
  48. return expr
  49. if frozenset(variables) != frozenset(self.symbols):
  50. raise ValueError("Values should be equal")
  51. # assumes only intervals
  52. return Integral(expr, (self.symbol, self.set), **kwargs)
  53. def as_boolean(self):
  54. return self.set.as_relational(self.symbol)
  55. class ProductContinuousDomain(ProductDomain, ContinuousDomain):
  56. """
  57. A collection of independent domains with continuous support
  58. """
  59. def compute_expectation(self, expr, variables=None, **kwargs):
  60. if variables is None:
  61. variables = self.symbols
  62. for domain in self.domains:
  63. domain_vars = frozenset(variables) & frozenset(domain.symbols)
  64. if domain_vars:
  65. expr = domain.compute_expectation(expr, domain_vars, **kwargs)
  66. return expr
  67. def as_boolean(self):
  68. return And(*[domain.as_boolean() for domain in self.domains])
  69. class ConditionalContinuousDomain(ContinuousDomain, ConditionalDomain):
  70. """
  71. A domain with continuous support that has been further restricted by a
  72. condition such as $x > 3$.
  73. """
  74. def compute_expectation(self, expr, variables=None, **kwargs):
  75. if variables is None:
  76. variables = self.symbols
  77. if not variables:
  78. return expr
  79. # Extract the full integral
  80. fullintgrl = self.fulldomain.compute_expectation(expr, variables)
  81. # separate into integrand and limits
  82. integrand, limits = fullintgrl.function, list(fullintgrl.limits)
  83. conditions = [self.condition]
  84. while conditions:
  85. cond = conditions.pop()
  86. if cond.is_Boolean:
  87. if isinstance(cond, And):
  88. conditions.extend(cond.args)
  89. elif isinstance(cond, Or):
  90. raise NotImplementedError("Or not implemented here")
  91. elif cond.is_Relational:
  92. if cond.is_Equality:
  93. # Add the appropriate Delta to the integrand
  94. integrand *= DiracDelta(cond.lhs - cond.rhs)
  95. else:
  96. symbols = cond.free_symbols & set(self.symbols)
  97. if len(symbols) != 1: # Can't handle x > y
  98. raise NotImplementedError(
  99. "Multivariate Inequalities not yet implemented")
  100. # Can handle x > 0
  101. symbol = symbols.pop()
  102. # Find the limit with x, such as (x, -oo, oo)
  103. for i, limit in enumerate(limits):
  104. if limit[0] == symbol:
  105. # Make condition into an Interval like [0, oo]
  106. cintvl = reduce_rational_inequalities_wrap(
  107. cond, symbol)
  108. # Make limit into an Interval like [-oo, oo]
  109. lintvl = Interval(limit[1], limit[2])
  110. # Intersect them to get [0, oo]
  111. intvl = cintvl.intersect(lintvl)
  112. # Put back into limits list
  113. limits[i] = (symbol, intvl.left, intvl.right)
  114. else:
  115. raise TypeError(
  116. "Condition %s is not a relational or Boolean" % cond)
  117. return Integral(integrand, *limits, **kwargs)
  118. def as_boolean(self):
  119. return And(self.fulldomain.as_boolean(), self.condition)
  120. @property
  121. def set(self):
  122. if len(self.symbols) == 1:
  123. return (self.fulldomain.set & reduce_rational_inequalities_wrap(
  124. self.condition, tuple(self.symbols)[0]))
  125. else:
  126. raise NotImplementedError(
  127. "Set of Conditional Domain not Implemented")
  128. class ContinuousDistribution(Distribution):
  129. def __call__(self, *args):
  130. return self.pdf(*args)
  131. class SingleContinuousDistribution(ContinuousDistribution, NamedArgsMixin):
  132. """ Continuous distribution of a single variable.
  133. Explanation
  134. ===========
  135. Serves as superclass for Normal/Exponential/UniformDistribution etc....
  136. Represented by parameters for each of the specific classes. E.g
  137. NormalDistribution is represented by a mean and standard deviation.
  138. Provides methods for pdf, cdf, and sampling.
  139. See Also
  140. ========
  141. sympy.stats.crv_types.*
  142. """
  143. set = Interval(-oo, oo)
  144. def __new__(cls, *args):
  145. args = list(map(sympify, args))
  146. return Basic.__new__(cls, *args)
  147. @staticmethod
  148. def check(*args):
  149. pass
  150. @cacheit
  151. def compute_cdf(self, **kwargs):
  152. """ Compute the CDF from the PDF.
  153. Returns a Lambda.
  154. """
  155. x, z = symbols('x, z', real=True, cls=Dummy)
  156. left_bound = self.set.start
  157. # CDF is integral of PDF from left bound to z
  158. pdf = self.pdf(x)
  159. cdf = integrate(pdf.doit(), (x, left_bound, z), **kwargs)
  160. # CDF Ensure that CDF left of left_bound is zero
  161. cdf = Piecewise((cdf, z >= left_bound), (0, True))
  162. return Lambda(z, cdf)
  163. def _cdf(self, x):
  164. return None
  165. def cdf(self, x, **kwargs):
  166. """ Cumulative density function """
  167. if len(kwargs) == 0:
  168. cdf = self._cdf(x)
  169. if cdf is not None:
  170. return cdf
  171. return self.compute_cdf(**kwargs)(x)
  172. @cacheit
  173. def compute_characteristic_function(self, **kwargs):
  174. """ Compute the characteristic function from the PDF.
  175. Returns a Lambda.
  176. """
  177. x, t = symbols('x, t', real=True, cls=Dummy)
  178. pdf = self.pdf(x)
  179. cf = integrate(exp(I*t*x)*pdf, (x, self.set))
  180. return Lambda(t, cf)
  181. def _characteristic_function(self, t):
  182. return None
  183. def characteristic_function(self, t, **kwargs):
  184. """ Characteristic function """
  185. if len(kwargs) == 0:
  186. cf = self._characteristic_function(t)
  187. if cf is not None:
  188. return cf
  189. return self.compute_characteristic_function(**kwargs)(t)
  190. @cacheit
  191. def compute_moment_generating_function(self, **kwargs):
  192. """ Compute the moment generating function from the PDF.
  193. Returns a Lambda.
  194. """
  195. x, t = symbols('x, t', real=True, cls=Dummy)
  196. pdf = self.pdf(x)
  197. mgf = integrate(exp(t * x) * pdf, (x, self.set))
  198. return Lambda(t, mgf)
  199. def _moment_generating_function(self, t):
  200. return None
  201. def moment_generating_function(self, t, **kwargs):
  202. """ Moment generating function """
  203. if not kwargs:
  204. mgf = self._moment_generating_function(t)
  205. if mgf is not None:
  206. return mgf
  207. return self.compute_moment_generating_function(**kwargs)(t)
  208. def expectation(self, expr, var, evaluate=True, **kwargs):
  209. """ Expectation of expression over distribution """
  210. if evaluate:
  211. try:
  212. p = poly(expr, var)
  213. if p.is_zero:
  214. return S.Zero
  215. t = Dummy('t', real=True)
  216. mgf = self._moment_generating_function(t)
  217. if mgf is None:
  218. return integrate(expr * self.pdf(var), (var, self.set), **kwargs)
  219. deg = p.degree()
  220. taylor = poly(series(mgf, t, 0, deg + 1).removeO(), t)
  221. result = 0
  222. for k in range(deg+1):
  223. result += p.coeff_monomial(var ** k) * taylor.coeff_monomial(t ** k) * factorial(k)
  224. return result
  225. except PolynomialError:
  226. return integrate(expr * self.pdf(var), (var, self.set), **kwargs)
  227. else:
  228. return Integral(expr * self.pdf(var), (var, self.set), **kwargs)
  229. @cacheit
  230. def compute_quantile(self, **kwargs):
  231. """ Compute the Quantile from the PDF.
  232. Returns a Lambda.
  233. """
  234. x, p = symbols('x, p', real=True, cls=Dummy)
  235. left_bound = self.set.start
  236. pdf = self.pdf(x)
  237. cdf = integrate(pdf, (x, left_bound, x), **kwargs)
  238. quantile = solveset(cdf - p, x, self.set)
  239. return Lambda(p, Piecewise((quantile, (p >= 0) & (p <= 1) ), (nan, True)))
  240. def _quantile(self, x):
  241. return None
  242. def quantile(self, x, **kwargs):
  243. """ Cumulative density function """
  244. if len(kwargs) == 0:
  245. quantile = self._quantile(x)
  246. if quantile is not None:
  247. return quantile
  248. return self.compute_quantile(**kwargs)(x)
  249. class ContinuousPSpace(PSpace):
  250. """ Continuous Probability Space
  251. Represents the likelihood of an event space defined over a continuum.
  252. Represented with a ContinuousDomain and a PDF (Lambda-Like)
  253. """
  254. is_Continuous = True
  255. is_real = True
  256. @property
  257. def pdf(self):
  258. return self.density(*self.domain.symbols)
  259. def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
  260. if rvs is None:
  261. rvs = self.values
  262. else:
  263. rvs = frozenset(rvs)
  264. expr = expr.xreplace({rv: rv.symbol for rv in rvs})
  265. domain_symbols = frozenset(rv.symbol for rv in rvs)
  266. return self.domain.compute_expectation(self.pdf * expr,
  267. domain_symbols, **kwargs)
  268. def compute_density(self, expr, **kwargs):
  269. # Common case Density(X) where X in self.values
  270. if expr in self.values:
  271. # Marginalize all other random symbols out of the density
  272. randomsymbols = tuple(set(self.values) - frozenset([expr]))
  273. symbols = tuple(rs.symbol for rs in randomsymbols)
  274. pdf = self.domain.compute_expectation(self.pdf, symbols, **kwargs)
  275. return Lambda(expr.symbol, pdf)
  276. z = Dummy('z', real=True)
  277. return Lambda(z, self.compute_expectation(DiracDelta(expr - z), **kwargs))
  278. @cacheit
  279. def compute_cdf(self, expr, **kwargs):
  280. if not self.domain.set.is_Interval:
  281. raise ValueError(
  282. "CDF not well defined on multivariate expressions")
  283. d = self.compute_density(expr, **kwargs)
  284. x, z = symbols('x, z', real=True, cls=Dummy)
  285. left_bound = self.domain.set.start
  286. # CDF is integral of PDF from left bound to z
  287. cdf = integrate(d(x), (x, left_bound, z), **kwargs)
  288. # CDF Ensure that CDF left of left_bound is zero
  289. cdf = Piecewise((cdf, z >= left_bound), (0, True))
  290. return Lambda(z, cdf)
  291. @cacheit
  292. def compute_characteristic_function(self, expr, **kwargs):
  293. if not self.domain.set.is_Interval:
  294. raise NotImplementedError("Characteristic function of multivariate expressions not implemented")
  295. d = self.compute_density(expr, **kwargs)
  296. x, t = symbols('x, t', real=True, cls=Dummy)
  297. cf = integrate(exp(I*t*x)*d(x), (x, -oo, oo), **kwargs)
  298. return Lambda(t, cf)
  299. @cacheit
  300. def compute_moment_generating_function(self, expr, **kwargs):
  301. if not self.domain.set.is_Interval:
  302. raise NotImplementedError("Moment generating function of multivariate expressions not implemented")
  303. d = self.compute_density(expr, **kwargs)
  304. x, t = symbols('x, t', real=True, cls=Dummy)
  305. mgf = integrate(exp(t * x) * d(x), (x, -oo, oo), **kwargs)
  306. return Lambda(t, mgf)
  307. @cacheit
  308. def compute_quantile(self, expr, **kwargs):
  309. if not self.domain.set.is_Interval:
  310. raise ValueError(
  311. "Quantile not well defined on multivariate expressions")
  312. d = self.compute_cdf(expr, **kwargs)
  313. x = Dummy('x', real=True)
  314. p = Dummy('p', positive=True)
  315. quantile = solveset(d(x) - p, x, self.set)
  316. return Lambda(p, quantile)
  317. def probability(self, condition, **kwargs):
  318. z = Dummy('z', real=True)
  319. cond_inv = False
  320. if isinstance(condition, Ne):
  321. condition = Eq(condition.args[0], condition.args[1])
  322. cond_inv = True
  323. # Univariate case can be handled by where
  324. try:
  325. domain = self.where(condition)
  326. rv = [rv for rv in self.values if rv.symbol == domain.symbol][0]
  327. # Integrate out all other random variables
  328. pdf = self.compute_density(rv, **kwargs)
  329. # return S.Zero if `domain` is empty set
  330. if domain.set is S.EmptySet or isinstance(domain.set, FiniteSet):
  331. return S.Zero if not cond_inv else S.One
  332. if isinstance(domain.set, Union):
  333. return sum(
  334. Integral(pdf(z), (z, subset), **kwargs) for subset in
  335. domain.set.args if isinstance(subset, Interval))
  336. # Integrate out the last variable over the special domain
  337. return Integral(pdf(z), (z, domain.set), **kwargs)
  338. # Other cases can be turned into univariate case
  339. # by computing a density handled by density computation
  340. except NotImplementedError:
  341. from sympy.stats.rv import density
  342. expr = condition.lhs - condition.rhs
  343. if not is_random(expr):
  344. dens = self.density
  345. comp = condition.rhs
  346. else:
  347. dens = density(expr, **kwargs)
  348. comp = 0
  349. if not isinstance(dens, ContinuousDistribution):
  350. from sympy.stats.crv_types import ContinuousDistributionHandmade
  351. dens = ContinuousDistributionHandmade(dens, set=self.domain.set)
  352. # Turn problem into univariate case
  353. space = SingleContinuousPSpace(z, dens)
  354. result = space.probability(condition.__class__(space.value, comp))
  355. return result if not cond_inv else S.One - result
  356. def where(self, condition):
  357. rvs = frozenset(random_symbols(condition))
  358. if not (len(rvs) == 1 and rvs.issubset(self.values)):
  359. raise NotImplementedError(
  360. "Multiple continuous random variables not supported")
  361. rv = tuple(rvs)[0]
  362. interval = reduce_rational_inequalities_wrap(condition, rv)
  363. interval = interval.intersect(self.domain.set)
  364. return SingleContinuousDomain(rv.symbol, interval)
  365. def conditional_space(self, condition, normalize=True, **kwargs):
  366. condition = condition.xreplace({rv: rv.symbol for rv in self.values})
  367. domain = ConditionalContinuousDomain(self.domain, condition)
  368. if normalize:
  369. # create a clone of the variable to
  370. # make sure that variables in nested integrals are different
  371. # from the variables outside the integral
  372. # this makes sure that they are evaluated separately
  373. # and in the correct order
  374. replacement = {rv: Dummy(str(rv)) for rv in self.symbols}
  375. norm = domain.compute_expectation(self.pdf, **kwargs)
  376. pdf = self.pdf / norm.xreplace(replacement)
  377. # XXX: Converting set to tuple. The order matters to Lambda though
  378. # so we shouldn't be starting with a set here...
  379. density = Lambda(tuple(domain.symbols), pdf)
  380. return ContinuousPSpace(domain, density)
  381. class SingleContinuousPSpace(ContinuousPSpace, SinglePSpace):
  382. """
  383. A continuous probability space over a single univariate variable.
  384. These consist of a Symbol and a SingleContinuousDistribution
  385. This class is normally accessed through the various random variable
  386. functions, Normal, Exponential, Uniform, etc....
  387. """
  388. @property
  389. def set(self):
  390. return self.distribution.set
  391. @property
  392. def domain(self):
  393. return SingleContinuousDomain(sympify(self.symbol), self.set)
  394. def sample(self, size=(), library='scipy', seed=None):
  395. """
  396. Internal sample method.
  397. Returns dictionary mapping RandomSymbol to realization value.
  398. """
  399. return {self.value: self.distribution.sample(size, library=library, seed=seed)}
  400. def compute_expectation(self, expr, rvs=None, evaluate=False, **kwargs):
  401. rvs = rvs or (self.value,)
  402. if self.value not in rvs:
  403. return expr
  404. expr = _sympify(expr)
  405. expr = expr.xreplace({rv: rv.symbol for rv in rvs})
  406. x = self.value.symbol
  407. try:
  408. return self.distribution.expectation(expr, x, evaluate=evaluate, **kwargs)
  409. except PoleError:
  410. return Integral(expr * self.pdf, (x, self.set), **kwargs)
  411. def compute_cdf(self, expr, **kwargs):
  412. if expr == self.value:
  413. z = Dummy("z", real=True)
  414. return Lambda(z, self.distribution.cdf(z, **kwargs))
  415. else:
  416. return ContinuousPSpace.compute_cdf(self, expr, **kwargs)
  417. def compute_characteristic_function(self, expr, **kwargs):
  418. if expr == self.value:
  419. t = Dummy("t", real=True)
  420. return Lambda(t, self.distribution.characteristic_function(t, **kwargs))
  421. else:
  422. return ContinuousPSpace.compute_characteristic_function(self, expr, **kwargs)
  423. def compute_moment_generating_function(self, expr, **kwargs):
  424. if expr == self.value:
  425. t = Dummy("t", real=True)
  426. return Lambda(t, self.distribution.moment_generating_function(t, **kwargs))
  427. else:
  428. return ContinuousPSpace.compute_moment_generating_function(self, expr, **kwargs)
  429. def compute_density(self, expr, **kwargs):
  430. # https://en.wikipedia.org/wiki/Random_variable#Functions_of_random_variables
  431. if expr == self.value:
  432. return self.density
  433. y = Dummy('y', real=True)
  434. gs = solveset(expr - y, self.value, S.Reals)
  435. if isinstance(gs, Intersection) and S.Reals in gs.args:
  436. gs = list(gs.args[1])
  437. if not gs:
  438. raise ValueError("Can not solve %s for %s"%(expr, self.value))
  439. fx = self.compute_density(self.value)
  440. fy = sum(fx(g) * abs(g.diff(y)) for g in gs)
  441. return Lambda(y, fy)
  442. def compute_quantile(self, expr, **kwargs):
  443. if expr == self.value:
  444. p = Dummy("p", real=True)
  445. return Lambda(p, self.distribution.quantile(p, **kwargs))
  446. else:
  447. return ContinuousPSpace.compute_quantile(self, expr, **kwargs)
  448. def _reduce_inequalities(conditions, var, **kwargs):
  449. try:
  450. return reduce_rational_inequalities(conditions, var, **kwargs)
  451. except PolynomialError:
  452. raise ValueError("Reduction of condition failed %s\n" % conditions[0])
  453. def reduce_rational_inequalities_wrap(condition, var):
  454. if condition.is_Relational:
  455. return _reduce_inequalities([[condition]], var, relational=False)
  456. if isinstance(condition, Or):
  457. return Union(*[_reduce_inequalities([[arg]], var, relational=False)
  458. for arg in condition.args])
  459. if isinstance(condition, And):
  460. intervals = [_reduce_inequalities([[arg]], var, relational=False)
  461. for arg in condition.args]
  462. I = intervals[0]
  463. for i in intervals:
  464. I = I.intersect(i)
  465. return I