U
    Kvf»N  ã                   @   s¢   d Z ddlZddlmZ ddlZddlmZ ddl	m
Z
 ddlmZ dd„ Zdd
d„Zddd„ZG dd„ deƒZd dd„Zd!dd„Zd"dd„Zdd„ Zdd„ ZdS )#z=
Created on Fri Sep 15 12:53:45 2017

Author: Josef Perktold
é    N)Ústats)ÚHolderTuple)ÚPoisson)ÚOLSc           	      C   s²   t  |¡}|jdkr*d}|ddd…f }nd}g }g }tt| ƒd ƒD ]F}| ||d … \}}| |dd…||…f  d¡¡ | || ¡ qFt  |¡}|r¤| ¡ }|t  |¡fS )aÅ  group columns into bins using sum

    This is mainly a helper function for combining probabilities into cells.
    It similar to `np.add.reduceat(x, edge_index, axis=-1)` except for the
    treatment of the last index and last cell.

    Parameters
    ----------
    edge_index : array_like
         This defines the (zero-based) indices for the columns that are be
         combined. Each index in `edge_index` except the last is the starting
         index for a bin. The largest index in a bin is the next edge_index-1.
    x : 1d or 2d array
        array for which columns are combined. If x is 1-dimensional that it
        will be treated as a 2-d row vector.

    Returns
    -------
    x_new : ndarray
    k_li : ndarray
        Count of columns combined in bin.


    Examples
    --------
    >>> dia.combine_bins([0,1,5], np.arange(4))
    (array([0, 6]), array([1, 4]))

    this aggregates to two bins with the sum of 1 and 4 elements
    >>> np.arange(4)[0].sum()
    0
    >>> np.arange(4)[1:5].sum()
    6

    If the rightmost index is smaller than len(x)+1, then the remaining
    columns will not be included.

    >>> dia.combine_bins([0,1,3], np.arange(4))
    (array([0, 3]), array([1, 2]))
    é   TNFé   )	ÚnpZasarrayÚndimÚrangeÚlenÚappendÚsumÚcolumn_stackZsqueeze)	Z
edge_indexÚxZis_1dZxliZkliZbin_idxÚiÚjZx_new© r   úK/tmp/pip-unpacked-wheel-2v6byqio/statsmodels/discrete/_diagnostics_count.pyÚ_combine_bins   s    )

 
r   Ú	predictedc                 C   s`  t |tƒr|\}}n
d| }}|dkr>ddlm} |jdd}| d¡}|j| d|d |j|d	|d |dk	r|| d|¡ | ¡  | 	d
¡ | d¡}	|	jt
 | ¡d|d |	jt
 |¡d	|d |dk	rØ|	 d|¡ |	 ¡  |	 	d¡ | d¡}
|
 t
 |¡t
 | ¡d¡ |
 t
 t| ƒ¡t| ƒ t
 t| ƒ¡t| ƒ ¡ |
 	d¡ |
 |¡ |
 |¡ |S )a3  diagnostic plots for comparing two lists of discrete probabilities

    Parameters
    ----------
    freq, probs_predicted : nd_arrays
        two arrays of probabilities, this can be any probabilities for
        the same events, default is designed for comparing predicted
        and observed probabilities
    label : str or tuple
        If string, then it will be used as the label for probs_predicted and
        "freq" is used for the other probabilities.
        If label is a tuple of strings, then the first is they are used as
        label for both probabilities

    upp_xlim : None or int
        If it is not None, then the xlim of the first two plots are set to
        (0, upp_xlim), otherwise the matplotlib default is used
    fig : None or matplotlib figure instance
        If fig is provided, then the axes will be added to it in a (3,1)
        subplots, otherwise a matplotlib figure instance is created

    Returns
    -------
    Figure
        The figure contains 3 subplot with probabilities, cumulative
        probabilities and a PP-plot
    ÚfreqNr   )é   é   )Zfigsizei7  z-o)Úlabelz-dZprobabilitiesi8  zcumulative probabilitiesi9  ÚozPP-plot)Ú
isinstanceÚlistZmatplotlib.pyplotZpyplotÚfigureZadd_subplotZplotZset_xlimZlegendÚ	set_titler   ZcumsumÚaranger   Z
set_xlabelZ
set_ylabel)r   Zprobs_predictedr   Zupp_xlimZfigZlabel0Úlabel1ZpltZax1Zax2Zax3r   r   r   Ú
plot_probsN   s6    







0


r!   c                 C   s4  | }| j  | j¡}|j jdd…df t |jd ¡k t¡}|dk	rlt	||ƒ\}}t	||ƒ\}	}|	jd }n||jd  }}|}	||	 }
t 
||
dd…dd…f f¡}|jd }tt |¡|ƒ ¡ }|d|j|j   }|j j|jd  }||d k r
ddl}| d¡ |}tj ||¡}t||||
|dd}|S )u¾  
    chisquare test for predicted probabilities using cmt-opg

    Parameters
    ----------
    results : results instance
        Instance of a count regression results
    probs : ndarray
        Array of predicted probabilities with observations
        in rows and event counts in columns
    bin_edges : None or array
        intervals to combine several counts into cells
        see combine_bins

    Returns
    -------
    (api not stable, replace by test-results class)
    statistic : float
        chisquare statistic for tes
    p-value : float
        p-value of test
    df : int
        degrees of freedom for chisquare distribution
    extras : ???
        currently returns a tuple with some intermediate results
        (diff, res_aux)

    Notes
    -----

    Status : experimental, no verified unit tests, needs to be generalized
    currently only OPG version with auxiliary regression is implemented

    Assumes counts are np.arange(probs.shape[1]), i.e. consecutive
    integers starting at zero.

    Auxiliary regression drops the last column of binned probs to avoid
    that probabilities sum to 1.

    References
    ----------
    .. [1] Andrews, Donald W. K. 1988a. â€œChi-Square Diagnostic Tests for
           Econometric Models: Theory.â€ Econometrica 56 (6): 1419â€“53.
           https://doi.org/10.2307/1913105.

    .. [2] Andrews, Donald W. K. 1988b. â€œChi-Square Diagnostic Tests for
           Econometric Models.â€ Journal of Econometrics 37 (1): 135â€“56.
           https://doi.org/10.1016/0304-4076(88)90079-6.

    .. [3] ManjÃ³n, M., and O. MartÃ­nez. 2014. â€œThe Chi-Squared Goodness-of-Fit
           Test for Count-Data Models.â€ Stata Journal 14 (4): 798â€“816.
    Nr   éÿÿÿÿr   z!auxiliary model is rank deficientÚchi2)Ú	statisticÚpvalueÚdfÚdiff1Úres_auxÚdistribution)ÚmodelÚ	score_obsÚparamsÚendogr   r   ÚshapeÚastypeÚintr   r   r   ÚonesÚfitÚssrÚuncentered_tssZrankÚwarningsÚwarnr   r#   Úsfr   )ÚresultsZprobsZ	bin_edgesÚmethodÚresr+   Zd_indZ
d_ind_binsZk_binsZ
probs_binsr'   Zx_auxÚnobsr(   Z	chi2_statr&   r5   r$   r%   r   r   r   Útest_chisquare_prob   s:    5*

úr<   c                   @   s   e Zd Zdd„ ZdS )ÚDispersionResultsc                 C   s    t  | j| j| j| jdœ¡}|S )N)r$   r%   r9   Úalternative)ÚpdZ	DataFramer$   r%   r9   r>   )ÚselfÚframer   r   r   Úsummary_frameê   s    üzDispersionResults.summary_frameN)Ú__name__Ú
__module__Ú__qualname__rB   r   r   r   r   r=   è   s   r=   ÚallFc                 C   sš  |dkrt d|› dƒ‚t| dƒr(| j} | jj}|jd }|  ¡ }| jd }|| }|| }t 	d|d  
¡  ¡}	| 
¡ }
| 
¡ |	 }|
|	 }||  
¡ t 	d| ¡ }dtj t |¡¡ }dtj t |¡¡ }dtj t |¡¡ }||g||g||gg}ddgd	dgd
dgg}|| }t||ƒjdd}|jd }|jd }| ||g¡ | ddg¡ t||ƒjdd}|jd }|jd }| ||g¡ | ddg¡ || }t||ƒjddd}|jd }|jd }| ||g¡ | ddg¡ t|t t|ƒ¡ƒjddd}|jd }|jd }| ||g¡ | ddg¡ t |¡}|rT||fS t|dd…df |dd…df dd„ |D ƒdd„ |D ƒdd}|S dS )aå  Score/LM type tests for Poisson variance assumptions

    Null Hypothesis is

    H0: var(y) = E(y) and assuming E(y) is correctly specified
    H1: var(y) ~= E(y)

    The tests are based on the constrained model, i.e. the Poisson model.
    The tests differ in their assumed alternatives, and in their maintained
    assumptions.

    Parameters
    ----------
    results : Poisson results instance
        This can be a results instance for either a discrete Poisson or a GLM
        with family Poisson.
    method : str
        Not used yet. Currently results for all methods are returned.
    _old : bool
        Temporary keyword for backwards compatibility, will be removed
        in future version of statsmodels.

    Returns
    -------
    res : instance
        The instance of DispersionResults has the hypothesis test results,
        statistic, pvalue, method, alternative, as main attributes and a
        summary_frame method that returns the results as pandas DataFrame.

    )rF   zunknown method "ú"Ú_resultsr   r   zDean Azmu (1 + a mu)zDean BzDean Cz
mu (1 + a)F)Úuse_tzCT nb2zCT nb1ÚHC3)Úcov_typerI   z
CT nb2 HC3z
CT nb1 HC3Nr   c                 S   s   g | ]}|d  ‘qS )r   r   ©Ú.0r   r   r   r   Ú
<listcomp>Y  s     z+test_poisson_dispersion.<locals>.<listcomp>c                 S   s   g | ]}|d  ‘qS )r   r   rL   r   r   r   rN   Z  s     zPoisson Dispersion Test)r$   r%   r9   r>   Úname)Ú
ValueErrorÚhasattrrH   r*   r-   r.   ÚpredictÚresid_responser   Úsqrtr   r   Únormr7   Úabsr   r2   ZtvaluesZpvaluesr   r1   r   Úarrayr=   )r8   r9   Z_oldr-   r;   ÚfittedÚresid2Zvar_resid_endogZvar_resid_fittedZstd1Zvar_resid_endog_sumZdean_aZdean_bZdean_cZpval_dean_aZpval_dean_bZpval_dean_cZresults_allÚdescriptionÚendog_vZres_ols_nb2Zstat_ols_nb2Zpval_ols_nb2Zres_ols_nb1Zstat_ols_nb1Zpval_ols_nb1Zstat_ols_hc1_nb2Zpval_ols_hc1_nb2Zstat_ols_hc1_nb1Zpval_ols_hc1_nb1r:   r   r   r   Útest_poisson_dispersionõ   sz     


þþ





ÿ


ûr\   TrJ   c                 C   s:  t | dƒr| j} | jj}|jd }	|  ¡ }
| jd }|rB|| }n||
 }||
 }|jd }|g}|r~| j | j¡}| 	|¡ |dk	r| 	|¡ t
|ƒdkr¬t |¡}d}n|d }d}t||ƒj|||d}|r|jd }t ||¡}| |¡}|j}|j}n0|jd }	d|j|j  }|	| }tj ||¡}||fS )	at  A variable addition test for the variance function

    This uses an artificial regression to calculate a variant of an LM or
    generalized score test for the specification of the variance assumption
    in a Poisson model. The performed test is a Wald test on the coefficients
    of the `exog_new_test`.

    Warning: insufficiently tested, especially for options
    rH   r   r   r   NTF)rK   Úcov_kwdsrI   )rQ   rH   r*   r-   r.   rR   rS   r+   r,   r   r   r   r   r   r2   ZeyeZ	wald_testr$   r%   r3   r4   r   r#   r7   )r8   Zexog_new_testZexog_new_controlZinclude_scoreZ	use_endogrK   r]   rI   r-   r;   rX   rY   Z	var_residr[   Zk_constraintsZex_listr+   ÚexZuse_waldZres_olsZk_varsÚconstraintsZhtZstat_olsZpval_olsZrsquared_noncenteredr   r   r   Ú _test_poisson_dispersion_generic`  sH    







ÿ


r`   c                 C   s0  t | jtƒsddl}| d¡ | jjjd }|dkrBt |df¡}| jj}| jj	}|  
¡ }t | ¡}|  ¡ }|j|   |¡j}	|jd| |   |¡}
||dk| | dd…df  }| d¡}|
|	j |¡ |	¡ }tj |¡}| |¡ |¡}tj |¡}|jd }tj ||¡}t||||dd}|S )u  score test for zero inflation or deflation in Poisson

    This implements Jansakul and Hinde 2009 score test
    for excess zeros against a zero modified Poisson
    alternative. They use a linear link function for the
    inflation model to allow for zero deflation.

    Parameters
    ----------
    results_poisson: results instance
        The test is only valid if the results instance is a Poisson
        model.
    exog_infl : ndarray
        Explanatory variables for the zero inflated or zero modified
        alternative. I exog_infl is None, then the inflation
        probability is assumed to be constant.

    Returns
    -------
    score test results based on chisquare distribution

    Notes
    -----
    This is a score test based on the null hypothesis that
    the true model is Poisson. It will also reject for
    other deviations from a Poisson model if those affect
    the zero probabilities, e.g. in the direction of
    excess dispersion as in the Negative Binomial
    or Generalized Poisson model.
    Therefore, rejection in this test does not imply that
    zero-inflated Poisson is the appropriate model.

    Status: experimental, no verified unit tests,

    TODO: If the zero modification probability is assumed
    to be constant under the alternative, then we only have
    a scalar test score and we can use one-sided tests to
    distinguish zero inflation and deflation from the
    two-sided deviations. (The general one-sided case is
    difficult.)
    In this case the test specializes to the test by Broek

    References
    ----------
    .. [1] Jansakul, N., and J. P. Hinde. 2002. â€œScore Tests for Zero-Inflated
           Poisson Models.â€ Computational Statistics & Data Analysis 40 (1):
           75â€“96. https://doi.org/10.1016/S0167-9473(01)00104-9.
    r   Nz&Test is only valid if model is Poissonr   r#   )r$   r%   r&   Z
rank_scorer)   )r   r*   r   r5   r6   r-   r.   r   r1   ÚexogrR   ÚexpZ
cov_paramsÚTÚdotr   ÚlinalgZpinvZmatrix_rankr   r#   r7   r   )Úresults_poissonZ	exog_inflr5   r;   r-   ra   ÚmuÚ	prob_zeroZcov_poiZcross_derivativeZcov_inflZscore_obs_inflZ
score_inflZcov_score_inflZcov_score_infl_invr$   Zdf2r&   r%   r:   r   r   r   Útest_poisson_zeroinflation_jh¨  s:    1
 

ûri   c              
   C   s²   |   ¡ }t | ¡}| jj}|dk| |  ¡ }d| |  ¡ | ¡  }|t |¡ }dtj 	t 
|¡¡ }tj 	|¡}tj |¡}	t||||	|d tj 	|d d¡ddd}
|
S )u`  score test for zero modification in Poisson, special case

    This assumes that the Poisson model has a constant and that
    the zero modification probability is constant.

    This is a special case of test_poisson_zeroinflation derived by
    van den Broek 1995.

    The test reports two sided and one sided alternatives based on
    the normal distribution of the test statistic.

    References
    ----------
    .. [1] Broek, Jan van den. 1995. â€œA Score Test for Zero Inflation in a
           Poisson Distribution.â€ Biometrics 51 (2): 738â€“43.
           https://doi.org/10.2307/2532959.

    r   r   r   Únormal©r$   r%   Zpvalue_smallerZpvalue_largerr#   Zpvalue_chi2Zdf_chi2r)   )rR   r   rb   r*   r-   r   rT   r   rU   r7   rV   Úcdfr   r#   )rf   rg   rh   r-   ZscoreZ	var_scorer$   Ú
pvalue_twoÚ
pvalue_uppÚ
pvalue_lowr:   r   r   r   Ú test_poisson_zeroinflation_broek  s(    ø
rp   c              
   C   sî   | j j}|  ¡ }t | ¡}| j jdk t¡}| ¡ | ¡  }|d|  }|| }tj	 
|j| | ¡}|| }	|	| |	 }
||
 }|t |¡ }dtj t |¡¡ }tj |¡}tj |¡}t|||||d tj |d d¡ddd}|S )u´  Test for excess zeros in Poisson regression model.

    The test is implemented following Tang and Tang [1]_ equ. (12) which is
    based on the test derived in He et al 2019 [2]_.

    References
    ----------

    .. [1] Tang, Yi, and Wan Tang. 2018. â€œTesting Modified Zeros for Poisson
           Regression Models:â€ Statistical Methods in Medical Research,
           September. https://doi.org/10.1177/0962280218796253.

    .. [2] He, Hua, Hui Zhang, Peng Ye, and Wan Tang. 2019. â€œA Test of Inflated
           Zeros for Poisson Regression Models.â€ Statistical Methods in
           Medical Research 28 (4): 1157â€“69.
           https://doi.org/10.1177/0962280217749991.

    r   r   r   rj   rk   )r*   ra   rR   r   rb   r-   r/   r0   r   re   Úinvrc   rT   r   rU   r7   rV   rl   r   r#   )r8   r   ZmeanZprob0ÚcountsZdiffZvar1ZpmÚcZpmxZvar2Úvarr$   rm   rn   ro   r:   r   r   r   Útest_poisson_zeros0  s4    ø
ru   )r   NN)NN)rF   F)NFTrJ   NF)N)Ú__doc__Znumpyr   Zscipyr   Zpandasr?   Zstatsmodels.stats.baser   Z#statsmodels.discrete.discrete_modelr   Z#statsmodels.regression.linear_modelr   r   r!   r<   r=   r\   r`   ri   rp   ru   r   r   r   r   Ú<module>   s.   <  ÿ
?
[
n      ø
H
Z.