K i3XdZddlmZddlmZddlmZddlmZddl m Z ddl m Z ddl mZdd lmZmZdd lmZdd lmZdd lmZmZdd lmZddlmZmZddlmZddl m!Z!ddl"m#Z#ddl$m%Z%m&Z&ddl'm(Z(ddl)m*Z*ddl+m,Z,ddlm-Z-ddlm.Z.ddl/m0Z0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:ddl;med!Z?e?je d"ZAGd#d$e ZBGd%d&eBZCGd'd(eBZDGd)d*eBZEGd+d,e ZFGd-d.eFZGGd/d0eZHGd1d2eHZIGd3d4eHe(ZJGd5d6eFZKGd7d8eKZLGd9d:eBZMd;ZNd<ZOd=ZPd>ZQd`d@ZRdadAZS dadBZTGdCdDe ZUdbdEZVdcdFZWdcdGZXdcdHZYd`dIZZe8dJK dddMZ[dedNZ\d?dLdejd?fdOZ^d?dLejd?fdPZ_d?dLejd?fdQZ` dfdRZa dfdSZb dgdTZcdUZddVZedWZfd`dXZgGdYdZZhGd[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)FunctionLambda) fuzzy_and)Mul)EqNe)S)DummySymbol)sympify) DiracDelta)KroneckerDelta)AndOr) MatrixSymbol)Indexed)lambdify) Relational)_sympify) FiniteSet ProductSet Intersection)solveset) import_module)doctest_depends_on)sympy_deprecation_warning)iterable)samplescipyxcyNF)r's T/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/stats/rv.py is_randomr,5s c>|j}td|DS)Nc32K|]}t|ywN)r,).0is r+ z_..=s+y|+s) free_symbolsany)r'atomss r+_r7:s NNE +U+ ++r-cReZdZdZdZdZdZdZdZe dZ e dZ dZ dZ 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|}tj||g|Sr0)rr__new__)clssymbolsargss r+r;zRandomDomain.__new__Ps"W%}}S'1D11r-c |jdSNrr>selfs r+r=zRandomDomain.symbolsTyy|r-c |jdSNrArBs r+setzRandomDomain.setXrDr-ctr0NotImplementedError)rCothers r+ __contains__zRandomDomain.__contains__\ !##r-ctr0rJrCexprs r+compute_expectationz RandomDomain.compute_expectation_rNr-N)__name__ __module__ __qualname____doc__is_ProductDomain is_Finite is_Continuous is_Discreter;propertyr=rHrMrRr*r-r+r9r9@sUIMK2$$r-r9c<eZdZdZdZedZedZdZy) SingleDomainz A single variable and its domain. See Also ======== sympy.stats.crv.SingleContinuousDomain sympy.stats.frv.SingleFiniteDomain cL|jsJtj|||Sr0) is_Symbolrr;r<symbolrHs r+r;zSingleDomain.__new__ms$}}S&#..r-c |jdSr@rArBs r+razSingleDomain.symbolqrDr-c,t|jSr0rrarBs r+r=zSingleDomain.symbolsu%%r-ct|dk7ryt|d\}}|j|k(xr||jvS)NrGFr)lentuplerarH)rCrLsymvals r+rMzSingleDomain.__contains__ys= u:?<?S{{c!5cTXXo5r-N) rSrTrUrVr;r[rar=rMr*r-r+r]r]cs9/&&6r-r]c6eZdZdZdZedZedZy) MatrixDomainz3 A Random Matrix variable and its domain. c\t|t|}}tj|||Sr0)_symbol_converterrrr;r`s r+r;zMatrixDomain.__new__s''/#}}S&#..r-c |jdSr@rArBs r+razMatrixDomain.symbolrDr-c,t|jSr0rdrBs r+r=zMatrixDomain.symbolsrer-N)rSrTrUrVr;r[rar=r*r-r+rlrls4/&&r-rlc\eZdZdZdZedZedZedZedZ dZ y) ConditionalDomainz A RandomDomain with an attached condition. See Also ======== sympy.stats.crv.ConditionalContinuousDomain sympy.stats.frv.ConditionalFiniteDomain c|jt|Dcic]}||jc}}tj|||Scc}wr0)xreplacerandom_symbolsrarr;)r< fulldomain conditionrss r+r;zConditionalDomain.__new__sM&&$Y/(1)+BII (12 }}S*i88(1sA c.|jjSr0)rvr=rBs r+r=zConditionalDomain.symbolss&&&r-c |jdSr@rArBs r+rvzConditionalDomain.fulldomainrDr-c |jdSrFrArBs r+rwzConditionalDomain.conditionrDr-ctd)Nz)Set of Conditional Domain not ImplementedrJrBs r+rHzConditionalDomain.sets!"MNNr-c^t|jj|jSr0)rrv as_booleanrwrBs r+r~zConditionalDomain.as_booleans 4??--/@@r-N) rSrTrUrVr;r[r=rvrwrHr~r*r-r+rrrrsd9 ''OOAr-rrceZdZUdZdZded<dZded<dZded<ded<edZ ed Z ed Z ed Z d Z d ZddZdZdZy)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 Nz bool | NonerXrYrZis_realc |jdSr@rArBs r+domainz PSpace.domainrDr-c |jdSrFrArBs r+densityzPSpace.densityrDr-c@tfdjDS)Nc36K|]}t|ywr0) RandomSymbol)r1rirCs r+r3z PSpace.values..sISc40Is) frozensetr=rBs`r+valuesz PSpace.valuessIDLLIIIr-c.|jjSr0)rr=rBs r+r=zPSpace.symbolss{{"""r-ctr0rJrCrws r+wherez PSpace.whererNr-ctr0rJrPs r+compute_densityzPSpace.compute_densityrNr-ctr0rJ)rCsizelibraryseeds r+r%z PSpace.samplerNr-ctr0rJrs r+ probabilityzPSpace.probabilityrNr-ctr0rJrPs r+rRzPSpace.compute_expectationrNr-r*r&N)rSrTrUrVrX__annotations__rYrZr[rrrr=rrr%rrRr*r-r+rrs""I{!!%M;%#K#  JJ##$$$$$r-rcVeZdZdZdZedZedZedZedZ y) SinglePSpacezx Represents the probabilities of a set of random events that can be attributed to a single variable/symbol. cFt|}tj|||Sr0)rnrr;)r<s distributions r+r;zSinglePSpace.__new__s a }}S!\22r-c.t|j|Sr0)rrarBs r+valuezSinglePSpace.valuesDKK..r-c |jdSr@rArBs r+razSinglePSpace.symbolrDr-c |jdSrFrArBs r+rzSinglePSpace.distributionrDr-cL|jj|jSr0)rpdfrarBs r+rzSinglePSpace.pdfs  $$T[[11r-N) rSrTrUrVr;r[rrarrr*r-r+rrs\3//22r-rceZdZdZd dZdZdZdZdZe dZ e dZ e dZ dZ d Zd Ze d Ze d Zy)ra 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.... Ncddlm}| t}t|}t |ts t d||k(rt |t rt}tj|||S)NrJointRandomSymbolz(pspace variable should be of type PSpace) sympy.stats.joint_rvrrrn isinstance TypeErrorrrrr;)r<rapspacers r+r;zRandomSymbol.__new__#s[: >XF"6*&&)FG G # # 6<(HC}}S&&11r-Tc |jdSrFrArBs r+zRandomSymbol.5499Q<r-c |jdSr@rArBs r+rzRandomSymbol.6rr-c.|jjSr0ranamerBs r+rzRandomSymbol.7s4;;#3#3r-c.|jjSr0)ra is_positiverBs r+_eval_is_positivezRandomSymbol._eval_is_positive9s{{&&&r-c.|jjSr0)ra is_integerrBs r+_eval_is_integerzRandomSymbol._eval_is_integer<s{{%%%r-c^|jjxs|jjSr0)rarrrBs r+ _eval_is_realzRandomSymbol._eval_is_real?s!{{""9dkk&9&99r-c.|jjSr0)rais_commutativerBs r+rzRandomSymbol.is_commutativeBs{{)))r-c|hSr0r*rBs r+r4zRandomSymbol.free_symbolsFs v r-r0)rSrTrUrVr; is_finite is_symbolis_Atom _diff_wrtr[rrarrrrrr4r*r-r+rrsz8 2IIGI / 0F / 0F 3 4D'&:**r-rcheZdZddZedZedZedZedZedZ y) RandomIndexedSymbolNc| t}t|ttfst d|zt j |||S)Nz0An Function or Indexed object is expected not %s)rrrr rrr;)r<idx_objrs r+r;zRandomIndexedSymbol.__new__LsB >XF'GX#67NPWXY Y}}S'622r-c |jdSr@rArBs r+rzRandomIndexedSymbol.Trr-c2t|jdSr@)strr>rBs r+rzRandomIndexedSymbol.UsTYYq\!2r-ct|jtr|jjdSt|jtr|jjdSy)NrGr)rrarr>r rBs r+keyzRandomIndexedSymbol.keyWsM dkk7 +;;##A& &  X .;;##A& &/r-c|jjr)|jj}|j||S|hSr0)rr4add)rC free_symss r+r4z RandomIndexedSymbol.free_symbols^s7 88 --I MM$  v r-c |jdSrFrArBs r+rzRandomIndexedSymbol.pspacefrDr-r0) rSrTrUr;r[rarrr4rr*r-r+rrJsY3/ 0F 2 3D '' r-rc8eZdZddZedZedZy)RandomMatrixSymbolNct|t|}}t|}| t}tj|||||Sr0)rrnrrr;)r<ranmrs r+r;zRandomMatrixSymbol.__new__ks@{HQK1"6* >XF}}S&!Q77r-c |jdSr@rArBs r+rzRandomMatrixSymbol.srr-c |jdS)NrArBs r+rzRandomMatrixSymbol.trr-r0)rSrTrUr;r[rarr*r-r+rrjs8/ 0F / 0Fr-rceZdZdZy) ProductPSpacez Abstract class for representing probability spaces with multiple random variables. See Also ======== sympy.stats.rv.IndependentProductPSpace sympy.stats.joint_rv.JointPSpace N)rSrTrUrVr*r-r+rrws   r-rceZdZdZdZedZedZedZedZ edZ dd Z ed Z ed Z dd Zd ZdZdZddZy)IndependentProductPSpacez A probability space resulting from the merger of two independent probability spaces. Often created using the function, pspace. c i}|D]}|jD]}|||< t|jDcgc]}|jc}}ddlm ddlm t|t fd|Dkr tdtd|Drddl m }|}tj|gt|}|Scc}w)Nr)MarginalDistribution)CompoundDistributionc3xK|]1}t|jfst|j3ywr0)rrrgr=)r1spacerrs r+r3z3IndependentProductPSpace.__new__..s<:U E&& "6)8 9"%--0:s7:zOverlapping Random Variablesc34K|]}|jywr0rXr1rs r+r3z3IndependentProductPSpace.__new__..s35u3)ProductFinitePSpace)rrkeysrarrsympy.stats.compound_rvrrgsum ValueErrorallsympy.stats.frvrrr;) r<spaces rs_space_dictrrrjr=robjrrs @@r+r;z IndependentProductPSpace.__new__s  -E -', e$ - -M4F4F4HIScjjIJ >@ w<#:f:: :;< < 3F3 3 ;%CmmC5)V"45 !JsCct|jDcgc]}|jc}}|j|jDcic]}||j c}Scc}wcc}wr0)r rrsubsrra)rCrprvs r+rzIndependentProductPSpace.pdfsM 5%))5 6vvt{{;r299};<<6;s AA$cXi}|jD]}|jD]}|||< |Sr0)rr)rCdrrs r+rz&IndependentProductPSpace.rs_space_dicts= [[ !E ! % ! !r-c|t|jjDcgc]}|jc}Scc}wr0)rrrra)rCrjs r+r=z IndependentProductPSpace.symbolss.1C1C1H1H1JK#3::KLLKs9c&t|jSr0)rr>rBs r+rzIndependentProductPSpace.spacess$))$$r-c:td|jDS)Nc34K|]}|jywr0)rrs r+r3z2IndependentProductPSpace.values..s=u||=r)sumsetsrrBs r+rzIndependentProductPSpace.valuess====r-Nc |xs |j}t|}|jD]%}|j|||jzfddi|}'|rt |dr|j di|S|S)NevaluateFdoitr*)rrrrRhasattrr)rCrQrvsrkwargsrs r+rRz,IndependentProductPSpace.compute_expectations| T[[n[[ aE,5,,T33E`PU`Y_`D a f-499&v& & r-c`t|jDcgc]}|jc}Scc}wr0) ProductDomainrr)rCrs r+rzIndependentProductPSpace.domains#Eu||EFFEs+ctd)Nz'Density not available for ProductSpacesrJrBs r+rz IndependentProductPSpace.densitys!"KLLr-c |jDcic]/}|j|||jD]\}}|| 1c}}}Scc}}}w)Nrrr)rr%items)rCrrrrkvs r+r%zIndependentProductPSpace.samplesc"&++UU $d KQQSU11UU UUs4A c d}t|tr)t|jd|jd}d}n~t|tr/t |jDcgc]}|j |c}St|tr/t|jDcgc]}|j |c}S|j|jz }t|}|j|}td|Drddlm}ddlm} ||j$vr{t't)|j$t+|gz } t'd| D} |j,j.|j0| fi|} t3|j4| S| |}t7d d } || |}|j |j9|j:d}nUdd lm}dd l m!}||}t7d d } || |}|j |j9|j:d}|s|StDjF|z Scc}wcc}w)NFrrGTc3FK|]}t|jywr0rrYr1rs r+r3z7IndependentProductPSpace.probability..6Bvbz''6!)SingleContinuousPSpace)ContinuousDistributionHandmadec34K|]}|jywr0ra)r1rxs r+r3z7IndependentProductPSpace.probability..sBb Brzreal)SingleDiscretePSpace)DiscreteDistributionHandmadeinteger)$rrrr>rr rrrlhsrhsrurr5sympy.stats.crvrsympy.stats.crv_typesrrrhrHrr integraterr rar __class__rsympy.stats.drvrsympy.stats.drv_typesrrOne)rCrwrcond_invargrQrdensrr randomsymbolsr=rrrresultrrs r+rz$IndependentProductPSpace.probabilitys i $9>>!,innQ.?@IH  3 ')..I3))#.IJ J  2 &)..I3))#.IJ J}}y}},T"##D) 6#6 6 > Lt{{" %c$++&6D69J&J K BMBB+dkk++DHHgHHdkk3//1$7Dc%A*1d3E&&y':':5;;'JKF < J/5Dc4(A(D1E&&y':':5;;'JKF%v91556>95JIs I Ic t|}td|Dr-tdd}|jt ||z fi|}n*tdd}|jt ||fi|}t ||S)Nc3FK|]}t|jywr0r r s r+r3z;IndependentProductPSpace.compute_density..r r rTrr)rur5rrRrrr )rCrQrrrs r+rz(IndependentProductPSpace.compute_densitysT" 6#6 6c%A+4++Jtax,@Dc4(A+4++N4,CDar-c td)Nz0CDF not well defined on multivariate expressions)r)rCrQrs r+ compute_cdfz$IndependentProductPSpace.compute_cdfsKLLr-c t|}|j|jDcic]}||jc}}|Dcgc] }t |}}t d|Drddlm}m}|} ||j|} nZt d|Drddl m } m } | } | |j|} n*td|Drddlm} | j!||S|r|j"Dcic]}|t%t'|}} j(|j*fi|}|j*|j|z }t-t/| j"|}  Scc}wcc}wcc}w)Nc34K|]}|jywr0rYr1pss r+r3z=IndependentProductPSpace.conditional_space..s2Br2rr)ConditionalContinuousDomainContinuousPSpacec34K|]}|jywr0rZr.s r+r3z=IndependentProductPSpace.conditional_space.. s2B2r)ConditionalDiscreteDomainDiscretePSpacec34K|]}|jywr0rr.s r+r3z=IndependentProductPSpace.conditional_space..s0"0r) FinitePSpace)rurtrrarr5rr0r1rrr4r5rrr7conditional_spacer=rrrRrr rh)rCrw normalizerrrpspacesr0r1rrr4r5r7 replacementnormrrs r+r8z*IndependentProductPSpace.conditional_spacesJY'&& 'L"BII 'LM (+,"6":,, 2'2 2 "$E0iHF 2'2 2 "E.t{{IFF 00 0 411$ B B 9=F2Bc"g.FKF-6--dhhA&AD((T]];77CU6>>2C8GVW%%/(M,GsE3E82E=r)rT)rSrTrUrVr;r[rrr=rrrRrrr%rrr*r8r*r-r+rrs0==MM%%>>GGMMU :D M&r-rcfeZdZdZdZdZedZedZedZ edZ dZ d Z y ) rz A domain resulting from the merger of two independent domains. See Also ======== sympy.stats.crv.ProductContinuousDomain sympy.stats.frv.ProductFiniteDomain Tc^g}|D];}|js|j|!|j|j=t |}t d|Drddlm}|}t d|Drddlm }|}t d|Drddl m }|}tj|g|S)Nc34K|]}|jywr0rr1rs r+r3z(ProductDomain.__new__..4s7Fv7rr)ProductFiniteDomainc34K|]}|jywr0r-rAs r+r3z(ProductDomain.__new__..7s;v##;r)ProductContinuousDomainc34K|]}|jywr0r3rAs r+r3z(ProductDomain.__new__..:s9fv!!9r)ProductDiscreteDomain)rWappendextenddomainsrrrrBrrDrrFrr;)r<rIdomains2rrBrDrFs r+r;zProductDomain.__new__*s 0F**'/  0 h' 7h7 7 ;%C ;(; ; ?)C 99 9 ='C}}S,8,,r-cj|jDcic]}|jD]}||c}}Scc}}wr0)rIr=)rCrras r+sym_domain_dictzProductDomain.sym_domain_dict@sE-1\\C639>>C)/CC CCs/ctt|jDcgc]}|jD]}|c}}Scc}}wr0)rrIr=)rCrris r+r=zProductDomain.symbolsEsBT\\=6-3^^=#&=3=> >=s4 c|jSr0rArBs r+rIzProductDomain.domainsJs yyr-c4td|jDS)Nc34K|]}|jywr0)rHrAs r+r3z$ProductDomain.set..PsB6FJJBr)rrIrBs r+rHzProductDomain.setNsBT\\BCCr-c |jD]X}t|Dcgc];}t|jj |dt j ur|=c}}||vsXyycc}w)NrFT)rIrrr=containsrtrue)rCrLritemelems r+rMzProductDomain.__contains__Rsqll Fu)t!()@)@a)I!J!""(#)*D6! )sAA) cht|jDcgc]}|jc}Scc}wr0)rrIr~)rCrs r+r~zProductDomain.as_boolean_s(t||DVV&&(DEEDs/N) rSrTrUrVrWr;r[rLr=rIrHrMr~r*r-r+rrss-,CC>>DD Fr-rcnt|dd}|%d}t|t}t||SgS)z> Returns all RandomSymbols within a SymPy Expression. r6Nc.|jjSr0r)rs r+rz random_symbols..is"))..r-)r)getattrlistrsorted)rQr6compls r+rurucs> D'4 (E ( |$ %aT"" r-c&t|}t|tr|j |jS|j t r-t |jt d}|jSt|std|ztfdDrdjSddl m }ddl m}D](}t|j||fs|jcStDcgc]}|jc}Scc}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 rz6Expression containing Random Variable expected, not %sc3VK|] }|jdjk("yw)rN)r)r1rrs r+r3zpspace..s" 4"299A % 4s&)CompoundPSpace)StochasticPSpace)rrrrhasrrZr6rurrrrasympy.stats.stochastic_processrbr)rQrmrarbrrs @r+rrps 4=D$ %$++*A{{ xx"# $**/0 1! 4yy  C QUYZ[[ 4 441v}}6? bii.2B!C D99  $#%>Bbii%> ??%>s7Dc0tj|S)z Union of sets )runion)setss r+rrs 9;  d ##r-ci}|D]2}|Dcgc]}|j|jk(s| c}d||<4|Scc}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 rr)abrrsarsbs r+rs_swaprnsM AC!"?#cjjCJJ&>#?B#C H@s<<Nc dt|r t||r|St|trt ||j }t |}t|trt|dk(rtt|jtst|d}t||}t|tr4tj|j vrt#|j d}d}|D]^}|j%||}|dk(ry|dk7s"|dk(r#t|t&r|j%||}J||j%||z }`|dk(ry|Stt)||} | j*|fi|} 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 rGrTF)r,pspace_independentrrrrarurgrrrrrhr rrRealsr>rZrrrr8rnrrt) rQrwr condsymbolsrresultssumsrestemp fullspacerswapdicts r+givenrysN Y #5dI#F )\*y)"2"23  +K9b!c+&6!&; vd|**,= > ;  "9b) g| ,GLL1H7<<?+G /C99R%Dt|u} 19D*!=99R-DDIIb#..D / 19 uT9-.I 'I ' ' 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)rQrwr{rrr|s r+ expectationr~sK@ T? %F<<0{4+00:6:: tY ''r-c `||d<ddlm}|r|||jdi|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 r{r) Probabilityr*)r}rr)rwgiven_conditionr{rrrs r+rr,s?@&F<<;{9o6;;EfEE y/ 22r-c>eZdZedZddZedZddZy)Densityc |jdSr@rArBs r+rzDensity.Ts1r-Nct|}|tj||}|St|}tj|||}|Sr0)rrr;)r<rQrwrs r+r;zDensity.__new__VsK~  --T*C !+I--T95C r-cRt|jdkDr|jdSyrF)rgr>rBs r+rwzDensity.condition_s# tyy>A 99Q< r-c ddlm}ddlm}ddlm}ddlm}ddlm }|j|j} }t||r |jS| t|| fi|}t|s t!t"t%t"|z St|t&rut|j(t*||fr,t-|j(dr|j(j.St|j(|r|j(j0Stt)||r||d<t)|j2|fi|} |rt-| d r| j5S| S) Nr)RandomMatrixPSpace) JointPSpace) MatrixPSpacer`)SingleFiniteDistributionrcompound_evaluater)sympy.stats.random_matrixrrr sympy.stats.matrix_distributionsrrrarrrQrwrdictryrur r'rrrrrrmodelrr) rCrrrrrrarrQrwr&s r+rz Density.doitfs@4A:<))T^^i d4 599   y3F3Dd#!ZD12 2 dL )$++ k<'PQ ^4{{///DKK);<{{((( fTlN 3*2F& '---d=f= /;;= Mr-r0r=)rSrTrUr[rQr;rwrr*r-r+rrSs+ - .D r-rc `|rt||fd|i|St||jdd|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)) r{rr*)sampling_densityrr)rQrwrr{rs r+rrsLRiJ  )74 # ( ( E( Ef EEr-c |tt||fi|fi|St|j|fi|}|rt |dr|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)cdfryrr*rrrQrwrrr&s r+rrsa@5y3F3>v>>&VD\ % %d 5f 5FGFF+{{} r-c |tt||fi|fi|St|j|fi|}|rt |dr|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_functionryrcompute_characteristic_functionrrrs r+rrs^.&uT9'G'GR6RR 9VD\ 9 9$ I& IFGFF+{{} r-c |tt||fi|fi|St|j|fi|}|rt |dr|j S|S)Nr)moment_generating_functionryr"compute_moment_generating_functionrrrs r+rrs\)%i*J6*JUfUU >> 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)) )rryr)rwrrs r+rrsE."U9o@@KFKK #6)  " "9 7 77r-)r&)modulesr*c t||||||}|dk7r;td|d|f|zdddt|Dcgc] }t|c}St|Scc}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. )rrr{rrGz 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) z1.9z!deprecated-sympy-stats-numsamples)deprecated_since_versionactive_deprecations_target) sample_iterr#rangenext) rQrwrrr{rriteratorr2s r+r%r%-sF4wCMTXZHQ!)*4 5 *md234  &+'J ).j(9:1X:: >;sAc zt|j|fi|}|rt|dr|jS|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)rcompute_quantilerr)rQrrr&s r+quantilers=T+VD\ * *4 :6 :FGFF+{{} r-c  ddlm}tstdzt t n t t jt|r2jtjjinTi}jD]2} t| |st| j| j|| <4j|fd fddvrtfi| ntfdi|  tfi| f d}  f d } tjur| 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 rrFailed to import %scLjtt|Sr0rrzip)r>rQrs r+fn_subszsample_iter..fn_subs!syyc#tn-..r-cR$jtt|Syr)r)r>rwrs r+ given_fn_subsz"sample_iter..given_fn_subs$s&  >>$s3~"67 7r-pymcpymc3rc3B Kd}dttrfnz}| kr\ j| } Dcgc] }||d }} |}|dk7r|dk7r t d|sN||dz }| kr[yycc}w#ttf$r |}YGwxYww)Nr)rGrTF(Conditions must not contain free symbolsrG)rintr% NameErrorrr)count_sizerrr>gdrwfngiven_fnrrr{r/rrrs r+return_generator_infinitez.sample_iter..return_generator_infinite4sD#!6tgDAj  ugD AA'*+AbE!H+D+$.!4B:"+$BDDd)O QJE%j +"9-.&-B.s:8BB BB)B>BBBBBc3 Kd}|r| j fttrfnz }d}d}| krE|sCDcgc] }||| }}  |}|dk7r|dk7r t d|sd}|dz }| kr|sC|r|d}| kr)Dcgc] }|| }} ||dz }| kr(yycc}w#ttf$r |}YuwxYwcc}w#ttf$r |YIwxYww)NTrFrrrG)r%rrrrr)faultyrrrr>rrwrrrrrr{r/rrrs r+return_generator_finitez,sample_iter..return_generator_finiteKs[ }:dC;PVZ[")6AFE*$V/23"e 33(2%t_TzbEk(FHH!% *$V .j +./RAbE%L/D/ %$i QJEj #4 &y12*D120 y) %tn$ %sw?C5B5C5B:%C5C5 C5CC5!C( C53C5:CC5CC5C2/C51C22C5)rrr!rrrrZrrrrrar>rrInfinity)rQrwrrr{rrrsubr#rrrrrrr/rs`````` @@@@@@r+rrsUl7  !.899 E$ * + D\ ryy/C$)*yy$ T[[$++ FGH99 @C#01' CJJ?C @yy~/ ##c4 *6 * c4 ; ;F ;C5f5.""HQZZ(** " $$r-c $t|f||||d|SN)rwrr{rrrQrwrr{rrs r+sample_iter_lambdifyrt- t Cyt",4 C;A CCr-c $t|f||||d|Srrrs r+sample_iter_subsrzrr-c d}d}t||f|||d|} | D]} | r|dz } |dz }t||z } |r| jS| S)zg Sampling version of P. See Also ======== P sampling_E sampling_density rrr{rrG)rrevalf) rwrrr{rrr count_true count_falsesamplesr%r&s r+ sampling_Prs~JK)_Fg%/dF>DFG  !OJ 1 K  z]Z 'F ||~ r-c ttt||f|||d|}t||z }|r|jS|S)zf Sampling version of E. See Also ======== P sampling_P sampling_density r)rZrrr) rQrrr{rrrrr&s r+ sampling_ErsS;t_Fg%/dF>DFGG ']Z 'F ||~ r-c fi}t||f|||d|D]}|j|ddz||<|S)zk Sampling version of density. See Also ======== density sampling_P sampling_E rrrG)rget)rQrrr{rrrsr&s r+rrsXGdOJW)3$JBHJ5!++fa0145 Nr-ct||rytdd}t|t||t|k7xs"t|t||t|k7S)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 FrTr)rprrr)rjrkrs r+ dependentrs[6!QsA Ar!Qx GAJ . / Ar!Qx GAJ .0r-ct|| 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)rjrks r+ independentrs6A r-c*tt|j}tt|j}ttt |j t |dk7ryt|j |dk(ryy)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) rFTN)rHrr=rgru intersection)rjrk a_symbols b_symbolss r+rprp stF1I%%&IF1I%%&I 3~a ! . .~a/@ ABaG 9 ! !) ,-2 r-c| t|}|s|S|Dcic]}||j}}|j|Scc}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. )rurar)rQr=rrxs r+rv_subsr$sJ  &  (/0"BII 0H0 99X 1s=c"eZdZUdZded<dZy)NamedArgsMixinr*ztuple[str, ...] _argnamesc |j|jj|S#t$r&t dt |j d|dwxYw)N'z' object has no attribute ')r>rindexrAttributeErrortyperS)rCattrs r+ __getattr__zNamedArgsMixin.__getattr__5sU ,99T^^11$78 8 , T ##T"+, , ,s '*/AN)rSrTrUrrrr*r-r+rr2s!#I#,r-rceZdZddZy) DistributionNc Ht|}|dvr|td|z|dk(rGddlm}ddl}|t |t r|jj|}n|}||||}n|dk(rOdd l m } ddl}|t |t r|jj|}n|}|d k(rdn|} | || |}n|d vrdd l m } ddl } | jd j| j  ddl} | j)5| |8| j+t-|ddd|dddd}|j/|}nd}dddnt1dt3|z|St1d|d|#t$$rddl} YwxYw#1swY1xYw)z, A random realization from the distribution >rnumpyrr&Nrr&r)do_sample_scipy)rr)do_sample_numpyr*r)do_sample_pymcrrGF)drawschainscompute_convergence_checks progressbar random_seedreturn_inferencedataXz&Sampling from %s is not supported yet.z Sampling for z# is not currently implemented from )r!r!sympy.stats.sampling.sample_scipyrrrrrandom default_rng!sympy.stats.sampling.sample_numpyr sympy.stats.sampling.sample_pymcrlogging getLoggersetLevelERRORr ImportErrorrModelr%rreshaperKr)rCrrrmodulerr rand_statesampsrrrrrs r+r%zDistribution.sample?sw' 9 9fn2W<= = g  J |z$4"\\5545@ ! #D$ ;E   I |z$4"\\5545@ !  BJDDE#D%>> 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)rwmessagetruths r+ _value_checkr |s:d I K i E ~!! D=r-cxt|tr t|}t|tstd|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)rrrr)ris r+rnrns8P#sSk c6 "=sCDD Jr-c\ddlm}t||s td|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 rrr%)processr s r+sample_stochastic_processrs-@G g0 1LMM >> r-r0)NNT)NTN)NT)Nr*r&rGNr=)Nr&rGTN)Nr&rGN)mrV __future__r functoolsrmathrsympy.core.addrsympy.core.basicrsympy.core.containersrsympy.core.exprr sympy.core.functionr r sympy.core.logicr sympy.core.mulr sympy.core.relationalrrsympy.core.singletonrsympy.core.symbolrrsympy.core.sympifyr'sympy.functions.special.delta_functionsr(sympy.functions.special.tensor_functionsrsympy.logic.boolalgrr"sympy.matrices.expressions.matexprrsympy.tensor.indexedrsympy.utilities.lambdifyrrrsympy.sets.setsrrrsympy.solvers.solvesetr sympy.externalr!sympy.utilities.decoratorr"sympy.utilities.exceptionsr#sympy.utilities.iterablesr$__doctest_requires__r'r,registerr7r9r]rlrrrrrrrrrrrurrrnryr~rrrrrrrr%rrrrrrrrrrrprrrr rnrr*r-r+r,s #$"' 2&*"-&>C);(-,'??+(8@.$gY/ 3K E,, $5 $F6<6:&<&$ A AF4$U4$n2624B4BH,@ 1| 1  F  Y&}Y&vAFLAFH !@H$ &Rj&(R=A$3N/e/d-F`*ZB 8>J'29"v(vr/b!%2w zzZ%x*.B$%JJTC &* ! CMN $@HI $*:A'+("0J<. ,,<5<~7r,\#r-