
    M/Ph@                        d Z ddlZddlmZmZmZ ddl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 n# e$ r	 ddlmZ Y nw xY w G d d	e
j                  Z e            Z G d
 de
j                  Z edd          Z G d de
j                  Zd Zd Zd Zd Z G d de
j                  Z	 d Z G d de
j                  Zd Zd\  Z Z!d\  Z Z!d Z"d Z#d Z$ eej%        e"e#d dd!d"d#$          Z& eej%        ej        ej'        d%dd&d'(          Z( eej)        ej'        ej        d)*          Z*	  G d+ d,e
j                  Z+ G d- d.e
j                  Z,	 	  G d/ d0e
j                  Z- G d1 d2          Z. e.            Z/ e-ej%        e/j0        e/j1        e/j2        e/j3        e/j4        d3d4ej5        dd5d67          Z6 e-ej7        e/j0        e/j1        e/j2        e/j3        e/j4        d3d4ej5        d)d5d87          Z8d9 Z1d: Z2d; Z3d< Z4d= Z9 e-ej%        e9e1e2e3e4d>ej5         d4dd?d@7          Z:dA Z1dB Z2dC Z3dD Z4dE Z; e-ej%        ej<        e1e2e3e4d3d4ej5        ddFdG7          Z=	 dHdIdJdKZ>dL Z?dNdMZ@dS )Oa  Various extensions to distributions

* skew normal and skew t distribution by Azzalini, A. & Capitanio, A.
* Gram-Charlier expansion distribution (using 4 moments),
* distributions based on non-linear transformation
  - Transf_gen
  - ExpTransf_gen, LogTransf_gen
  - TransfTwo_gen
    (defines as examples: square, negative square and abs transformations)
  - this versions are without __new__
* mnvormcdf, mvstdnormcdf : cdf, rectangular integral for multivariate normal
  distribution

TODO:
* Where is Transf_gen for general monotonic transformation ? found and added it
* write some docstrings, some parts I do not remember
* add Box-Cox transformation, parametrized ?


this is only partially cleaned, still includes test examples as functions

main changes
* add transf_gen (2010-05-09)
* added separate example and tests (2010-05-09)
* collect transformation function into classes

Example
-------

>>> logtg = Transf_gen(stats.t, np.exp, np.log,
                numargs = 1, a=0, name = 'lnnorm',
                longname = 'Exp transformed normal',
                extradoc = '
distribution of y = exp(x), with x standard normal'
                'precision for moment andstats is not very high, 2-3 decimals')
>>> logtg.cdf(5, 6)
0.92067704211191848
>>> stats.t.cdf(np.log(5), 6)
0.92067704211191848

>>> logtg.pdf(5, 6)
0.021798547904239293
>>> stats.t.pdf(np.log(5), 6)
0.10899273954837908
>>> stats.t.pdf(np.log(5), 6)/5.  #derivative
0.021798547909675815


Author: josef-pktd
License: BSD

    N)poly1dsqrtexp)statsspecial)distributions)mvsk2mcmc2mvsk)mvndstc                   8    e Zd ZdZd Zd Zd Zd Zd Zd
dZ	d	S )SkewNorm_genzunivariate Skew-Normal distribution of Azzalini

    class follows scipy.stats.distributions pattern
    but with __init__


    c                 J    t           j                            | dd           d S )NSkew Normal distributionalphanameshapesr   rv_continuous__init__selfs    h/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/sandbox/distributions/extras.pyr   zSkewNorm_gen.__init__R   s5    #,,+ 	- 	
 	
 	
 	
 	
    c                     dS N    r   r   s     r   	_argcheckzSkewNorm_gen._argcheckZ       qr   c                 H   |t          j        d|dz  z             z  }t          j                            | j                  }||z  t          j        d|dz  z
            t          j                            | j                  z  z   }t          j        |dk    ||           S )Nr      sizer   )npr   r   normrvs_sizewhere)r   r   deltau0u1s        r   _rvszSkewNorm_gen._rvs]   s    EQJ///Z^^^,,RZ"'!eqj.11EJNN
N4S4SSSxQRC(((r   c                 .    |                      ||          S N_mom0_sc)r   nr   s      r   _munpzSkewNorm_gen._munpd   s     }}Q&&&r   c                     dt          j        dt           j        z            z  t          j        |dz   dz            z  t	          j        ||z            z  S N       @r#   r&   r   pir   r   ndtrr   xr   s      r   _pdfzSkewNorm_gen._pdfi   J    RWQY'''"&!q&3*?*??',uWXyBYBYYYr   mvskc                     d S r0   r   )r   r<   r   momentss       r   _stats_skipzSkewNorm_gen._stats_skipm   s    r   Nr?   )
__name__
__module____qualname____doc__r   r    r.   r4   r=   rB   r   r   r   r   r   I   s         
 
 
  ) ) )' ' '
Z Z Z     r   r   c                       e Zd ZdZd Zd ZdS )SkewNorm2_genzjunivariate Skew-Normal distribution of Azzalini

    class follows scipy.stats.distributions pattern

    c                     dS r   r   r   s     r   r    zSkewNorm2_gen._argcheck}   r!   r   c                     dt          j        dt           j        z            z  t          j        |dz   dz            z  t	          j        ||z            z  S r6   r8   r;   s      r   r=   zSkewNorm2_gen._pdf   r>   r   N)rD   rE   rF   rG   r    r=   r   r   r   rI   rI   v   sA           Z Z Z Z Zr   rI   r   r   r   c                   0    e Zd ZdZd Zd Zd Zd Zd ZdS )ACSkewT_genzzunivariate Skew-T distribution of Azzalini

    class follows scipy.stats.distributions pattern
    but with __init__
    c                 J    t           j                            | dd           d S )NzSkew T distributionz	df, alphar   r   r   s    r   r   zACSkewT_gen.__init__   s5    #,,& 	- 	
 	
 	
 	
 	
r   c                     ||k    |dk    z  S )Nr   r   )r   dfr   s      r   r    zACSkewT_gen._argcheck   s    26**r   c                     t           j                            || j                  }t                              || j                  }|t          j        ||z            z  S )Nr$   )r   chi2r(   r)   skewnormr&   r   )r   rP   r   Vzs        r   r.   zACSkewT_gen._rvs   sK     JNN2DJN//LLTZL00271r6??""r   c                 0    |                      |||          S r0   r1   )r   r3   rP   r   s       r   r4   zACSkewT_gen._munp   s     }}QE***r   c           
          dt           j                            ||          z  t          j        |dz   ||z  t          j        d|z   |dz  |z   z            z            z  S )Nr7   r   r#   )r   tr=   r   stdtrr&   r   )r   r<   rP   r   s       r   r=   zACSkewT_gen._pdf   sm    ]_))!R0007=aQRUWU\VQ$V& V& J& 4' 4' ' 	'r   N)	rD   rE   rF   rG   r   r    r.   r4   r=   r   r   r   rM   rM      si         
 
 
0+ + +# # #+ + +
' ' ' ' 'r   rM   c                     d g| z  }t          d          |d<   t          d|           D ]@}||dz
                                           t          ddg          ||dz
           z  z
  ||<   A|S )Nr   r   )r   rangederiv)Nplistr3   s      r   	_hermnormr_      sw     FQJEayyE!H1a[[ H HQ<%%''&!Q..5Q<*GGaLr   c                   	
 t          |           }|dk     rt          d          t          d          t          | d                   
| d         	|dk    rt	          |dz             }t          d|dz             D ]~}d}t          |dz
  dz            D ]^}|d|z  z
  }|dz  r| |dz
           }n)| |dz
           

z  t          j        |dz
            z  z
  }|||         |         
|z  z  |z  z  }_t          	
fd}|fS )zReturn the Gaussian expanded pdf function given the list of central
    moments (first one is mean).

    version of scipy.stats, any changes ?
    the scipy.stats version has a bug and returns normal distribution
    r#   :At least two moments must be given to approximate the pdf.r   r              c                     | z
  z  } |          t          | |z  dz            z  t          dt          j        z            z  z  S r6   )r   r   r&   r9   r<   xnmusigtotps     r   thisfuncz pdf_moments_st.<locals>.thisfunc  sK    "f^tBxx#rcBhn---QY?#EEr   )
len
ValueErrorr   r   r_   r[   scipy
factorial2SystemErrorprint)cntr]   DvalskCkr3   mmomdiffrj   rg   rh   ri   s            @@@r   pdf_moments_strw      sa    	CA1uu 0 1 1 	1 !99D
s1v,,C	QB1uu!a%  1a!e__ $ $A{## 	3 	3AAE	A1u Ka!e*a!e*sSy53CAE3J3J'JJ%(1+q(722BB
F F F F F F F T>r   c                 $  	
 t          |           }|dk     rt          d          | \  	}}}t          d          t          |          
|dk    r6t	          |dz             }|dz  }|dz  }||d         z  z
  ||d         z  z   	
fd}|S )	a;  Return the Gaussian expanded pdf function given the list of 1st, 2nd
    moment and skew and Fisher (excess) kurtosis.



    Parameters
    ----------
    mvsk : list of mu, mc2, skew, kurt
        distribution is matched to these four moments

    Returns
    -------
    pdffunc : function
        function that evaluates the pdf(x), where x is the non-standardized
        random variable.


    Notes
    -----

    Changed so it works only if four arguments are given. Uses explicit
    formula, not loop.

    This implements a Gram-Charlier expansion of the normal distribution
    where the first 2 moments coincide with those of the normal distribution
    but skew and kurtosis can deviate from it.

    In the Gram-Charlier distribution it is possible that the density
    becomes negative. This is the case when the deviation from the
    normal distribution is too large.



    References
    ----------
    https://en.wikipedia.org/wiki/Edgeworth_series
    Johnson N.L., S. Kotz, N. Balakrishnan: Continuous Univariate
    Distributions, Volume 1, 2nd ed., p.30
       z2Four moments must be given to approximate the pdf.r   r#         @      8@rb   c                     | z
  z  } |          t          j        | |z  dz            z  t          j        dt           j        z            z  z  S r6   r&   r   r   r9   re   s     r   pdffunczpdf_mvsk.<locals>.pdffuncY  Q    "f^tBxx"&"rC000271ru93E3EEKKr   rk   rl   r   r   r_   )r?   r]   mc2skewkurtrr   C3C4r~   rg   rh   ri   s            @@@r   pdf_mvskr      s    P 	D		A1uu 0 1 1 	1 BT4!99D
s))C1uu!a%  CZD[ b58m#b58m3L L L L L L L Nr   c                 f   t          |           }|dk     rt          d          | \  }}}}||dz  z  }||dz  z  dz
  }t          d          t          | d                   | d         |dk    r6t	          |dz             }|dz  }	|d	z  }
|	|d
         z  z
  |
|d         z  z   fd}|S )a  Return the Gaussian expanded pdf function given the list of central
    moments (first one is mean).

    Changed so it works only if four arguments are given. Uses explicit
    formula, not loop.

    Notes
    -----

    This implements a Gram-Charlier expansion of the normal distribution
    where the first 2 moments coincide with those of the normal distribution
    but skew and kurtosis can deviate from it.

    In the Gram-Charlier distribution it is possible that the density
    becomes negative. This is the case when the deviation from the
    normal distribution is too large.



    References
    ----------
    https://en.wikipedia.org/wiki/Edgeworth_series
    Johnson N.L., S. Kotz, N. Balakrishnan: Continuous Univariate
    Distributions, Volume 1, 2nd ed., p.30
    r#   ra   g      ?r7   g      @r   r   rz   r{   rb   ry   c                     | z
  z  } |          t          j        | |z  dz            z  t          j        dt           j        z            z  z  S r6   r}   re   s     r   rj   zpdf_moments.<locals>.thisfunc  r   r   r   )rq   r]   mcr   mc3mc4r   r   rr   r   r   rj   rg   rh   ri   s               @@@r   pdf_momentsr   `  s   4 	CA1uu 0 1 1 	1 BS#Dc!D!99D
s1v,,C	QB1uu!a%    CZD[b58m#b58m3L L L L L L L Or   c                   $    e Zd ZdZd Zd Zd ZdS )NormExpan_genzGram-Charlier Expansion of Normal distribution

    class follows scipy.stats.distributions pattern
    but with __init__

    c                    t           j                            | dd           |                    dd          }|dk    r@t	          j        |          dd          \  }}}}||||f| _        t          ||||f          }nI|dk    rt          |          }|| _        n,|dk    r|}t          |          | _        nt          d	          || _
        t          | j                  | _        d S )
NzNormal Expansion distribution r   modesampler#   r?   centmomzmode must be 'mvsk' or centmom)r   r   r   getr   describer?   r	   r
   rl   rq   r   r=   )	r   argskwdsr   rg   rh   skkurrq   s	            r   r   zNormExpan_gen.__init__  s    #,,0 	- 	
 	
 	
. xx))8$~d33ABB7BRS"c*DI2sB,--CCV^^$--CDIIYCDII=>>> TY''			r   c                 ,    |                      |          S r0   r1   )r   r3   s     r   r4   zNormExpan_gen._munp  s     }}Qr   c                     | j         S r0   rC   r   s    r   rB   zNormExpan_gen._stats_skip  s
    yr   N)rD   rE   rF   rG   r   r4   rB   r   r   r   r   r     sL         +( +( +(Z     
    r   r   c                  r    d |                                  D             }|                    dd           }||fS )Nc                 n    i | ]2\  }}|                     d           |                    d dd          |3S )u_ r   )
startswithreplace).0rs   vs      r   
<dictcomp>z$get_u_argskwargs.<locals>.<dictcomp>  sN     + + +da||D))+		$A&& + + +r   u_args)itemspop)kwargsu_kwargsr   s      r   get_u_argskwargsr   	  sE    + +fllnn + + +H\\(D))F8r   c                   4     e Zd ZdZ fdZd Zd Zd Z xZS )
Transf_genzUa class for non-linear monotonic transformation of a continuous random variable

    c                     || _         || _        |                    dd          | _        |                    dd          }|                    dd          }|                    dd           }|                    dt          j                   }	|                    d	t          j                  }
|                    d
d          | _        t          di |\  | _        | _	        || _
        t                                          |	|
||           d S )Nnumargsr   r   
transfdistlongname#Non-linear transformed distributionextradocabdecrF)r   r   r   r   r   )funcfuncinvr   r   r&   infr   r   r   r   klssuperr   )r   r   r   r   r   r   r   r   r   r   r   	__class__s              r   r   zTransf_gen.__init__  s     	 zz)Q//zz&,//::j*OPP::j$//JJsRVG$$JJsBF##JJvu--	 &6%?%?%?%?"T] 	1x@@@@@r   c                 h    | j         | j        _         |                      | j        j        |           S r0   )r)   r   r   r.   )r   r   r   s      r   r.   zTransf_gen._rvs0  s*    ||MDHM40111r   c                     | j         s) | j        j        |                     |          g|R i |S d | j        j        |                     |          g|R i |z
  S N      ?)r   r   _cdfr   r   r<   r   r   s       r   r   zTransf_gen._cdf4  sp    y 	I 48=aB4BBB6BBB t||AHHHHHHHHr   c                     | j         s)|                      | j        j        |g|R i |          S |                      | j        j        d|z
  g|R i |          S r   )r   r   r   _ppf)r   qr   r   s       r   r   zTransf_gen._ppf<  sq    y 	D99]TX]1>t>>>v>>???99]TX]1q5B4BBB6BBCCCr   )	rD   rE   rF   rG   r   r.   r   r   __classcell__r   s   @r   r   r     s~         A A A A A42 2 2I I ID D D D D D Dr   r   c                 ,    t          j        d|           S r   )r&   divider<   s    r   inverser   C  s    9S!r   )g?g?)g      "@r   c                 2    ddt           z   | t          z  z   z  S )Nr   r   muxstdxr   s    r   inversewr   K  s    !c'AH$%%r   c                 2    d| z  dz
  t           z
  t          z  S r   r   r   s    r   inversew_invr   O  s    !GcMC4''r   c                     | S r0   r   r   s    r   identitr   S      Hr   Tdiscfznormal-based discount factorzA
distribution of discount factor y=1/(1+x)) with x N(0.05,0.1**2))r   r   r   r   r   r#   lnnormzExp transformed normal)r   r   r   r   r   )r   c                   .     e Zd ZdZ fdZd Zd Z xZS )ExpTransf_genDistribution based on log/exp transformation

    the constructor can be called with a distribution class
    and generates the distribution of the transformed random variable

    c                     d|v r|d         | _         nd| _         d|v r	|d         }nd}d|v r	|d         }nd}t                                          d|           || _        d S Nr   r   r   zLog transformed distributionr   r   )r   r   r   r   r   r   r   r   r   r   r   r   r   s         r   r   zExpTransf_gen.__init__t  s     !),DLLDLV&>DD1D&==sAAA14(((r   c                 N    	  | j         j        t          j        |          g|R  S r0   )r   cdfr&   logr   r<   r   s      r   r   zExpTransf_gen._cdf  s)    tx|BF1II-----r   c                 L    t          j         | j        j        |g|R            S r0   )r&   r   r   ppfr   r   r   s      r   r   zExpTransf_gen._ppf  s(    vldhl1,t,,,---r   rD   rE   rF   rG   r   r   r   r   r   s   @r   r   r   l  s`             &. . .
. . . . . . .r   r   c                   .     e Zd ZdZ fdZd Zd Z xZS )LogTransf_genr   c                     d|v r|d         | _         nd| _         d|v r	|d         }nd}d|v r	|d         }nd}t                                          ||           || _        d S r   r   r   s         r   r   zLogTransf_gen.__init__  s    !),DLLDLV&>DD1D&==sAAA14(((r   c                 L     | j         j        t          j        |          g|R  S r0   )r   r   r&   r   r   s      r   r   zLogTransf_gen._cdf  s&    tx}RVAYY.....r   c                 L    t          j         | j        j        |g|R            S r0   )r&   r   r   r   r   s      r   r   zLogTransf_gen._ppf  s(    vmdhmA----...r   r   r   s   @r   r   r     s`             $/ / // / / / / / /r   r   c                   @     e Zd ZdZ fdZd Zd Zd Zd Zd Z	 xZ
S )TransfTwo_genaO  Distribution based on a non-monotonic (u- or hump-shaped transformation)

    the constructor can be called with a distribution class, and functions
    that define the non-linear transformation.
    and generates the distribution of the transformed random variable

    Note: the transformation, it's inverse and derivatives need to be fully
    specified: func, funcinvplus, funcinvminus, derivplus,  derivminus.
    Currently no numerical derivatives or inverse are calculated

    This can be used to generate distribution instances similar to the
    distributions in scipy.stats.

    c                    || _         || _        || _        || _        || _        |                    dd          | _        |                    dd          }	|                    dd          }
|                    dd           }|                    dt          j                   }|                    d	t          j                  }|                    d
d          | _	        t          di |\  | _        | _        || _        t                                          |||	|j        |
           | j                            t'          ||||||| j	                             d S )Nr   r   r   r   r   r   r   r   r   shapeF)r   r   r   r   r   )r   r   funcinvplusfuncinvminus	derivplus
derivminusr   r   )r   r   r   r   r   r   r   r&   r   r   r   r   r   r   r   r   r   _ctor_paramupdatedict)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                 r   r   zTransfTwo_gen.__init__  s\   
 	&("$ zz)Q//zz&,//::j*OPP::j$//JJsRVG$$JJsBF##ZZ//
 &6%?%?%?%?"T] 	14
X 	 	
 	
 	

 	St*i&dj: : :	
 	
 	
 	
 	
r   c                 h    | j         | j        _         |                      | j        j        |           S r0   )r)   r   r   r.   )r   r   s     r   r.   zTransfTwo_gen._rvs  s*    yy-...r   c                 \   | j         dk    rd}n| j         dk    rd}nt          d          ||                     |           | j        j        |                     |          g|R i |z  |                     |           | j        j        |                     |          g|R i |z  z
  z  S )Nur   humpzshape can only be `u` or `hump`)r   rl   r   r   r=   r   r   r   )r   r<   r   r   signpdfs        r   r=   zTransfTwo_gen._pdf  s    :GGZ6!!GG>???$..++mdhmD<L<LQ<O<O.aRV.a.a.aZ`.a.aa//!,,}tx}T=N=Nq=Q=Q 0GTX 0G 0G 0G?E0G 0G GG H 	Hr   c                     | j         dk    rS | j        j        |                     |          g|R i | | j        j        |                     |          g|R i |z
  S d | j        |g|R i |z
  S )Nr   r   )r   r   r   r   r   _sfr   s       r   r   zTransfTwo_gen._cdf"  s    : 48=!1!1!!4!4FtFFFvFFd//22DTDDDVDDE E !5d555f5555r   c                     | j         dk    rS | j        j        |                     |          g|R i | | j        j        |                     |          g|R i |z
  S d | j        |g|R i |z
  S )Nr   r   )r   r   r   r   r   r   s       r   r   zTransfTwo_gen._sf+  s    : 48=!1!1!!4!4FtFFFvFFd//22DTDDDVDDE E 16t666v6666r   c                     d |D             }t          j         | j        |g|R            }t          j        |          rt	          |          S |S )Nc                 6    g | ]}t          j        |          S r   )r&   squeeze)r   args     r   
<listcomp>z'TransfTwo_gen._munp.<locals>.<listcomp>5  s     000C
3000r   )r&   r  r2   isscalarfloat)r   r3   r   r   outs        r   r4   zTransfTwo_gen._munp4  s[    004000jq0400011;s 	::
r   )rD   rE   rF   rG   r   r.   r=   r   r   r4   r   r   s   @r   r   r     s          $
 $
 $
 $
 $
L/ / /H H H6 6 67 7 7      r   r   c                   0    e Zd ZdZd Zd Zd Zd Zd ZdS )
SquareFunczclass to hold quadratic function with inverse function and derivative

    using instance methods instead of class methods, if we want extension
    to parametrized function
    c                 *    t          j        |          S r0   r&   r   r   r<   s     r   inversepluszSquareFunc.inverseplusM  s    wqzzr   c                 0    dt          j        |          z
  S Nrc   r
  r  s     r   inverseminuszSquareFunc.inverseminusP      RWQZZr   c                 0    dt          j        |          z  S N      ?r
  r  s     r   r   zSquareFunc.derivplusS  r  r   c                 6    ddt          j        |          z  z
  S Nrc   r  r
  r  s     r   r   zSquareFunc.derivminusV  s    S271::%%%r   c                 ,    t          j        |d          S Nr#   r&   powerr  s     r   
squarefunczSquareFunc.squarefuncY  s    x1~~r   N)	rD   rE   rF   rG   r  r  r   r   r  r   r   r   r  r  F  si                     & & &    r   r  r   rc   
squarenormzsquared normal distribution)r   r   r   r   r   r   zsquared t distributionc                 ,    t          j        |            S r0   r
  r   s    r   r  r  p  s    7A2;;r   c                 2    dt          j        |            z
  S r  r
  r   s    r   r  r  t      !r   c                 8    ddt          j        |            z  z
  S r  r
  r   s    r   r   r   x  s    rwr{{"""r   c                 2    dt          j        |            z  S r  r
  r   s    r   r   r   |  r  r   c                 .    t          j        | d           S r  r  r   s    r   negsquarefuncr"    s    HQNN?r   r   negsquarenormz$negative squared normal distributionc                     | S r0   r   r   s    r   r  r    r   r   c                     d| z
  S r  r   r   s    r   r  r    s    7Nr   c                     dS r   r   r   s    r   r   r     s    3r   c                     dS )Ng      r   r   s    r   r   r     s    9r   c                 *    t          j        |           S r0   )r&   absr   s    r   absfuncr*    s    6!99r   absnormzabsolute of normal distributionz"normal completion with ERROR < EPSzscompletion with ERROR > EPS and MAXPTS function values used;
                    increase MAXPTS to decrease ERROR;zN > 500 or N < 1)r   r   r#   c                    t          |           }t          j        |           } t          j        |          }t          j        |          }t          j        t	          ||dz
  z  dz                      }| j        dk    s|j        dk    rt          d          t          |          |k    rt          d          |dk    r|j        dk    r|}nb|j        dk    rt          |          ||dz
  z  dz  k    r|}n8|j        ||fk    r|t          j	        |d                   }nt          d          d|vr|dk    rd	|z  |d<   t          j
        |           }t          j        |          }dt          j        |          z  }t          j        ||d
           t          j        ||d           t          j        |||z  d           t          | |||fi |\  }	}
}|rt          dt           |         |	           |
S )a	  standardized multivariate normal cumulative distribution function

    This is a wrapper for scipy.stats._mvn.mvndst which calculates
    a rectangular integral over a standardized multivariate normal
    distribution.

    This function assumes standardized scale, that is the variance in each dimension
    is one, but correlation can be arbitrary, covariance = correlation matrix

    Parameters
    ----------
    lower, upper : array_like, 1d
       lower and upper integration limits with length equal to the number
       of dimensions of the multivariate normal distribution. It can contain
       -np.inf or np.inf for open integration intervals
    corrcoef : float or array_like
       specifies correlation matrix in one of three ways, see notes
    optional keyword parameters to influence integration
        * maxpts : int, maximum number of function values allowed. This
             parameter can be used to limit the time. A sensible
             strategy is to start with `maxpts` = 1000*N, and then
             increase `maxpts` if ERROR is too large.
        * abseps : float absolute error tolerance.
        * releps : float relative error tolerance.

    Returns
    -------
    cdfvalue : float
        value of the integral


    Notes
    -----
    The correlation matrix corrcoef can be given in 3 different ways
    If the multivariate normal is two-dimensional than only the
    correlation coefficient needs to be provided.
    For general dimension the correlation matrix can be provided either
    as a one-dimensional array of the upper triangular correlation
    coefficients stacked by rows, or as full square correlation matrix

    See Also
    --------
    mvnormcdf : cdf of multivariate normal distribution without
        standardization

    Examples
    --------

    >>> print(mvstdnormcdf([-np.inf,-np.inf], [0.0,np.inf], 0.5))
    0.5
    >>> corr = [[1.0, 0, 0.5],[0,1,0],[0.5,0,1]]
    >>> print(mvstdnormcdf([-np.inf,-np.inf,-100.0], [0.0,0.0,0.0], corr, abseps=1e-6))
    0.166666399198
    >>> print(mvstdnormcdf([-np.inf,-np.inf,-100.0],[0.0,0.0,0.0],corr, abseps=1e-8))
    something wrong completion with ERROR > EPS and MAXPTS function values used;
                        increase MAXPTS to decrease ERROR; 1.048330348e-006
    0.166666546218
    >>> print(mvstdnormcdf([-np.inf,-np.inf,-100.0],[0.0,0.0,0.0], corr,                             maxpts=100000, abseps=1e-8))
    0.166666588293

    r   r7   zcan handle only 1D boundszbounds have different lengthsr#   r   z corrcoef has incorrect dimensionmaxptsi'  r   zsomething wrong)rk   r&   arrayzerosintndimrl   r%   r   tril_indicesisneginfisposinfonesputmaskr   rp   
informcode)loweruppercorrcoefr   r3   correllowinfuppinfinfinerrorcdfvalueinforms               r   mvstdnormcdfrB     s   ~ 	E

A HUOOEHUOOEx!!HXc!q1u++,,--F
aUZ1__4555
5zzQ8999Avv(-1$$	!		Ha!es1B B B	Aq6	!	!"/!R001
 ;<<<tq55"QYDN[F[F"'!**EJufa   Jufa   Jufvor*** %UE5&IIDIIE8V <F!3U;;;Or   c                    t          j        |           } |(t          j        | j                   t           j        z  }nt          j        |          }t          j        |          }t          j        t          j        |                    }||z
  |z  }| |z
  |z  } t          j        |          }||z  |j        z  }t          || |fi |S )aA  multivariate normal cumulative distribution function

    This is a wrapper for scipy.stats._mvn.mvndst which calculates
    a rectangular integral over a multivariate normal distribution.

    Parameters
    ----------
    lower, upper : array_like, 1d
       lower and upper integration limits with length equal to the number
       of dimensions of the multivariate normal distribution. It can contain
       -np.inf or np.inf for open integration intervals
    mu : array_lik, 1d
       list or array of means
    cov : array_like, 2d
       specifies covariance matrix
    optional keyword parameters to influence integration
        * maxpts : int, maximum number of function values allowed. This
             parameter can be used to limit the time. A sensible
             strategy is to start with `maxpts` = 1000*N, and then
             increase `maxpts` if ERROR is too large.
        * abseps : float absolute error tolerance.
        * releps : float relative error tolerance.

    Returns
    -------
    cdfvalue : float
        value of the integral


    Notes
    -----
    This function normalizes the location and scale of the multivariate
    normal distribution and then uses `mvstdnormcdf` to call the integration.

    See Also
    --------
    mvstdnormcdf : location and scale standardized multivariate normal cdf
    )
r&   r.  r5  r   r   r   diag
atleast_2dTrB  )r9  rg   covr8  r   stdevdivrowcorrs           r   	mvnormcdfrK  u  s    P HUOOE}%%%.
(3--CGBGCLL!!E RZ5 ERZ5 E]5!!F<&("D ud33d333r   r0   )ArG   numpyr&   r   r   r   rm   r   r   scipy.statsr    statsmodels.stats.moment_helpersr	   r
   scipy.stats._mvnr   ImportErrorscipy.stats.mvnr   r   rS   rI   	skewnorm2rM   r_   rw   r   r   r   r   r   r   r   r   r   r   r   r'   invdnormalgr   
lognormalggammaloggammaexpgr   r   r   r  sqfuncr  r  r  r   r   r   squarenormalgrX   squaretgr"  negsquarenormalgr*  r)  
absnormalgr7  rB  rK  r   r   r   <module>r\     s  2 2h     # # # # # # # # # #                  % % % % % % = = = = = = = ='''''''' ' ' ' '&&&&&&&'& & & & &=. & & &R <>>Z Z Z Z ZM/ Z Z Z M9'   	
6' 6' 6' 6' 6'-- 6' 6' 6'@
 
 
& & &R= = =@? ? ?D< < < < <M/ < < <B#L  /D /D /D /D /D, /D /D /Dd   	T	T& & &( ( (   jX|$!";Y"fh h h Z
BFBF !QX!9  
 z%+rvrvqAAA!. !. !. !. !.M/ !. !. !.H/ / / / /M/ / / /H>` ` ` ` `M/ ` ` `Z       . 
ej&*;V=O$163CVEV$'3"&&'lEb      =&"3V5G,f.>@Q"cRV!"@X      # # #     !=]K!*JfSV)**P# # #            ]5:rv{L$jsbf#$9?`  
M^ 6:#% %
r r rj74 74 74 74 74 74s   3 A A