B
    ¤ŠãZ‹  ã               @   sü   d dl mZmZmZ d dlZd dlZd dlmZ d dl	m
Z
 d dlmZ d dlmZ dggdgdggd	gddgd
ggdgddgdgd
dgdggdœZdd„ Zdd„ Ze dej ¡Zdd„ Zdd„ Zdd„ ZG dd„ deƒZedkrøddddgZeeƒZdS )é    )ÚdivisionÚprint_functionÚabsolute_importN)ÚHermiteE)Ú	factorial)Úrv_continuous)é   r   )r   é   )r	   r   )r   é   )r
   r   )r   é   )r	   r	   )r   r   )r   r	   r
   r   c             C   s>   | dk rt d|  ƒ‚yt|  S  tk
r8   tdƒ‚Y nX dS )aN   Return all non-negative integer solutions of the diophantine equation

            n*k_n + ... + 2*k_2 + 1*k_1 = n   (1)

    Parameters
    ----------
    n: int
        the r.h.s. of Eq. (1)

    Returns
    -------
    partitions: a list of solutions of (1). Each solution is itself
        a list of the form `[(m, k_m), ...]` for non-zero `k_m`.
        Notice that the index `m` is 1-based.

    Examples:
    ---------
    >>> _faa_di_bruno_partitions(2)
    [[(1, 2)], [(2, 1)]]
    >>> for p in _faa_di_bruno_partitions(4):
    ...     assert 4 == sum(m * k for (m, k) in p)

    r   z+Expected a positive integer; got %s insteadz'Higher order terms not yet implemented.N)Ú
ValueErrorÚ_faa_di_bruno_cacheÚKeyErrorÚNotImplementedError)Ún© r   úBlib/python3.7/site-packages/statsmodels/distributions/edgeworth.pyÚ_faa_di_bruno_partitions   s    r   c             C   sÈ   |dk rt d| ƒ‚t| ƒ|k r6t d||t| ƒf ƒ‚d}x|t|ƒD ]p}tdd„ |D ƒƒ}d|d  t|d ƒ }x8|D ]0\}}|t | |d  t|ƒ |¡t|ƒ 9 }qxW ||7 }qDW |t|ƒ9 }|S )aw  Compute n-th cumulant given moments.

    Parameters
    ----------
    momt: array_like
        `momt[j]` contains `(j+1)`-th moment.
        These can be raw moments around zero, or central moments
        (in which case, `momt[0]` == 0).
    n: integer
        which cumulant to calculate (must be >1)

    Returns
    -------
    kappa: float
        n-th cumulant.

    r   z,Expected a positive integer. Got %s instead.z0%s-th cumulant requires %s moments, only got %s.g        c             s   s   | ]\}}|V  qd S )Nr   )Ú.0ÚmÚkr   r   r   ú	<genexpr>S   s    z(cumulant_from_moments.<locals>.<genexpr>éÿÿÿÿ)r   Úlenr   Úsumr   ÚnpÚpower)Zmomtr   ZkappaÚpÚrÚtermr   r   r   r   r   Úcumulant_from_moments:   s    ,r    r	   c             C   s   t  | d  d ¡t S )Nr	   g       @)r   ZexpÚ_norm_pdf_C)Úxr   r   r   Ú	_norm_pdf^   s    r#   c             C   s
   t  | ¡S )N)ÚspecialÚndtr)r"   r   r   r   Ú	_norm_cdfa   s    r&   c             C   s   t  |  ¡S )N)r$   r%   )r"   r   r   r   Ú_norm_sfd   s    r'   c                   sB   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zd	d
„ Zdd„ Z‡  Z	S )ÚExpandedNormalar  Construct the Edgeworth expansion pdf given cumulants.

    Parameters
    ----------
    cum: array_like
        `cum[j]` contains `(j+1)`-th cumulant: cum[0] is the mean,
        cum[1] is the variance and so on.

    Notes
    -----
    This is actually an asymptotic rather than convergent series, hence
    higher orders of the expansion may or may not improve the result.
    In a strongly non-Gaussian case, it is possible that the density
    becomes negative, especially far out in the tails.

    Examples
    --------
    Construct the 4th order expansion for the chi-square distribution using
    the known values of the cumulants:

    >>> import matplotlib.pyplot as plt
    >>> from scipy import stats
    >>> from scipy.misc import factorial
    >>> df = 12
    >>> chi2_c = [2**(j-1) * factorial(j-1) * df for j in range(1, 5)]
    >>> edgw_chi2 = ExpandedNormal(chi2_c, name='edgw_chi2', momtype=0)

    Calculate several moments:
    >>> m, v = edgw_chi2.stats(moments='mv')
    >>> np.allclose([m, v], [df, 2 * df])
    True

    Plot the density function:
    >>> mu, sigma = df, np.sqrt(2*df)
    >>> x = np.linspace(mu - 3*sigma, mu + 3*sigma)
    >>> fig1 = plt.plot(x, stats.chi2.pdf(x, df=df), 'g-', lw=4, alpha=0.5)
    >>> fig2 = plt.plot(x, stats.norm.pdf(x, mu, sigma), 'b--', lw=4, alpha=0.5)
    >>> fig3 = plt.plot(x, edgw_chi2.pdf(x), 'r-', lw=2)
    >>> plt.show()

    References
    ----------
    .. [*] E.A. Cornish and R.A. Fisher, Moments and cumulants in the
         specification of distributions, Revue de l'Institut Internat.
         de Statistique. 5: 307 (1938), reprinted in
         R.A. Fisher, Contributions to Mathematical Statistics. Wiley, 1950.
    .. [*] http://en.wikipedia.org/wiki/Edgeworth_series
    .. [*] S. Blinnikov and R. Moessner, Expansions for nearly Gaussian
        distributions, Astron. Astrophys. Suppl. Ser. 130, 193 (1998)

    úEdgeworth expanded normalc                sâ   t |ƒdk rtdƒ‚|  |¡\| _| _| _t| jƒ| _| jjdkrZt| jdd …  ƒ| _	n
dd„ | _	t
 | j ¡ ¡}|| j | j }|t
 |¡dkt
 |¡dk @   ¡ r¼d| }t |t¡ | |dd	œ¡ tt| ƒjf |Ž d S )
Nr	   z"At least two cumulants are needed.r   c             S   s   dS )Ng        r   )r"   r   r   r   Ú<lambda>¤   s    z)ExpandedNormal.__init__.<locals>.<lambda>r   r   zPDF has zeros at %s )ÚnameZmomtype)r   r   Ú_compute_coefs_pdfZ_coefÚ_muÚ_sigmar   Ú	_herm_pdfÚsizeÚ	_herm_cdfr   Zreal_if_closeÚrootsÚimagÚabsÚanyÚwarningsÚwarnÚRuntimeWarningÚupdateÚsuperr(   Ú__init__)ÚselfÚcumr+   Úkwdsr   Zmesg)Ú	__class__r   r   r;   œ   s    
$
zExpandedNormal.__init__c             C   s(   || j  | j }|  |¡t|ƒ | j S )N)r-   r.   r/   r#   )r<   r"   Úyr   r   r   Ú_pdf±   s    zExpandedNormal._pdfc             C   s*   || j  | j }t|ƒ|  |¡t|ƒ  S )N)r-   r.   r&   r1   r#   )r<   r"   r@   r   r   r   Ú_cdfµ   s    zExpandedNormal._cdfc             C   s*   || j  | j }t|ƒ|  |¡t|ƒ  S )N)r-   r.   r'   r1   r#   )r<   r"   r@   r   r   r   Ú_sfº   s    zExpandedNormal._sfc          
   C   s  |d t  |d ¡ }}t  |¡}x,t|ƒD ] \}}||  |d |   < q,W t  |jd d ¡}d|d< x¤t|jd ƒD ]’}xŒt|d ƒD ]|}	||d  }
x<|	D ]4\}}|
t  ||d  t	|d ƒ |¡t	|ƒ 9 }
q¤W t
dd„ |	D ƒƒ}||d d|    |
7  < qŽW q|W |||fS )	Nr   r   r
   é   g      ð?r	   c             s   s   | ]\}}|V  qd S )Nr   )r   r   r   r   r   r   r   Í   s    z4ExpandedNormal._compute_coefs_pdf.<locals>.<genexpr>)r   ÚsqrtZasarrayÚ	enumerateZzerosr0   Úranger   r   r   r   )r<   r=   ZmuZsigmaZlamÚjÚlZcoefÚsr   r   r   r   r   r   r   r   r,   ¿   s    
0$z!ExpandedNormal._compute_coefs_pdf)r)   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r;   rA   rB   rC   r,   Ú__classcell__r   r   )r?   r   r(   h   s   3r(   Ú__main__r   )Z
__future__r   r   r   r6   Znumpyr   Znumpy.polynomial.hermite_er   Z
scipy.miscr   Zscipy.statsr   Zscipy.specialr$   r   r   r    rE   Zpir!   r#   r&   r'   r(   rK   r=   Zenr   r   r   r   Ú<module>   s(   	
 "#j