
    wg                    X   d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ ddlmZmZ ddlmZ ddlmZmZ ddlmZ ddl m!Z! ddl"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddlm-Z- ddlm.Z. ddl/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddgiZ= ed       Z>ed!        Z?e?j                  e
      d"        ZA G d# d$e
      ZB G d% d&eB      ZC G d' d(eB      ZD G d) d*eB      ZE G d+ d,e
      ZF G d- d.eF      ZG G d/ d0e      ZH G d1 d2eH      ZI G d3 d4eHe(      ZJ G d5 d6eF      ZK G d7 d8eK      ZL G d9 d:eB      ZMd; ZNd< ZOd= ZPd> ZQd`d@ZRdadAZS	 	 dadBZT G dC dDe
      ZUdbdEZVdcdFZWdcdGZXdcdHZYd`dIZZ e8dJK      	 	 dddM       Z[dedNZ\d?dLdej                  d?fdOZ^d?dLej                  d?fdPZ_d?dLej                  d?fdQZ`	 	 dfdRZa	 	 dfdSZb	 	 dgdTZcdU ZddV ZedW Zfd`dXZg G dY dZ      Zh G d[ d\e
      Zid] Zjd^ Zkd_ Zly?)ha  
Main Random Variables Module

Defines abstract random variable type.
Contains interfaces for probability space object (PSpace) as well as standard
operators, P, E, sample, density, where, quantile

See Also
========

sympy.stats.crv
sympy.stats.frv
sympy.stats.rv_interface
    )annotations)singledispatch)prod)Add)Basic)Tuple)Expr)FunctionLambda)	fuzzy_and)Mul)EqNe)S)DummySymbol)sympify)
DiracDelta)KroneckerDelta)AndOr)MatrixSymbol)Indexed)lambdify)
Relational)_sympify)	FiniteSet
ProductSetIntersection)solveset)import_module)doctest_depends_on)sympy_deprecation_warning)iterable)samplescipyxc                     yNF )r'   s    S/home/mcse/projects/flask/flask-venv/lib/python3.12/site-packages/sympy/stats/rv.py	is_randomr,   5   s        c                >    | j                   }t        d |D              S )Nc              3  2   K   | ]  }t        |        y wN)r,   ).0is     r+   	<genexpr>z_.<locals>.<genexpr>=   s     +y|+s   )free_symbolsany)r'   atomss     r+   _r7   :   s    NNE+U+++r-   c                  R    e Zd ZdZdZdZdZdZd Ze	d        Z
e	d        Zd Zd Zy)	RandomDomainz
    Represents a set of variables and the values which they can take.

    See Also
    ========

    sympy.stats.crv.ContinuousDomain
    sympy.stats.frv.FiniteDomain
    Fc                @    t        | }t        j                  | |g| S r0   )r   r   __new__)clssymbolsargss      r+   r;   zRandomDomain.__new__P   s"    W%}}S'1D11r-   c                     | j                   d   S Nr   r>   selfs    r+   r=   zRandomDomain.symbolsT       yy|r-   c                     | j                   d   S N   rA   rB   s    r+   setzRandomDomain.setX   rD   r-   c                    t               r0   NotImplementedError)rC   others     r+   __contains__zRandomDomain.__contains__\       !##r-   c                    t               r0   rJ   rC   exprs     r+   compute_expectationz RandomDomain.compute_expectation_   rN   r-   N)__name__
__module____qualname____doc__is_ProductDomain	is_Finiteis_Continuousis_Discreter;   propertyr=   rH   rM   rR   r*   r-   r+   r9   r9   @   sU     IMK2    $$r-   r9   c                  <    e Zd ZdZd Zed        Zed        Zd Zy)SingleDomainz
    A single variable and its domain.

    See Also
    ========

    sympy.stats.crv.SingleContinuousDomain
    sympy.stats.frv.SingleFiniteDomain
    c                L    |j                   sJ t        j                  | ||      S r0   )	is_Symbolr   r;   r<   symbolrH   s      r+   r;   zSingleDomain.__new__m   s$    }}S&#..r-   c                     | j                   d   S r@   rA   rB   s    r+   ra   zSingleDomain.symbolq   rD   r-   c                ,    t        | j                        S r0   r   ra   rB   s    r+   r=   zSingleDomain.symbolsu       %%r-   c                    t        |      dk7  ryt        |      d   \  }}| j                  |k(  xr || j                  v S )NrG   Fr   )lentuplera   rH   )rC   rL   symvals       r+   rM   zSingleDomain.__contains__y   s=    u:?<?S{{c!5cTXXo5r-   N)	rS   rT   rU   rV   r;   r[   ra   r=   rM   r*   r-   r+   r]   r]   c   s9    /   & &6r-   r]   c                  6    e Zd ZdZd Zed        Zed        Zy)MatrixDomainz3
    A Random Matrix variable and its domain.

    c                \    t        |      t        |      }}t        j                  | ||      S r0   )_symbol_converterr   r   r;   r`   s      r+   r;   zMatrixDomain.__new__   s'    '/#}}S&#..r-   c                     | j                   d   S r@   rA   rB   s    r+   ra   zMatrixDomain.symbol   rD   r-   c                ,    t        | j                        S r0   rd   rB   s    r+   r=   zMatrixDomain.symbols   re   r-   N)rS   rT   rU   rV   r;   r[   ra   r=   r*   r-   r+   rl   rl      s4    /   & &r-   rl   c                  \    e Zd ZdZd Zed        Zed        Zed        Zed        Z	d Z
y)	ConditionalDomainz
    A RandomDomain with an attached condition.

    See Also
    ========

    sympy.stats.crv.ConditionalContinuousDomain
    sympy.stats.frv.ConditionalFiniteDomain
    c                    |j                  t        |      D ci c]  }||j                   c}      }t        j                  | ||      S c c}w r0   )xreplacerandom_symbolsra   r   r;   )r<   
fulldomain	conditionrss       r+   r;   zConditionalDomain.__new__   sM    &&$Y/(1 )+BII (1 2	}}S*i88(1s   Ac                .    | j                   j                  S r0   )rv   r=   rB   s    r+   r=   zConditionalDomain.symbols   s    &&&r-   c                     | j                   d   S r@   rA   rB   s    r+   rv   zConditionalDomain.fulldomain   rD   r-   c                     | j                   d   S rF   rA   rB   s    r+   rw   zConditionalDomain.condition   rD   r-   c                    t        d      )Nz)Set of Conditional Domain not ImplementedrJ   rB   s    r+   rH   zConditionalDomain.set   s    !"MNNr-   c                ^    t        | j                  j                         | j                        S r0   )r   rv   
as_booleanrw   rB   s    r+   r~   zConditionalDomain.as_boolean   s     4??--/@@r-   N)rS   rT   rU   rV   r;   r[   r=   rv   rw   rH   r~   r*   r-   r+   rr   rr      sd    9
 ' '     O OAr-   rr   c                      e Zd ZdZdZdZdZdZed        Z	ed        Z
ed        Zed        Zd Zd Zdd	Zd
 Zd Zy)PSpacea}  
    A Probability Space.

    Explanation
    ===========

    Probability Spaces encode processes that equal different values
    probabilistically. These underly Random Symbols which occur in SymPy
    expressions and contain the mechanics to evaluate statistical statements.

    See Also
    ========

    sympy.stats.crv.ContinuousPSpace
    sympy.stats.frv.FinitePSpace
    Nc                     | j                   d   S r@   rA   rB   s    r+   domainzPSpace.domain   rD   r-   c                     | j                   d   S rF   rA   rB   s    r+   densityzPSpace.density   rD   r-   c                @     t         fd j                  D              S )Nc              3  6   K   | ]  }t        |        y wr0   )RandomSymbol)r1   ri   rC   s     r+   r3   z PSpace.values.<locals>.<genexpr>   s     ISc40Is   )	frozensetr=   rB   s   `r+   valueszPSpace.values   s    IDLLIIIr-   c                .    | j                   j                  S r0   )r   r=   rB   s    r+   r=   zPSpace.symbols   s    {{"""r-   c                    t               r0   rJ   rC   rw   s     r+   wherezPSpace.where   rN   r-   c                    t               r0   rJ   rP   s     r+   compute_densityzPSpace.compute_density   rN   r-   c                    t               r0   rJ   )rC   sizelibraryseeds       r+   r%   zPSpace.sample   rN   r-   c                    t               r0   rJ   r   s     r+   probabilityzPSpace.probability   rN   r-   c                    t               r0   rJ   rP   s     r+   rR   zPSpace.compute_expectation   rN   r-   r*   r&   N)rS   rT   rU   rV   rX   rY   rZ   is_realr[   r   r   r   r=   r   r   r%   r   rR   r*   r-   r+   r   r      s    " IMKG    J J # #$$$$$r-   r   c                  V    e Zd ZdZd Zed        Zed        Zed        Zed        Z	y)SinglePSpacezx
    Represents the probabilities of a set of random events that can be
    attributed to a single variable/symbol.
    c                F    t        |      }t        j                  | ||      S r0   )rn   r   r;   )r<   sdistributions      r+   r;   zSinglePSpace.__new__   s    a }}S!\22r-   c                .    t        | j                  |       S r0   )r   ra   rB   s    r+   valuezSinglePSpace.value   s    DKK..r-   c                     | j                   d   S r@   rA   rB   s    r+   ra   zSinglePSpace.symbol   rD   r-   c                     | j                   d   S rF   rA   rB   s    r+   r   zSinglePSpace.distribution   rD   r-   c                L    | j                   j                  | j                        S r0   )r   pdfra   rB   s    r+   r   zSinglePSpace.pdf  s      $$T[[11r-   N)
rS   rT   rU   rV   r;   r[   r   ra   r   r   r*   r-   r+   r   r      s\    3 / /     2 2r-   r   c                      e Zd ZdZddZdZdZdZdZ e	d       Z
 e	d       Z e	d       Zd Zd	 Zd
 Ze	d        Ze	d        Zy)r   a  
    Random Symbols represent ProbabilitySpaces in SymPy Expressions.
    In principle they can take on any value that their symbol can take on
    within the associated PSpace with probability determined by the PSpace
    Density.

    Explanation
    ===========

    Random Symbols contain pspace and symbol properties.
    The pspace property points to the represented Probability Space
    The symbol is a standard SymPy Symbol that is used in that probability space
    for example in defining a density.

    You can form normal SymPy expressions using RandomSymbols and operate on
    those expressions with the Functions

    E - Expectation of a random expression
    P - Probability of a condition
    density - Probability Density of an expression
    given - A new random expression (with new random symbols) given a condition

    An object of the RandomSymbol type should almost never be created by the
    user. They tend to be created instead by the PSpace class's value method.
    Traditionally a user does not even do this but instead calls one of the
    convenience functions Normal, Exponential, Coin, Die, FiniteRV, etc....
    Nc                    ddl m} |
t               }t        |      }t	        |t              st        d      | |k(  rt	        |t              rt        } t        j                  | ||      S )Nr   JointRandomSymbolz(pspace variable should be of type PSpace)
sympy.stats.joint_rvr   r   rn   
isinstance	TypeErrorr   r   r   r;   )r<   ra   pspacer   s       r+   r;   zRandomSymbol.__new__#  s[    :>XF"6*&&)FGG##
6<(HC}}S&&11r-   Tc                     | j                   d   S rF   rA   rB   s    r+   <lambda>zRandomSymbol.<lambda>5      499Q< r-   c                     | j                   d   S r@   rA   rB   s    r+   r   zRandomSymbol.<lambda>6  r   r-   c                .    | j                   j                  S r0   ra   namerB   s    r+   r   zRandomSymbol.<lambda>7  s    4;;#3#3 r-   c                .    | j                   j                  S r0   )ra   is_positiverB   s    r+   _eval_is_positivezRandomSymbol._eval_is_positive9  s    {{&&&r-   c                .    | j                   j                  S r0   )ra   
is_integerrB   s    r+   _eval_is_integerzRandomSymbol._eval_is_integer<  s    {{%%%r-   c                ^    | j                   j                  xs | j                  j                  S r0   )ra   r   r   rB   s    r+   _eval_is_realzRandomSymbol._eval_is_real?  s!    {{""9dkk&9&99r-   c                .    | j                   j                  S r0   )ra   is_commutativerB   s    r+   r   zRandomSymbol.is_commutativeB  s    {{)))r-   c                    | hS r0   r*   rB   s    r+   r4   zRandomSymbol.free_symbolsF  s	    vr-   r0   )rS   rT   rU   rV   r;   	is_finite	is_symbolis_Atom	_diff_wrtr[   r   ra   r   r   r   r   r   r4   r*   r-   r+   r   r     sz    8
2 IIGI/0F/0F34D'&: * *  r-   r   c                  h    e Zd ZddZ ed       Z ed       Zed        Zed        Zed        Z	y)	RandomIndexedSymbolNc                    |
t               }t        |t        t        f      st	        d|z        t        j                  | ||      S )Nz0An Function or Indexed object is expected not %s)r   r   r   r
   r   r   r;   )r<   idx_objr   s      r+   r;   zRandomIndexedSymbol.__new__L  sB    >XF'GX#67NPWXYY}}S'622r-   c                     | j                   d   S r@   rA   rB   s    r+   r   zRandomIndexedSymbol.<lambda>T  r   r-   c                2    t        | j                  d         S r@   )strr>   rB   s    r+   r   zRandomIndexedSymbol.<lambda>U  s    TYYq\!2 r-   c                    t        | j                  t              r| j                  j                  d   S t        | j                  t              r| j                  j                  d   S y )NrG   r   )r   ra   r   r>   r
   rB   s    r+   keyzRandomIndexedSymbol.keyW  sM    dkk7+;;##A&&X.;;##A&& /r-   c                    | j                   j                  r)| j                   j                  }|j                  |        |S | hS r0   )r   r4   add)rC   	free_symss     r+   r4   z RandomIndexedSymbol.free_symbols^  s7    88  --IMM$vr-   c                     | j                   d   S rF   rA   rB   s    r+   r   zRandomIndexedSymbol.pspacef  rD   r-   r0   )
rS   rT   rU   r;   r[   ra   r   r   r4   r   r*   r-   r+   r   r   J  sY    3 /0F23D' '    r-   r   c                  8    e Zd ZddZ ed       Z ed       Zy)RandomMatrixSymbolNc                    t        |      t        |      }}t        |      }|
t               }t        j                  | ||||      S r0   )r   rn   r   r   r;   )r<   ra   nmr   s        r+   r;   zRandomMatrixSymbol.__new__k  s@    {HQK1"6*>XF}}S&!Q77r-   c                     | j                   d   S r@   rA   rB   s    r+   r   zRandomMatrixSymbol.<lambda>s  r   r-   c                     | j                   d   S )N   rA   rB   s    r+   r   zRandomMatrixSymbol.<lambda>t  r   r-   r0   )rS   rT   rU   r;   r[   ra   r   r*   r-   r+   r   r   j  s    8 /0F/0Fr-   r   c                      e Zd ZdZy)ProductPSpacez
    Abstract class for representing probability spaces with multiple random
    variables.

    See Also
    ========

    sympy.stats.rv.IndependentProductPSpace
    sympy.stats.joint_rv.JointPSpace
    N)rS   rT   rU   rV   r*   r-   r+   r   r   w  s    	 	r-   r   c                      e Zd ZdZd Zed        Zed        Zed        Zed        Z	ed        Z
dd	Zed
        Zed        ZddZd Zd Zd ZddZy)IndependentProductPSpacez
    A probability space resulting from the merger of two independent probability
    spaces.

    Often created using the function, pspace.
    c                  	
 i }|D ]  }|j                   D ]  }|||<   	  t        |j                         D cg c]  }|j                   c} }ddlm
 ddlm	 t        |      t        	
fd|D              k  rt        d      t        d |D              rddlm} |} t        j                  | gt        |  }|S c c}w )Nr   )MarginalDistribution)CompoundDistributionc              3  x   K   | ]1  }t        |j                  f      st        |j                         3 y wr0   )r   r   rg   r=   )r1   spacer   r   s     r+   r3   z3IndependentProductPSpace.__new__.<locals>.<genexpr>  s<      :U	E&& "6)8 
9 "%--0 :s   7:zOverlapping Random Variablesc              3  4   K   | ]  }|j                     y wr0   rX   r1   r   s     r+   r3   z3IndependentProductPSpace.__new__.<locals>.<genexpr>  s     35u3   )ProductFinitePSpace)r   r   keysra   r   r   sympy.stats.compound_rvr   rg   sum
ValueErrorallsympy.stats.frvr   r   r;   )r<   spacesrs_space_dictr   r   rj   r=   r   objr   r   s            @@r+   r;   z IndependentProductPSpace.__new__  s     	-E -',e$-	- M4F4F4HIScjjIJ 	>@w<# :f : : : ;<<3F33;%CmmC5)V"45
! Js   C c                    t        | j                  D cg c]  }|j                   c} }|j                  | j                  D ci c]  }||j
                   c}      S c c}w c c}w r0   )r   r   r   subsr   ra   )rC   r   prvs       r+   r   zIndependentProductPSpace.pdf  sM    5%))56vvt{{;r299};<< 6;s   AA$c                X    i }| j                   D ]  }|j                  D ]  }|||<   	  |S r0   )r   r   )rC   dr   r   s       r+   r   z&IndependentProductPSpace.rs_space_dict  s=    [[ 	!E ! %!	! r-   c                |    t        | j                  j                         D cg c]  }|j                   c} S c c}w r0   )r   r   r   ra   )rC   rj   s     r+   r=   z IndependentProductPSpace.symbols  s.    1C1C1H1H1JK#3::KLLKs   9c                &    t        | j                   S r0   )r   r>   rB   s    r+   r   zIndependentProductPSpace.spaces  s    $))$$r-   c                :    t        d | j                  D              S )Nc              3  4   K   | ]  }|j                     y wr0   )r   r   s     r+   r3   z2IndependentProductPSpace.values.<locals>.<genexpr>  s     =u||=r   )sumsetsr   rB   s    r+   r   zIndependentProductPSpace.values  s    ====r-   Nc                    |xs | j                   }t        |      }| j                  D ]%  } |j                  |||j                   z  fddi|}' |rt	        |d      r |j
                  di |S |S )NevaluateFdoitr*   )r   r   r   rR   hasattrr   )rC   rQ   rvsr   kwargsr   s         r+   rR   z,IndependentProductPSpace.compute_expectation  s|     T[[n[[ 	aE,5,,T33E`PU`Y_`D	af-499&v&&r-   c                `    t        | j                  D cg c]  }|j                   c} S c c}w r0   )ProductDomainr   r   )rC   r   s     r+   r   zIndependentProductPSpace.domain  s#    Eu||EFFEs   +c                    t        d      )Nz'Density not available for ProductSpacesrJ   rB   s    r+   r   z IndependentProductPSpace.density  s    !"KLLr-   c           
         | j                   D ci c]/  }|j                  |||      j                         D ]  \  }}||
 1 c}}}S c c}}}w )Nr   r   r   )r   r%   items)rC   r   r   r   r   kvs          r+   r%   zIndependentProductPSpace.sample  sc    "&++ U U$dKQQSU1 1 U U 	U Us   4A
c                   d}t        |t              r)t        |j                  d   |j                  d         }d}n~t        |t              r/t        |j                  D cg c]  }| j                  |       c} S t        |t              r/t        |j                  D cg c]  }| j                  |       c} S |j                  |j                  z
  }t        |      }| j                  |      }t        d |D              rddlm} ddlm}	 || j$                  v r{t'        t)        | j$                        t+        |g      z
        }
t'        d |
D              } | j,                  j.                  | j0                  |fi |}t3        |j4                  |      S  |	|      }t7        d	d
      } |||      }|j                  |j9                  |j:                  d            }nUddlm} ddl m!}  ||      }t7        d	d      } |||      }|j                  |j9                  |j:                  d            }|s|S tD        jF                  |z
  S c c}w c c}w )NFr   rG   Tc              3  F   K   | ]  }t        |      j                    y wr0   r   rY   r1   r   s     r+   r3   z7IndependentProductPSpace.probability.<locals>.<genexpr>       6Bvbz''6   !)SingleContinuousPSpace)ContinuousDistributionHandmadec              3  4   K   | ]  }|j                     y wr0   ra   )r1   rx   s     r+   r3   z7IndependentProductPSpace.probability.<locals>.<genexpr>  s     Bb		Br   zreal)SingleDiscretePSpace)DiscreteDistributionHandmadeinteger)$r   r   r   r>   r   r   r   r   r   lhsrhsru   r   r5   sympy.stats.crvr  sympy.stats.crv_typesr  r   rh   rH   r   r   	integrater   r   ra   r   	__class__r   sympy.stats.drvr  sympy.stats.drv_typesr  r   One)rC   rw   r   cond_invargrQ   r   densr  r  randomsymbolsr=   r   r  r   resultr  r  s                     r+   r   z$IndependentProductPSpace.probability  s   i$9>>!,innQ.?@IH	3')..I3))#.IJJ	2&)..I3))#.IJJ}}y}},T"##D)6#66>Lt{{" %c$++&6D69J&J KBMBB+dkk++DHHgHHdkk3//1$7Dc%A*1d3E&&y':':5;;'JKF<J/5Dc4(A(D1E&&y':':5;;'JKF%v91556>95 JIs   IIc                   t        |      }t        d |D              r-t        dd      } | j                  t	        ||z
        fi |}n*t        dd      } | j                  t        ||      fi |}t        ||      S )Nc              3  F   K   | ]  }t        |      j                    y wr0   r	  r
  s     r+   r3   z;IndependentProductPSpace.compute_density.<locals>.<genexpr>  r  r  r  Tr  r  )ru   r5   r   rR   r   r   r   )rC   rQ   r   r   r  s        r+   r   z(IndependentProductPSpace.compute_density  s    T"6#66c%A+4++Jtax,@ D c4(A+4++N4,C Dar-   c                    t        d      )Nz0CDF not well defined on multivariate expressions)r   )rC   rQ   r   s      r+   compute_cdfz$IndependentProductPSpace.compute_cdf  s    KLLr-   c           	        t        |      }|j                  | j                  D ci c]  }||j                   c}      }|D cg c]  }t	        |       }}t        d |D              rddlm}m} |}	 || j                  |      }
nZt        d |D              rddl
m}m} |}	 || j                  |      }
n*t        d |D              rddlm} |j!                  | |      S |r| j"                  D ci c]  }|t%        t'        |             }} 
j(                  | j*                  fi |}| j*                  |j                  |      z  }t-        t/        |
j"                        |      } 	
      S c c}w c c}w c c}w )Nc              3  4   K   | ]  }|j                     y wr0   rY   r1   pss     r+   r3   z=IndependentProductPSpace.conditional_space.<locals>.<genexpr>  s     2Br2r   r   )ConditionalContinuousDomainContinuousPSpacec              3  4   K   | ]  }|j                     y wr0   rZ   r-  s     r+   r3   z=IndependentProductPSpace.conditional_space.<locals>.<genexpr>  s     2B2r   )ConditionalDiscreteDomainDiscretePSpacec              3  4   K   | ]  }|j                     y wr0   r   r-  s     r+   r3   z=IndependentProductPSpace.conditional_space.<locals>.<genexpr>  s     0"0r   )FinitePSpace)ru   rt   r   ra   r   r5   r  r/  r0  r   r  r3  r4  r   r   r6  conditional_spacer=   r   r   rR   r   r   rh   )rC   rw   	normalizer   r   r   pspacesr/  r0  r   r   r3  r4  r6  replacementnormr   r   s                     r+   r7  z*IndependentProductPSpace.conditional_space  sJ   Y'&&'L"BII'LM	(+,"6":,,2'22"$E0iHF2'22 "E.t{{IFF000411$	BB9=F2Bc"g.FKF-6--dhhA&AD((T]];77C U6>>2C8GVW%%/ (M, Gs   E3E82E=r)   r   T)rS   rT   rU   rV   r;   r[   r   r   r=   r   r   rR   r   r   r%   r   r   r)  r7  r*   r-   r+   r   r     s    0 = =   M M % % > > G G M MU
 :D
M&r-   r   c                  f    e Zd ZdZdZd Zed        Zed        Zed        Z	ed        Z
d Zd	 Zy
)r   z
    A domain resulting from the merger of two independent domains.

    See Also
    ========
    sympy.stats.crv.ProductContinuousDomain
    sympy.stats.frv.ProductFiniteDomain
    Tc                ^   g }|D ];  }|j                   s|j                  |       !|j                  |j                         = t	        | }t        d |D              rddlm} |} t        d |D              rddlm	} |} t        d |D              rddl
m} |} t        j                  | g| S )Nc              3  4   K   | ]  }|j                     y wr0   r   r1   r   s     r+   r3   z(ProductDomain.__new__.<locals>.<genexpr>4  s     7Fv7r   r   )ProductFiniteDomainc              3  4   K   | ]  }|j                     y wr0   r,  r@  s     r+   r3   z(ProductDomain.__new__.<locals>.<genexpr>7  s     ;v##;r   )ProductContinuousDomainc              3  4   K   | ]  }|j                     y wr0   r2  r@  s     r+   r3   z(ProductDomain.__new__.<locals>.<genexpr>:  s     9fv!!9r   )ProductDiscreteDomain)rW   appendextenddomainsr   r   r   rA  r  rC  r  rE  r   r;   )r<   rH  domains2r   rA  rC  rE  s          r+   r;   zProductDomain.__new__*  s     	0F**'/		0
 h'7h77;%C;(;;?)C999='C}}S,8,,r-   c                j    | j                   D ci c]  }|j                  D ]  }||  c}}S c c}}w r0   )rH  r=   )rC   r   ra   s      r+   sym_domain_dictzProductDomain.sym_domain_dict@  sE    -1\\ C639>>C)/  C C 	C Cs   /c                t    t        | j                  D cg c]  }|j                  D ]  }|  c}} S c c}}w r0   )r   rH  r=   )rC   r   ri   s      r+   r=   zProductDomain.symbolsE  sB    T\\ =6-3^^=#&  =3 = > 	> =s   4
c                    | j                   S r0   rA   rB   s    r+   rH  zProductDomain.domainsJ  s    yyr-   c                4    t        d | j                  D         S )Nc              3  4   K   | ]  }|j                     y wr0   )rH   r@  s     r+   r3   z$ProductDomain.set.<locals>.<genexpr>P  s     B6FJJBr   )r   rH  rB   s    r+   rH   zProductDomain.setN  s    BT\\BCCr-   c                    | j                   D ]X  }t        |D cg c];  }t        |j                  j	                  |d               t
        j                  u r|= c}      }||vsX y yc c}w )Nr   FT)rH  r   r   r=   containsr   true)rC   rL   r   itemelems        r+   rM   zProductDomain.__contains__R  sq    ll 	Fu )t!()@)@a)I!J!""( # ) *D 6!	 )s   A A)
c                h    t        | j                  D cg c]  }|j                          c} S c c}w r0   )r   rH  r~   )rC   r   s     r+   r~   zProductDomain.as_boolean_  s(    t||DVV&&(DEEDs   /N)rS   rT   rU   rV   rW   r;   r[   rK  r=   rH  rH   rM   r~   r*   r-   r+   r   r     ss     -, C C > >   D DFr-   r   c                n    t        | dd      }|%d }t         |t                    }t        ||      S g S )z>
    Returns all RandomSymbols within a SymPy Expression.
    r6   Nc                .    | j                   j                  S r0   r   )r   s    r+   r   z random_symbols.<locals>.<lambda>i  s    ")).. r-   )r   )getattrlistr   sorted)rQ   r6   compls       r+   ru   ru   c  s>     D'4(E(|$%aT""	r-   c                &   t        |       } t        | t              r| j                  | j                  S | j	                  t
              r-t        | j                  t
                    d   }|j                  S t        |       st        d| z        t        fdD              rd   j                  S ddlm} ddlm} D ](  }t        |j                  ||f      s|j                  c S  t        D cg c]  }|j                   c} S c c}w )z
    Returns the underlying Probability Space of a random expression.

    For internal use.

    Examples
    ========

    >>> from sympy.stats import pspace, Normal
    >>> X = Normal('X', 0, 1)
    >>> pspace(2*X + 1) == X.pspace
    True
    r   z6Expression containing Random Variable expected, not %sc              3  V   K   | ]   }|j                   d    j                   k(   " yw)r   N)r   )r1   r   r   s     r+   r3   zpspace.<locals>.<genexpr>  s"     
4"299A%
4s   &)CompoundPSpace)StochasticPSpace)r   r   r   r   hasr   rY  r6   ru   r   r   r   r`  sympy.stats.stochastic_processra  r   )rQ   rmr`  ra  r   r   s        @r+   r   r   p  s     4=D$%$++*A{{xx"#$**/01!4yy

CQUYZ[[

4
441v}}6? bii.2B!CD99 $#%>Bbii%>??%>s   7Dc                0     t               j                  |  S )z
    Union of sets
    )r   union)setss    r+   r   r     s     9;d##r-   c                    i }| D ]2  }|D cg c]  }|j                   |j                   k(  s|  c}d   ||<   4 |S c c}w )a}  
    Build a dictionary to swap RandomSymbols based on their underlying symbol.

    i.e.
    if    ``X = ('x', pspace1)``
    and   ``Y = ('x', pspace2)``
    then ``X`` and ``Y`` match and the key, value pair
    ``{X:Y}`` will appear in the result

    Inputs: collections a and b of random variables which share common symbols
    Output: dict mapping RVs in a to RVs in b
    r   r  )abr   rsarsbs        r+   rs_swaprm    sM     	A C!"?#cjjCJJ&>#?B#CH @s   <<Nc                d   t        |      rt        | |      r| S t        |t              rt	        ||j
                        }t        |      }t        |t              rt        |      dk(  rt        t        |       j                  t              st        |      d   }t        ||      }t        |t              r4t        j                  |j                   v rt#        |j                   d         }d}|D ]^  }| j%                  ||      }|dk(  r y|dk7  s"|dk(  r#t        | t&              r| j%                  ||      }J|| j%                  ||      z  }` |dk(  ry|S t        t)        | |            }	 |	j*                  |fi |}
t-        |	j.                  |
j.                        }| j1                  |      } | S )a   Conditional Random Expression.

    Explanation
    ===========

    From a random expression and a condition on that expression creates a new
    probability space from the condition and returns the same expression on that
    conditional probability space.

    Examples
    ========

    >>> from sympy.stats import given, density, Die
    >>> X = Die('X', 6)
    >>> Y = given(X, X > 3)
    >>> density(Y).dict
    {4: 1/3, 5: 1/3, 6: 1/3}

    Following convention, if the condition is a random symbol then that symbol
    is considered fixed.

    >>> from sympy.stats import Normal
    >>> from sympy import pprint
    >>> from sympy.abc import z

    >>> X = Normal('X', 0, 1)
    >>> Y = Normal('Y', 0, 1)
    >>> pprint(density(X + Y, Y)(z), use_unicode=False)
                    2
           -(-Y + z)
           -----------
      ___       2
    \/ 2 *e
    ------------------
             ____
         2*\/ pi
    rG   r   TF)r,   pspace_independentr   r   r   ra   ru   rg   r   r   rr   rh   r    r   r   Realsr>   rY  r   r   r   r7  rm  r   rt   )rQ   rw   r   condsymbolsr   resultssumsrestemp	fullspacer   swapdicts               r+   givenrx    s   N Y#5dI#F)\*y)"2"23	 +K9b!c+&6!&;vd|**,=>;"9b)g|,GLL1H7<<?+G 	/C99R%Dt|u} 19D*!=99R-DDIIb#..D	/ 19 uT9-.I'I''	<V<E y''6H=="DKr-   c                z    t        |       s| S ||d<   ddlm} |r  || |      j                  di |S  || |      S )aM  
    Returns the expected value of a random expression.

    Parameters
    ==========

    expr : Expr containing RandomSymbols
        The expression of which you want to compute the expectation value
    given : Expr containing RandomSymbols
        A conditional expression. E(X, X>0) is expectation of X given X > 0
    numsamples : int
        Enables sampling and approximates the expectation with this many samples
    evalf : Bool (defaults to True)
        If sampling return a number rather than a complex expression
    evaluate : Bool (defaults to True)
        In case of continuous systems return unevaluated integral

    Examples
    ========

    >>> from sympy.stats import E, Die
    >>> X = Die('X', 6)
    >>> E(X)
    7/2
    >>> E(2*X + 1)
    8

    >>> E(X, X > 3) # Expectation of X given that it is above 3
    5
    
numsamplesr   )Expectationr*   )r,    sympy.stats.symbolic_probabilityr{  r   )rQ   rw   rz  r   r   r{  s         r+   expectationr}    sK    @ T?%F<<0{4+00:6::tY''r-   c                `    ||d<   ddl m} |r  || |      j                  di |S  || |      S )a{  
    Probability that a condition is true, optionally given a second condition.

    Parameters
    ==========

    condition : Combination of Relationals containing RandomSymbols
        The condition of which you want to compute the probability
    given_condition : Combination of Relationals containing RandomSymbols
        A conditional expression. P(X > 1, X > 0) is expectation of X > 1
        given X > 0
    numsamples : int
        Enables sampling and approximates the probability with this many samples
    evaluate : Bool (defaults to True)
        In case of continuous systems return unevaluated integral

    Examples
    ========

    >>> from sympy.stats import P, Die
    >>> from sympy import Eq
    >>> X, Y = Die('X', 6), Die('Y', 6)
    >>> P(X > 3)
    1/2
    >>> P(Eq(X, 5), X > 2) # Probability that X == 5 given that X > 2
    1/4
    >>> P(X > Y)
    5/12
    rz  r   )Probabilityr*   )r|  r  r   )rw   given_conditionrz  r   r   r  s         r+   r   r   ,  s?    @ &F<<;{9o6;;EfEEy/22r-   c                  >    e Zd Z ed       ZddZed        ZddZy)Densityc                     | j                   d   S r@   rA   rB   s    r+   r   zDensity.<lambda>T  s    1 r-   Nc                    t        |      }|t        j                  | |      }|S t        |      }t        j                  | ||      }|S r0   )r   r   r;   )r<   rQ   rw   r   s       r+   r;   zDensity.__new__V  sK    ~--T*C 
 !+I--T95C
r-   c                R    t        | j                        dkD  r| j                  d   S y rF   )rg   r>   rB   s    r+   rw   zDensity.condition_  s#    tyy>A99Q<r-   c                   ddl m} ddlm} ddlm} ddlm} ddlm	} | j                  | j                  }	}t        ||      r|j                  S |	t        ||	fi |}t        |      s t!        t"        t%        t"        |z
              S t        |t&              rut        |j(                  t*        ||f      r,t-        |j(                  d      r|j(                  j.                  S t        |j(                  |      r|j(                  j0                  S t        t)        |      |      r||d<    t)        |      j2                  |fi |}
|rt-        |
d	      r|
j5                         S |
S )
Nr   )RandomMatrixPSpace)JointPSpace)MatrixPSpacer_  )SingleFiniteDistributionr   compound_evaluater   )sympy.stats.random_matrixr  r   r   sympy.stats.matrix_distributionsr  r   r`  r   r  rQ   rw   r   dictrx  ru   r   r'   r   r   r   r   r   r   modelr   r   )rC   r   r   r  r  r  r`  r  rQ   rw   r%  s              r+   r   zDensity.doitf  s   @4A:<))T^^id4599 y3F3Dd#!ZD122dL)$++k<'PQ^4{{///DKK);<{{(((fTlN3*2F&'---d=f=/;;= Mr-   r0   r<  )rS   rT   rU   r[   rQ   r;   rw   r   r*   r-   r+   r  r  S  s+    -.D  r-   r  c                `    |rt        | |fd|i|S  t        | |      j                  dd|i|S )aH  
    Probability density of a random expression, optionally given a second
    condition.

    Explanation
    ===========

    This density will take on different forms for different types of
    probability spaces. Discrete variables produce Dicts. Continuous
    variables produce Lambdas.

    Parameters
    ==========

    expr : Expr containing RandomSymbols
        The expression of which you want to compute the density value
    condition : Relational containing RandomSymbols
        A conditional expression. density(X > 1, X > 0) is density of X > 1
        given X > 0
    numsamples : int
        Enables sampling and approximates the density with this many samples

    Examples
    ========

    >>> from sympy.stats import density, Die, Normal
    >>> from sympy import Symbol

    >>> x = Symbol('x')
    >>> D = Die('D', 6)
    >>> X = Normal(x, 0, 1)

    >>> density(D).dict
    {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
    >>> density(2*D).dict
    {2: 1/6, 4: 1/6, 6: 1/6, 8: 1/6, 10: 1/6, 12: 1/6}
    >>> density(X)(x)
    sqrt(2)*exp(-x**2/2)/(2*sqrt(pi))
    rz  r   r*   )sampling_densityr  r   )rQ   rw   r   rz  r   s        r+   r   r     sL    R i J  	 )74#((E(EfEEr-   c                    |t        t        | |fi |fi |S  t        |       j                  | fi |}|rt	        |d      r|j                         S |S )a  
    Cumulative Distribution Function of a random expression.

    optionally given a second condition.

    Explanation
    ===========

    This density will take on different forms for different types of
    probability spaces.
    Discrete variables produce Dicts.
    Continuous variables produce Lambdas.

    Examples
    ========

    >>> from sympy.stats import density, Die, Normal, cdf

    >>> D = Die('D', 6)
    >>> X = Normal('X', 0, 1)

    >>> density(D).dict
    {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6}
    >>> cdf(D)
    {1: 1/6, 2: 1/3, 3: 1/2, 4: 2/3, 5: 5/6, 6: 1}
    >>> cdf(3*D, D > 2)
    {9: 1/4, 12: 1/2, 15: 3/4, 18: 1}

    >>> cdf(X)
    Lambda(_z, erf(sqrt(2)*_z/2)/2 + 1/2)
    r   )cdfrx  r   r)  r   r   rQ   rw   r   r   r%  s        r+   r  r    sa    @ 5y3F3>v>> &VD\%%d5f5FGFF+{{}r-   c                    |t        t        | |fi |fi |S  t        |       j                  | fi |}|rt	        |d      r|j                         S |S )a<  
    Characteristic function of a random expression, optionally given a second condition.

    Returns a Lambda.

    Examples
    ========

    >>> from sympy.stats import Normal, DiscreteUniform, Poisson, characteristic_function

    >>> X = Normal('X', 0, 1)
    >>> characteristic_function(X)
    Lambda(_t, exp(-_t**2/2))

    >>> Y = DiscreteUniform('Y', [1, 2, 7])
    >>> characteristic_function(Y)
    Lambda(_t, exp(7*_t*I)/3 + exp(2*_t*I)/3 + exp(_t*I)/3)

    >>> Z = Poisson('Z', 2)
    >>> characteristic_function(Z)
    Lambda(_t, exp(2*exp(_t*I) - 2))
    r   )characteristic_functionrx  r   compute_characteristic_functionr   r   r  s        r+   r  r    s^    . &uT9'G'GR6RR9VD\99$I&IFGFF+{{}r-   c                    |t        t        | |fi |fi |S  t        |       j                  | fi |}|rt	        |d      r|j                         S |S )Nr   )moment_generating_functionrx  r   "compute_moment_generating_functionr   r   r  s        r+   r  r    s\    )%i*J6*JUfUU<VD\<<TLVLFGFF+{{}r-   c                l    |t        t        | |fi |fi |S  t        |       j                   | fi |S )a  
    Returns the domain where a condition is True.

    Examples
    ========

    >>> from sympy.stats import where, Die, Normal
    >>> from sympy import And

    >>> D1, D2 = Die('a', 6), Die('b', 6)
    >>> a, b = D1.symbol, D2.symbol
    >>> X = Normal('x', 0, 1)

    >>> where(X**2<1)
    Domain: (-1 < x) & (x < 1)

    >>> where(X**2<1).set
    Interval.open(-1, 1)

    >>> where(And(D1<=D2, D2<3))
    Domain: (Eq(a, 1) & Eq(b, 1)) | (Eq(a, 1) & Eq(b, 2)) | (Eq(a, 2) & Eq(b, 2))
    )r   rx  r   )rw   r  r   s      r+   r   r     sE    . "U9o@@KFKK #6)""9777r-   )r&   )modulesr*   c                    t        | |||||      }|dk7  r;t        d| d|f|z    ddd       t        |      D cg c]  }t        |       c}S t        |      S c c}w )	a
  
    A realization of the random expression.

    Parameters
    ==========

    expr : Expression of random variables
        Expression from which sample is extracted
    condition : Expr containing RandomSymbols
        A conditional expression
    size : int, tuple
        Represents size of each sample in numsamples
    library : str
        - 'scipy' : Sample using scipy
        - 'numpy' : Sample using numpy
        - 'pymc'  : Sample using PyMC

        Choose any of the available options to sample from as string,
        by default is 'scipy'
    numsamples : int
        Number of samples, each with size as ``size``.

        .. deprecated:: 1.9

        The ``numsamples`` parameter is deprecated and is only provided for
        compatibility with v1.8. Use a list comprehension or an additional
        dimension in ``size`` instead. See
        :ref:`deprecated-sympy-stats-numsamples` for details.

    seed :
        An object to be used as seed by the given external library for sampling `expr`.
        Following is the list of possible types of object for the supported libraries,

        - 'scipy': int, numpy.random.RandomState, numpy.random.Generator
        - 'numpy': int, numpy.random.RandomState, numpy.random.Generator
        - 'pymc': int

        Optional, by default None, in which case seed settings
        related to the given library will be used.
        No modifications to environment's global seed settings
        are done by this argument.

    Returns
    =======

    sample: float/list/numpy.ndarray
        one sample or a collection of samples of the random expression.

        - sample(X) returns float/numpy.float64/numpy.int64 object.
        - sample(X, size=int/tuple) returns numpy.ndarray object.

    Examples
    ========

    >>> from sympy.stats import Die, sample, Normal, Geometric
    >>> X, Y, Z = Die('X', 6), Die('Y', 6), Die('Z', 6) # Finite Random Variable
    >>> die_roll = sample(X + Y + Z)
    >>> die_roll # doctest: +SKIP
    3
    >>> N = Normal('N', 3, 4) # Continuous Random Variable
    >>> samp = sample(N)
    >>> samp in N.pspace.domain.set
    True
    >>> samp = sample(N, N>0)
    >>> samp > 0
    True
    >>> samp_list = sample(N, size=4)
    >>> [sam in N.pspace.domain.set for sam in samp_list]
    [True, True, True, True]
    >>> sample(N, size = (2,3)) # doctest: +SKIP
    array([[5.42519758, 6.40207856, 4.94991743],
       [1.85819627, 6.83403519, 1.9412172 ]])
    >>> G = Geometric('G', 0.5) # Discrete Random Variable
    >>> samp_list = sample(G, size=3)
    >>> samp_list # doctest: +SKIP
    [1, 3, 2]
    >>> [sam in G.pspace.domain.set for sam in samp_list]
    [True, True, True]
    >>> MN = Normal("MN", [3, 4], [[2, 1], [1, 2]]) # Joint Random Variable
    >>> samp_list = sample(MN, size=4)
    >>> samp_list # doctest: +SKIP
    [array([2.85768055, 3.38954165]),
     array([4.11163337, 4.3176591 ]),
     array([0.79115232, 1.63232916]),
     array([4.01747268, 3.96716083])]
    >>> [tuple(sam) in MN.pspace.domain.set for sam in samp_list]
    [True, True, True, True]

    .. versionchanged:: 1.7.0
        sample used to return an iterator containing the samples instead of value.

    .. versionchanged:: 1.9.0
        sample returns values or array of values instead of an iterator and numsamples is deprecated.

    )r   r   rz  r   rG   z
            The numsamples parameter to sympy.stats.sample() is deprecated.
            Either use a list comprehension, like

            [sample(...) for i in range(zO)]

            or add a dimension to size, like

            sample(..., size=z)
            z1.9z!deprecated-sympy-stats-numsamples)deprecated_since_versionactive_deprecations_target)sample_iterr#   rangenext)	rQ   rw   r   r   rz  r   r   iteratorr2   s	            r+   r%   r%   -  s    F 4wCMTXZH Q!) *4 5  *md23 4	 &+'J	
 ).j(9:1X::> ;s   Ac                z     t        |       j                  | fi |}|rt        |d      r|j                         S |S )a  
    Return the :math:`p^{th}` order quantile of a probability distribution.

    Explanation
    ===========

    Quantile is defined as the value at which the probability of the random
    variable is less than or equal to the given probability.

    .. math::
        Q(p) = \inf\{x \in (-\infty, \infty) : p \le F(x)\}

    Examples
    ========

    >>> from sympy.stats import quantile, Die, Exponential
    >>> from sympy import Symbol, pprint
    >>> p = Symbol("p")

    >>> l = Symbol("lambda", positive=True)
    >>> X = Exponential("x", l)
    >>> quantile(X)(p)
    -log(1 - p)/lambda

    >>> D = Die("d", 6)
    >>> pprint(quantile(D)(p), use_unicode=False)
    /nan  for Or(p > 1, p < 0)
    |
    | 1       for p <= 1/6
    |
    | 2       for p <= 1/3
    |
    < 3       for p <= 1/2
    |
    | 4       for p <= 2/3
    |
    | 5       for p <= 5/6
    |
    \ 6        for p <= 1

    r   )r   compute_quantiler   r   )rQ   r   r   r%  s       r+   quantiler    s=    T +VD\**4:6:FGFF+{{}r-   c                    ddl m} t              st        dz        t	        t                     nt	               t        j                        t         |      r2 j                   t         j                   j                        i       nTi } j                  D ]2  }	t        |	|      st        |	j                  |	j                        ||	<   4  j                  |        fdfddv rt         fi |nt         fdi|t        fi |f
d}
fd	}t        j                  u r |
       S  |       S )
a  
    Returns an iterator of realizations from the expression given a condition.

    Parameters
    ==========

    expr: Expr
        Random expression to be realized
    condition: Expr, optional
        A conditional expression
    size : int, tuple
        Represents size of each sample in numsamples
    numsamples: integer, optional
        Length of the iterator (defaults to infinity)
    seed :
        An object to be used as seed by the given external library for sampling `expr`.
        Following is the list of possible types of object for the supported libraries,

        - 'scipy': int, numpy.random.RandomState, numpy.random.Generator
        - 'numpy': int, numpy.random.RandomState, numpy.random.Generator
        - 'pymc': int

        Optional, by default None, in which case seed settings
        related to the given library will be used.
        No modifications to environment's global seed settings
        are done by this argument.

    Examples
    ========

    >>> from sympy.stats import Normal, sample_iter
    >>> X = Normal('X', 0, 1)
    >>> expr = X*X + 3
    >>> iterator = sample_iter(expr, numsamples=3) # doctest: +SKIP
    >>> list(iterator) # doctest: +SKIP
    [12, 4, 7]

    Returns
    =======

    sample_iter: iterator object
        iterator object containing the sample/samples of given expr

    See Also
    ========

    sample
    sampling_P
    sampling_E

    r   r   Failed to import %sc                 L    j                  t        t        |                   S r0   r   r  zip)r>   rQ   r   s    r+   fn_subszsample_iter.<locals>.fn_subs!  s    yyc#tn-..r-   c                 R    $j                  t        t        |                   S yr)   r  )r>   rw   r   s    r+   given_fn_subsz"sample_iter.<locals>.given_fn_subs$  s&     >>$s3~"677r-   pymcpymc3r  c               3  B  
K   d} dt        t              rfnz   }| k  r\j                  |
      }D cg c]
  }||   d    }}	  | }|dk7  r|dk7  rt        d      |sN |  | dz  } | k  r[y y c c}w # t        t        f$ r  	| }Y Gw xY ww)Nr   )rG   r  TF(Conditions must not contain free symbolsrG   )r   intr%   	NameErrorr   r   )count_sizer   r   r>   gdrw   fngiven_fnr  r   rz  r.  r   r   r   s         r+   return_generator_infinitez.sample_iter.<locals>.return_generator_infinite4  s     D#!6tgDAj 		ugD	AA'*+AbE!H+D+$.!4B :"+$BD Dd)OQJE% j + "9- .&-B.s:   8BB 
BB )B>BBBBBc               3    K   d} | r|j                  ft        t              rfnz         }d} d}|k  rE| sCD cg c]
  }||   |    }}	  	| }|dk7  r|dk7  rt        d      |sd} |dz  }|k  r| sC| r|d}|k  r)D cg c]
  }|   |    }}	  |  |dz  }|k  r(y y c c}w # t        t        f$ r  
| }Y uw xY wc c}w # t        t        f$ r
  |  Y Iw xY ww)NTr  Fr   r  rG   )r%   r   r  r  r   r   )faultyr   r  r   r>   r  rw   r  r  r  r  r   rz  r.  r   r   r   s         r+   return_generator_finitez,sample_iter.<locals>.return_generator_finiteK  s[    		
}:dC;PVZ[")  6A FE*$V/23"e33(2%t_ TzbEk(FH H!%
 *$V . j +./RAbE%L/D/%$i QJE j # 4 &y1 2*D12 0
 y) %tn$%sw   ?C5B5C5B: %C5C5C5CC5!C (
C53C5:CC5CC5C2/C51C22C5)r   r   r!   r   r   r   rY  r   r   r   r   ra   r>   r   r   Infinity)rQ   rw   r   r   rz  r   r   r   subr"  r  r  r  r  r  r  r.  r   s   ``````      @@@@@@r+   r  r    sU   l 7!.899E$	*+D\
ryy/C$)*yy$T[[$++ FGH99 	@C#01'

CJJ?C	@ yy~/
 ## c4*6*c4;;F; C5f5 ." "H QZZ(**"$$r-   c                $    t        | f||||d|S N)rw   r   rz  r   r  rQ   rw   r   rz  r   r   s         r+   sample_iter_lambdifyr  t  -     t Cyt",4C;AC Cr-   c                $    t        | f||||d|S r  r  r  s         r+   sample_iter_subsr  z  r  r-   c                    d}d}t        | |f|||d|}	|	D ]  }
|
r|dz  }|dz  } t        |      |z  }|r|j                         S |S )zg
    Sampling version of P.

    See Also
    ========

    P
    sampling_E
    sampling_density

    r   r   rz  r   rG   )r  r   evalf)rw   r  r   rz  r  r   r   
count_truecount_falsesamplesr%   r%  s               r+   
sampling_Pr    s~     JK)_ Fg%/dF>DFG  !OJ1K	 z]Z'F||~r-   c           	     t    t        t        | |f|||d|      }t        | |z  }|r|j                         S |S )zf
    Sampling version of E.

    See Also
    ========

    P
    sampling_P
    sampling_density
    r  )rY  r  r   r  )	rQ   r  r   rz  r  r   r   r  r%  s	            r+   
sampling_Er    sS     ;t_ Fg%/dF>DF GG']Z'F||~r-   c                f    i }t        | |f|||d|D ]  }|j                  |d      dz   ||<    |S )zk
    Sampling version of density.

    See Also
    ========
    density
    sampling_P
    sampling_E
    r  r   rG   )r  get)rQ   r  r   rz  r   r   rr  r%  s           r+   r  r    sX     GdO JW)3$JBHJ 5!++fa0145 Nr-   c                    t        | |      ryt        dd      }t        | t        ||            t        |       k7  xs" t        |t        | |            t        |      k7  S )a  
    Dependence of two random expressions.

    Two expressions are independent if knowledge of one does not change
    computations on the other.

    Examples
    ========

    >>> from sympy.stats import Normal, dependent, given
    >>> from sympy import Tuple, Eq

    >>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
    >>> dependent(X, Y)
    False
    >>> dependent(2*X + Y, -Y)
    True
    >>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
    >>> dependent(X, Y)
    True

    See Also
    ========

    independent
    Fr  Tr  )ro  r   r   r   )ri  rj  r  s      r+   	dependentr    s[    6 !QsA Ar!Qx GAJ. /Ar!Qx GAJ.0r-   c                    t        | |       S )a  
    Independence of two random expressions.

    Two expressions are independent if knowledge of one does not change
    computations on the other.

    Examples
    ========

    >>> from sympy.stats import Normal, independent, given
    >>> from sympy import Tuple, Eq

    >>> X, Y = Normal('X', 0, 1), Normal('Y', 0, 1)
    >>> independent(X, Y)
    True
    >>> independent(2*X + Y, -Y)
    False
    >>> X, Y = given(Tuple(X, Y), Eq(X + Y, 3))
    >>> independent(X, Y)
    False

    See Also
    ========

    dependent
    )r  )ri  rj  s     r+   independentr    s    6 Ar-   c                *   t        t        |      j                        }t        t        |       j                        }t        t        t	        |             j                  t	        |                  dk7  ryt        |j                  |            dk(  ryy)ac  
    Tests for independence between a and b by checking if their PSpaces have
    overlapping symbols. This is a sufficient but not necessary condition for
    independence and is intended to be used internally.

    Notes
    =====

    pspace_independent(a, b) implies independent(a, b)
    independent(a, b) does not imply pspace_independent(a, b)
    r   FTN)rH   r   r=   rg   ru   intersection)ri  rj  	a_symbols	b_symbolss       r+   ro  ro    st     F1I%%&IF1I%%&I
3~a !..~a/@ABaG
9!!),-2r-   c                    |t        |       }|s| S |D ci c]  }||j                   }}| j                  |      S c c}w )z
    Given a random expression replace all random variables with their symbols.

    If symbols keyword is given restrict the swap to only the symbols listed.
    )ru   ra   r   )rQ   r=   r   rw  s       r+   rv_subsr  $  sJ      &(/0"BII0H099X 1s   =c                  "    e Zd ZU dZded<   d Zy)NamedArgsMixinr*   ztuple[str, ...]	_argnamesc                    	 | j                   | j                  j                  |         S # t        $ r& t	        dt        |       j                  d|d      w xY w)N'z' object has no attribute ')r>   r  indexr   AttributeErrortyperS   )rC   attrs     r+   __getattr__zNamedArgsMixin.__getattr__5  sU    	,99T^^11$788 	, T
##T"+ , ,	,s	   '* /AN)rS   rT   rU   r  __annotations__r  r*   r-   r+   r  r  2  s    !#I#,r-   r  c                      e Zd ZddZy)DistributionNc           	     H   t        |      }|dv r|t        d|z        |dk(  rGddlm} ddl}|t        |t              r|j                  j                  |      }n|} || ||      }n|dk(  rOdd	l	m
}	 ddl}|t        |t              r|j                  j                  |      }n|}|d
k(  rdn|}
 |	| |
|      }n|dv rddlm} ddl}|j                  d      j                  |j                          	 ddl}|j)                         5   ||       r8|j+                  t-        |      ddd|d      dd d   }|j/                  |      }nd}ddd       nt1        dt3        |      z        |S t1        d| d|      # t$        $ r ddl}Y w xY w# 1 sw Y   1xY w)z, A random realization from the distribution >   r  numpyr  r&   Nr  r&   r   )do_sample_scipy)r   r  )do_sample_numpyr*   r  )do_sample_pymcr  rG   F)drawschainscompute_convergence_checksprogressbarrandom_seedreturn_inferencedataXz&Sampling from %s is not supported yet.zSampling for z# is not currently implemented from )r!   r   !sympy.stats.sampling.sample_scipyr  r  r   r  randomdefault_rng!sympy.stats.sampling.sample_numpyr   sympy.stats.sampling.sample_pymcr  logging	getLoggersetLevelERRORr  ImportErrorr  Modelr%   r   reshaperK   r   )rC   r   r   r   moduler  r  
rand_statesampsr  r  r  r  r  s                 r+   r%   zDistribution.sample?  s    w'99fn2W<==g J|z$4"\\5545@
!
#D$
;EI|z$4"\\5545@
!
 BJDDE#D%<E))Gf%..w}}=%  !!$' KKd4j_d(-4V[ ( ]]^``ceE!MM$/E E! ! &&N(+G'5 6 6 L!W 	#  %$%! !s   9F AFFFF!r   )rS   rT   rU   r%   r*   r-   r+   r  r  =  s    :r-   r  c                ^    t        |       s| g} t        |       }|dk(  rt        |      |dk(  S )a  
    Raise a ValueError with message if condition is False, else
    return True if all conditions were True, else False.

    Examples
    ========

    >>> from sympy.stats.rv import _value_check
    >>> from sympy.abc import a, b, c
    >>> from sympy import And, Dummy

    >>> _value_check(2 < 3, '')
    True

    Here, the condition is not False, but it does not evaluate to True
    so False is returned (but no error is raised). So checking if the
    return value is True or False will tell you if all conditions were
    evaluated.

    >>> _value_check(a < b, '')
    False

    In this case the condition is False so an error is raised:

    >>> r = Dummy(real=True)
    >>> _value_check(r < r - 1, 'condition is not true')
    Traceback (most recent call last):
    ...
    ValueError: condition is not true

    If no condition of many conditions must be False, they can be
    checked by passing them as an iterable:

    >>> _value_check((a < 0, b < 0, c < 0), '')
    False

    The iterable can be a generator, too:

    >>> _value_check((i < 0 for i in (a, b, c)), '')
    False

    The following are equivalent to the above but do not pass
    an iterable:

    >>> all(_value_check(i < 0, '') for i in (a, b, c))
    False
    >>> _value_check(And(a < 0, b < 0, c < 0), '')
    False
    FT)r$   r   r   )rw   messagetruths      r+   _value_checkr	  |  s:    d IK	i E~!!D=r-   c                x    t        | t              rt        |       } t        | t              st        d| z        | S )a  
    Casts the parameter to Symbol if it is 'str'
    otherwise no operation is performed on it.

    Parameters
    ==========

    sym
        The parameter to be converted.

    Returns
    =======

    Symbol
        the parameter converted to Symbol.

    Raises
    ======

    TypeError
        If the parameter is not an instance of both str and
        Symbol.

    Examples
    ========

    >>> from sympy import Symbol
    >>> from sympy.stats.rv import _symbol_converter
    >>> s = _symbol_converter('s')
    >>> isinstance(s, Symbol)
    True
    >>> _symbol_converter(1)
    Traceback (most recent call last):
    ...
    TypeError: 1 is neither a Symbol nor a string
    >>> r = Symbol('r')
    >>> isinstance(r, Symbol)
    True
    z#%s is neither a Symbol nor a string)r   r   r   r   )ri   s    r+   rn   rn     s8    P #sSkc6"=sCDDJr-   c                \    ddl m} t        | |      st        d      | j	                         S )a'  
    This function is used to sample from stochastic process.

    Parameters
    ==========

    process: StochasticProcess
        Process used to extract the samples. It must be an instance of
        StochasticProcess

    Examples
    ========

    >>> from sympy.stats import sample_stochastic_process, DiscreteMarkovChain
    >>> from sympy import Matrix
    >>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
    >>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
    >>> next(sample_stochastic_process(Y)) in Y.state_space
    True
    >>> next(sample_stochastic_process(Y))  # doctest: +SKIP
    0
    >>> next(sample_stochastic_process(Y)) # doctest: +SKIP
    2

    Returns
    =======

    sample: iterator object
        iterator object containing the sample of given process

    r   )StochasticProcessz1Process must be an instance of Stochastic Process)$sympy.stats.stochastic_process_typesr  r   r   r%   )processr  s     r+   sample_stochastic_processr    s-    @ Gg01LMM>>r-   r0   )NNT)NTN)NT)Nr*   r&   rG   Nr<  )Nr&   rG   TN)Nr&   rG   N)mrV   
__future__r   	functoolsr   mathr   sympy.core.addr   sympy.core.basicr   sympy.core.containersr   sympy.core.exprr	   sympy.core.functionr
   r   sympy.core.logicr   sympy.core.mulr   sympy.core.relationalr   r   sympy.core.singletonr   sympy.core.symbolr   r   sympy.core.sympifyr   'sympy.functions.special.delta_functionsr   (sympy.functions.special.tensor_functionsr   sympy.logic.boolalgr   r   "sympy.matrices.expressions.matexprr   sympy.tensor.indexedr   sympy.utilities.lambdifyr   r   r   sympy.sets.setsr   r   r   sympy.solvers.solvesetr    sympy.externalr!   sympy.utilities.decoratorr"   sympy.utilities.exceptionsr#   sympy.utilities.iterablesr$   __doctest_requires__r'   r,   registerr7   r9   r]   rl   rr   r   r   r   r   r   r   r   r   ru   r   r   rm  rx  r}  r   r  r   r  r  r  r   r%   r  r  r  r  r  r  r  r  r  r  ro  r  r  r  r	  rn   r  r*   r-   r+   <module>r,     s   # $   " '   2 &  * " - & > C ) ; ( - , ' ? ? + ( 8 @ . $gY/  3K   E, ,
 $5  $F6< 6:&< &$ A  AF4$U 4$n26 24B4 BH, @
1| 
1	F 	Y&} Y&vAFL AFH
!@H$&Rj&(R =A$3N/e /d-F`*ZB	8> J'29"v (vr/b !%2w zzZ%x *.B$%JJTC &* !

C MN $@ HI $* :A'+("0J<., ,<5 <~7r,\#r-   