
p7]c           @   s  d  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 l m Z d d l m Z d d	 l m Z d
 d e e e d  Z d d  Z d   Z d e f d     YZ d e f d     YZ d e f d     YZ d d  Z d e f d     YZ d S(   sk   Influence and Outlier Measures

Created on Sun Jan 29 11:16:09 2012

Author: Josef Perktold
License: BSD-3
i(   t   defaultdictN(   t   lzip(   t   _plot_influence_doc(   t   OLS(   t   multipletests(   t   cache_readonly(   t   maybe_unwrap_resultst   bonfg?c         C   s  d d l  m } | d k r7 t |  j j d d  } n  t |  d d  } | d k rz t |   } t d | j j	   n  |   j
 }	 | r t j |	  j   d d d  }
 |	 |
 }	 | d k	 r t j |  |
 } q n  |  j d } | j j t j |	  |  d } t | d	 | d
 | } t j |	 | | d f } | d k	 rs| d d  d f | k  } | | } n t d  } | d k	 rd d l m } | | d d d | d g d t j |  | S| S(   sU  
    Outlier Tests for RegressionResults instances.

    Parameters
    ----------
    model_results : RegressionResults
        Linear model results
    method : str
        - `bonferroni` : one-step correction
        - `sidak` : one-step correction
        - `holm-sidak` :
        - `holm` :
        - `simes-hochberg` :
        - `hommel` :
        - `fdr_bh` : Benjamini/Hochberg
        - `fdr_by` : Benjamini/Yekutieli
        See `statsmodels.stats.multitest.multipletests` for details.
    alpha : float
        familywise error rate
    labels : None or array_like
        If `labels` is not None, then it will be used as index to the
        returned pandas DataFrame. See also Returns below
    order : bool
        Whether or not to order the results by the absolute value of the
        studentized residuals. If labels are provided they will also be sorted.
    cutoff : None or float in [0, 1]
        If cutoff is not None, then the return only includes observations with
        multiple testing corrected p-values strictly below the cutoff. The
        returned array or dataframe can be empty if there are no outlier
        candidates at the specified cutoff.

    Returns
    -------
    table : ndarray or DataFrame
        Returns either an ndarray or a DataFrame if labels is not None.
        Will attempt to get labels from model_results if available. The
        columns are the Studentized residuals, the unadjusted p-value,
        and the corrected p-value according to method.

    Notes
    -----
    The unadjusted p-value is stats.t.sf(abs(resid), df) where
    df = df_resid - 1.
    i(   t   statst
   row_labelst   get_influences=   model_results object %s does not have a get_influence method.Ni   i   t   alphat   method(   t	   DataFramet   columnst   student_residt   unadj_ps   (p)t   index(   t   scipyR   t   Nonet   getattrt   modelt   dataR   t   AttributeErrort	   __class__t   __name__t   resid_studentized_externalt   npt   abst   argsortt   asarrayt   df_residt   tt   sfR   t   c_t   slicet   pandasR   (   t   model_resultsR   R   t   labelst   ordert   cutoffR   t   inflt   resultst   residt   idxt   dfR   t   adj_pR   t   maskR   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   outlier_test   s8    ."
"	i   c         C   s   | d } |  j  j j d } t j |  j |  d d  d d  f } t j |  j  j | f  } t |  j  j |  j	   } t j
 | d | j d |  } | j |  S(   s  Ramsey's RESET specification test for linear models

    This is a general specification test, for additional non-linear effects
    in a model.


    Notes
    -----
    The test fits an auxiliary OLS regression where the design matrix, exog,
    is augmented by powers 2 to degree of the fitted values. Then it performs
    an F-test whether these additional terms are significant.

    If the p-value of the f-test is below a threshold, e.g. 0.1, then this
    indicates that there might be additional non-linear effects in the model
    and that the linear model is mis-specified.


    References
    ----------
    http://en.wikipedia.org/wiki/Ramsey_RESET_test

    i   Ni(   R   t   exogt   shapeR   t   vandert   fittedvaluest   column_stackR   t   endogt   fitt   eyet   f_test(   t   rest   degreeR'   t   k_varst   y_fitted_vanderR1   t   res_auxt   r_matrix(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   reset_ramseyi   s    
+ c         C   sx   |  j  d } |  d d  | f } t j |  | k } |  d d  | f } t | |  j   j } d d | } | S(   s~  variance inflation factor, VIF, for one exogenous variable

    The variance inflation factor is a measure for the increase of the
    variance of the parameter estimates if an additional variable, given by
    exog_idx is added to the linear regression. It is a measure for
    multicollinearity of the design matrix, exog.

    One recommendation is that if VIF is greater than 5, then the explanatory
    variable given by exog_idx is highly collinear with the other explanatory
    variables, and the parameter estimates will have large standard errors
    because of this.

    Parameters
    ----------
    exog : ndarray
        design matrix with all explanatory variables, as for example used in
        regression
    exog_idx : int
        index of the exogenous variable in the columns of exog

    Returns
    -------
    vif : float
        variance inflation factor

    Notes
    -----
    This function does not save the auxiliary regression.

    See Also
    --------
    xxx : class for regression diagnostics  TODO: doesn't exist yet

    References
    ----------
    http://en.wikipedia.org/wiki/Variance_inflation_factor

    i   Ng      ?(   R2   R   t   arangeR   R7   t   rsquared(   R1   t   exog_idxR<   t   x_iR/   t   x_notit   r_squared_it   vif(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   variance_inflation_factor   s    't   _BaseInfluenceMixinc           B   sl   e  Z d  Z d
 d d d d d
 d  Z e j i d d 6 e _ d
 d
 d
 d  Z d d
 d
 d
 d
 d	  Z RS(   s=   common methods between OLSInfluence and MLE/GLMInfluence
    g?t   cooksi0   g      ?c   
      K   sz   | d  k r- t |  d  o' d |  j k } n  d d l m } | |  j |  d | d | d | d | d	 | d
 | | }	 |	 S(   Nt   _cachet   res_loooi(   t   _influence_plott   externalR   t	   criteriont   sizet
   plot_alphat   ax(   R   t   hasattrRK   t$   statsmodels.graphics.regressionplotsRM   R*   (
   t   selfRN   R   RO   RP   RQ   RR   t   kwargsRM   R:   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   plot_influence   s    !t    t   extra_params_docc         K   sm  d d l  m } | j |  \ } } | d  k r: d } n  t |  j  }	 t j |	  }
 | j |
 | |  | d k r t j	 |	 t j
  } n t j |  | k } d t j	 |	  } |  j j j j } | d  k r t j |	  } n  | j t j |  d | t |
 |  t | |  d |  } i d d	 6d
 d 6} | j | |  | j d |  | j | |  | S(   Ni(   t   utilss
   Index Plott   alli   i    t   largei   t   fontsizet   blackt   colort   Observation(   t   statsmodels.graphicsRZ   t   create_mpl_axR   t   lenR6   R   RA   t   scattert   onest   bool_R   R*   R   R   R	   t   annotate_axest   whereR   t
   set_ylabelt
   set_xlabelt	   set_title(   RU   t   yt   ylabelt	   thresholdt   titleRR   t   kwdsRZ   t   figt   nobsR   t   large_pointst   psizeR&   t   font(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   _plot_index   s.    		c      
   K   sN  | } | d k r d } n  | d k rZ |  j d d  | f } d |  j j j | }	 n | j d  r |  j d } d }	 n | j d  s | j d	  r |  j } d
 }	 nt | j d  r |  j d } d }	 nO | j d  r |  j } d }	 n. t	 |  |  } | d k	 r| | } n  | }	 |  j
 | |	 d | d | d | | }
 |
 S(   s9  index plot for influence attributes

        Parameters
        ----------
        y_var : string
            Name of attribute or shortcut for predefined attributes that will
            be plotted on the y-axis.
        threshold : None or float
            Threshold for adding annotation with observation labels.
            Observations for which the absolute value of the y_var is larger
            than the threshold will be annotated. Set to a negative number to
            label all observations or to a large number to have no annotation.
        title : string
            If provided, the title will replace the default "Index Plot" title.
        ax : matplolib axis instance
            The plot will be added to the `ax` if provided, otherwise a new
            figure is created.
        idx : None or integer
            Some attributes require an additional index to select the y-var.
            In dfbetas this refers to the column indes.
        kwds : optional keywords
            Keywords will be used in the call to matplotlib scatter function.

        R[   t   dfbetaNs   DFBETA for t   cooki    s   Cook's distancet   hatt   levers!   Leverage (diagonal of hat matrix)R+   s    Internally Studentized ResidualsRn   Ro   RR   (   R   t   dfbetasR*   R   t
   exog_namest
   startswitht   cooks_distancet   hat_matrix_diagt   resid_studentizedR   Rv   (   RU   t   y_varRn   Ro   RR   R,   Rp   RO   Rl   Rm   Rq   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt
   plot_index   s2    							N(	   R   t
   __module__t   __doc__R   RW   R   t   formatRv   R   (    (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyRI      s   		t   MLEInfluencec           B   s   e  Z d  Z d d d d d d d  Z e d    Z e d    Z e d    Z e d    Z	 e d    Z
 e d    Z e d    Z e d	    Z e d
    Z d   Z RS(   s:
  Local Influence and outlier measures (experimental)

    This currently subclasses GLMInfluence instead of the other way.
    No common superclass yet.
    This is another version before checking what is common

    Parameters
    ----------
    results : instance of results class
        This only works for model and results classes that have the necessary
        helper methods.
    other arguments are only to override default behavior and are used instead
    of the corresponding attribute of the results class.
    By default resid_pearson is used as resid.




    Attributes
    ----------
    hat_matrix_diag (hii) : This is the generalized leverage computed as the
        local derivative of fittedvalues (predicted mean) with respect to the
        observed response for each observation.
    d_params : Change in parameters computed with one Newton step using the
        full Hessian corrected by division by (1 - hii).
    dbetas : change in parameters divided by the standard error of parameters
        from the full model results, ``bse``.
    cooks_distance : quadratic form for change in parameters weighted by
        ``cov_params`` from the full model divided by the number of variables.
        It includes p-values based on the F-distribution which are only
        approximate outside of linear Gaussian models.
    resid_studentized : In the general MLE case resid_studentized are
        computed from the score residuals scaled by hessian factor and
        leverage. This does not use ``cov_params``.
    d_fittedvalues : local change of expected mean given the change in the
        parameters as computed in ``d_params``.
    d_fittedvalues_scaled : same as d_fittedvalues but scaled by the standard
        errors of a predicted mean of the response.
    params_one : is the one step parameter estimate computed as ``params``
        from the full sample minus ``d_params``.

    Notes
    -----
    MLEInfluence produces the same results as GLMInfluence (verified for GLM
    Binomial and Gaussian). There will be some differences for non-canonical
    links or if a robust cov_type is used.

    Warning: This does currently not work for constrained or penalized models,
    e.g. models estimated with fit_constrained or fit_regularized.

    This has not yet been tested for correctness when offset or exposure
    are used, although they should be supported by the code.

    status: experimental,
    This class will need changes to support different kinds of models, e.g.
    extra parameters in discrete.NegativeBinomial or two-part models like
    ZeroInflatedPoisson.


    c         C   s4  t  |  |  _ } | j j j \ |  _ |  _ | d  k	 r@ | n	 | j j |  _ | d  k	 ra | n	 | j j |  _ | d  k	 r | n | j	 |  _
 | d  k	 r | n | j |  _ | d  k	 r | n	 | j   |  _ | j j |  _ |  j j j |  j j  |  _ |  j j j |  j j  |  _ | d  k	 r0| |  _ n  d  S(   N(   R   R*   R   R1   R2   Rr   R<   R   R6   t   resid_pearsonR+   t   scalet
   cov_paramsR   t   model_classt   hessiant   paramst	   score_obst   _hat_matrix_diag(   RU   R*   R+   R6   R1   R   R   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   __init__f  s    !!c         C   s|   t  |  d  r |  j S|  j j j |  j j  } |  j j j |  j j  } | t j j	 |  j
 | j  j j d  } | S(   sx   Diagonal of the generalized leverage

        This is the analogue of the hat matrix diagonal for general MLE.

        R   i   (   RS   R   R*   R   t   _deriv_mean_dparamsR   t   _deriv_score_obs_dendogR   t   linalgt   solveR   t   Tt   sum(   RU   t   dmu_dpt   dsdyt   h(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR   z  s    ,c         C   sV   |  j  j d  |  j  } t j j |  j | j  j } | d |  j d d  d f S(   s   Change in parameter estimates

        This uses one-step approximation of the parameter change to deleting
        one observation.
        i    i   N(	   R   R   R   R   R   R   R   R   R   (   RU   t   so_notit   beta_i(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   d_params  s    c         C   s   |  j  |  j j } | S(   s   Scaled change in parameter estimates

        The one-step change of parameters in d_params is rescaled by dividing
        by the standard error of the parameter estimate given by results.bse.
        (   R   R*   t   bse(   RU   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR{     s    c         C   s   |  j  j |  j S(   s   Parameter estimate based on one-step approximation

        This the one step parameter estimate computed as
        ``params`` from the full sample minus ``d_params``.
        (   R*   R   R   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt
   params_one  s    c         C   sy   |  j  t j j |  j |  j  j  j j d  } | |  j :} d d l m	 } | j
 j | |  j |  j j  } | | f S(   s  Cook's distance and p-values

        Based on one step approximation d_params and on results.cov_params
        Cook's distance divides by the number of explanatory variables.

        p-values are based on the F-distribution which are only approximate
        outside of linear Gaussian models.

        Warning: The definition of p-values might change if we switch to using
        chi-square distribution instead of F-distribution, or if we make it
        dependent on the fit keyword use_t.

        i   i(   R   (   R   R   R   R   R   R   R   R<   R   R   t   fR!   R*   R   (   RU   t   cooks_d2R   t   pvals(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR~     s    !c         C   s[   |  j  j j |  j  j  } |  j  j j |  j  j  } | t j |  t j d |  j  S(   s   Score residual divided by sqrt of hessian factor

        experimental, agrees with GLMInfluence for Binomial and Gaussian.
        no reference for this
        i   (   R*   R   t   score_factorR   t   hessian_factorR   t   sqrtR   (   RU   R!   t   hf(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    c         C   s   |  j  j   S(   N(   R*   t   get_prediction(   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   _get_prediction  s    c         C   s>   t  j |  j j  } |  j j j |  } | |  j j d  S(   s-  Change in expected response, fittedvalues

        Local change of expected mean given the change in the parameters as
        computed in d_params.

        Notes
        -----
        This uses one-step approximation of the parameter change to deleting
        one observation ``d_params``.
        i   (   R   R   R*   R   R   R   R   R   (   RU   R   t   deriv(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   d_fittedvalues  s    c         C   s   |  j  |  j j S(   s  
        Change in fittedvalues scaled by standard errors

        This uses one-step approximation of the parameter change to deleting
        one observation ``d_params``, and divides by the standard errors
        for the predicted mean provided by results.get_prediction.
        (   R   R   t   se_mean(   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   d_fittedvalues_scaled  s    c      
   C   s   d d l  m } |  j j j } | j } g  | j D] } d | ^ q2 } | t d |  j d d |  j	 d |  j
 d |  j  d	 | } | |  j d
 | d	 | } | j |  S(   s  
        Creates a DataFrame with influence results.

        Returns
        -------
        frame : pandas DataFrame
            A DataFrame with selected results for each observation.
            The index will be the same as provided to the model.

        Notes
        -----
        The resultant DataFrame contains six variables in addition to the
        ``dfbetas``. These are:

        * cooks_d : Cook's Distance defined in ``cooks_distance``
        * standard_resid : Standardized residuals defined in
          `resid_studentizedl`
        * hat_diag : The diagonal of the projection, or hat, matrix defined in
          `hat_matrix_diag`
        * dffits_internal : DFFITS statistics using internally Studentized
          residuals defined in `d_fittedvalues_scaled`

        i(   R   t   dfb_t   cooks_di    t   standard_residt   hat_diagt   dffits_internalR   R   (   R$   R   R*   R   R   R	   t   xnamest   dictR~   R   R   R   R{   t   join(   RU   R   R   R	   t   it   beta_labelst   summary_dataRw   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   summary_frame  s    	 					N(   R   R   R   R   R   R   R   R   R{   R   R~   R   R   R   t   propertyR   R   (    (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR   (  s   <		t   OLSInfluencec           B   s|  e  Z d  Z d   Z e d    Z e d    Z e d    Z e d    Z e d    Z	 e d    Z
 e d    Z e d	    Z d d
  Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z d e d  Z d   Z e d    Z d   Z d d  Z  RS(   s\  class to calculate outlier and influence measures for OLS result

    Parameters
    ----------
    results : RegressionResults
        currently assumes the results are from an OLS regression

    Notes
    -----
    One part of the results can be calculated without any auxiliary regression
    (some of which have the `_internal` postfix in the name. Other statistics
    require leave-one-observation-out (LOOO) auxiliary regression, and will be
    slower (mainly results with `_external` postfix in the name).
    The auxiliary LOOO regression only the required results are stored.

    Using the LOO measures is currently only recommended if the data set
    is not too large. One possible approach for LOOO measures would be to
    identify possible problem observations with the _internal measures, and
    then run the leave-one-observation-out only with observations that are
    possible outliers. (However, this is not yet available in an automized way.)

    This should be extended to general least squares.

    The leave-one-variable-out (LOVO) auxiliary regression are currently not
    used.

    c         C   s   t  |  |  _ | j j j \ |  _ |  _ | j j |  _ | j j |  _ | j |  _ | j j	 |  _
 | j |  _ i  |  _ i  |  _ d  S(   N(   R   R*   R   R1   R2   Rr   R<   R6   R+   R   R   t	   mse_residR   t   aux_regression_exogt   aux_regression_endog(   RU   R*   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR   >  s    	c         C   s    |  j  |  j j j j j d  S(   s   Diagonal of the hat_matrix for OLS

        Notes
        -----
        temporarily calculated here, this should go to model class
        i   (   R1   R*   R   t
   pinv_wexogR   R   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR   M  s    c         C   s   |  j  } |  j d | S(   s   PRESS residuals
        i   (   R   R+   (   RU   t   hii(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   resid_pressW  s    	c         C   s   |  j  } |  j | d | S(   s   Influence measure

        matches the influence measure that gretl reports
        u * h / (1 - h)
        where u are the residuals and h is the diagonal of the hat_matrix
        i   (   R   R+   (   RU   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt	   influence^  s    	c         C   s   |  j  } | d | S(   s   Factor of diagonal of hat_matrix used in influence

        this might be useful for internal reuse
        h / (1 - h)
        i   (   R   (   RU   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   hat_diag_factori  s    	c         C   s   t  j |  j |  j  S(   s0   Error sum of squares of PRESS residuals
        (   R   t   dotR   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt	   ess_presss  s    c         C   s   |  j  S(   s   Studentized residuals using variance from OLS

        alias for resid_studentized_internal for compatibility with
        MLEInfluence this uses sigma from original estimate and does
        not require leave one out loop
        (   t   resid_studentized_internal(   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR   y  s    c         C   s   |  j  d d  S(   s   Studentized residuals using variance from OLS

        this uses sigma from original estimate
        does not require leave one out loop
        t   sigmaN(   t   get_resid_studentized_externalR   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    c         C   s"   t  j |  j  } |  j d |  S(   s   Studentized residuals using LOOO variance

        this uses sigma from leave-one-out estimates

        requires leave one out loop for observations
        R   (   R   R   t   sigma2_not_obsiR   (   RU   t
   sigma_looo(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    c         C   sL   |  j  } | d k r0 |  j } t j |  } n  |  j | t j d |  S(   s  calculate studentized residuals

        Parameters
        ----------
        sigma : None or float
            estimate of the standard deviation of the residuals. If None, then
            the estimate from the regression results is used.

        Returns
        -------
        stzd_resid : ndarray
            studentized residuals

        Notes
        -----
        studentized residuals are defined as ::

           resid / sigma / np.sqrt(1 - hii)

        where resid are the residuals from the regression, sigma is an
        estimate of the standard deviation of the residuals, and hii is the
        diagonal of the hat_matrix.

        i   N(   R   R   R   R   R   R+   (   RU   R   R   t
   sigma2_est(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s
    		c         C   sj   |  j  } |  j d |  j } | | d | 9} d d l m } | j j | |  j |  j j  } | | f S(   sE   Cooks distance

        uses original results, no nobs loop

        i   i   i(   R   (	   R   R   R<   R   R   R   R!   R*   R   (   RU   R   R   R   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR~     s    	!c         C   sR   |  j  } |  j t j | d |  } d t j |  j d |  j  } | | f S(   s   dffits measure for influence of an observation

        based on resid_studentized_internal
        uses original results, no nobs loop

        i   i   g      ?(   R   R   R   R   R<   Rr   (   RU   R   t   dffits_t   dffits_threshold(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    	!c         C   sR   |  j  } |  j t j | d |  } d t j |  j d |  j  } | | f S(   s  dffits measure for influence of an observation

        based on resid_studentized_external,
        uses results from leave-one-observation-out loop

        It is recommended that observations with dffits large than a
        threshold of 2 sqrt{k / n} where k is the number of parameters, should
        be investigated.

        Returns
        -------
        dffits: float
        dffits_threshold : float

        References
        ----------
        `Wikipedia <http://en.wikipedia.org/wiki/DFFITS>`_

        i   i   g      ?(   R   R   R   R   R<   Rr   (   RU   R   R   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   dffits  s    	!c         C   s_   |  j  j |  j } | t j |  j d d  d f  :} | t j t j |  j  j   :} | S(   sJ   dfbetas

        uses results from leave-one-observation-out loop
        N(	   R*   R   t   params_not_obsiR   R   R   R   t   diagt   normalized_cov_params(   RU   R{   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR{     s    &"c         C   s   |  j  j |  j } | S(   sJ   dfbetas

        uses results from leave-one-observation-out loop
        (   R*   R   R   (   RU   Rw   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyRw     s    c         C   s   t  j |  j d  S(   s   error variance for all LOOO regressions

        This is 'mse_resid' from each auxiliary regression.

        uses results from leave-one-observation-out loop
        R   (   R   R   t	   _res_looo(   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    c         C   s   t  j |  j d  S(   so   parameter estimates for all LOOO regressions

        uses results from leave-one-observation-out loop
        R   (   R   R   R   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    c         C   s   t  j |  j d  S(   st   determinant of cov_params of all LOOO regressions

        uses results from leave-one-observation-out loop
        t   det_cov_params(   R   R   R   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   det_cov_params_not_obsi   s    c         C   s&   |  j  t j j |  j j    } | S(   s   covariance ratio between LOOO and original

        This uses determinant of the estimate of the parameter covariance
        from leave-one-out estimates.
        requires leave one out loop for observations

        (   R   R   R   t   detR*   R   (   RU   t	   cov_ratio(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR   (  s    
c         C   s   |  j  d |  j S(   s   estimate of variance of the residuals

        ::

           sigma2 = sigma2_OLS * (1 - hii)

        where hii is the diagonal of the hat matrix

        i   (   R   R   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt	   resid_var6  s    c         C   s   t  j |  j  S(   sn   estimate of standard deviation of the residuals

        See Also
        --------
        resid_var

        (   R   R   R   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt	   resid_stdD  s    	R6   c   
      C   s   | d k r> |  j  } t | |  r, | | S|  j j j } nS y |  j | | Wn t k
 rd n X|  j | } i  } |  j d d  | f } |  j j d } t	 j
 |  | k } |  j d d  | f } t | |  j   }	 | r |	 | | <n  |	 S(   s  regression results from LOVO auxiliary regression with cache


        The result instances are stored, which could use a large amount of
        memory if the datasets are large. There are too many combinations to
        store them all, except for small problems.

        Parameters
        ----------
        drop_idx : int
            index of exog that is dropped from the regression
        endog_idx : 'endog' or int
            If 'endog', then the endogenous variable of the result instance
            is regressed on the exogenous variables, excluding the one at
            drop_idx. If endog_idx is an integer, then the exog with that
            index is regressed with OLS on all other exogenous variables.
            (The latter is the auxiliary regression for the variance inflation
            factor.)

        this needs more thought, memory versus speed
        not yet used in any other parts, not sufficiently tested
        R6   Ni   (   R   RS   R*   R   R6   R   t   KeyErrorR1   R2   R   RA   R   R7   (
   RU   t   drop_idxt	   endog_idxt   storet   storedRD   R<   R/   RE   R:   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt
   _ols_xnotiO  s&    	c         C   s   d d l  m } |  j j j } |  j } | |  j  } t t  } xg | D]_ \ } } xP | D]H }	 |  j	 | | d d  | f  j
   }
 | |	 j t |
 |	   q] WqJ W| S(   s  
        regress endog on exog without one of the variables

        This uses a k_vars loop, only attributes of the OLS instance are
        stored.

        Parameters
        ----------
        attributes : list of strings
           These are the names of the attributes of the auxiliary OLS results
           instance that are stored and returned.

        not yet used
        i(   t   LeaveOneOutN(   t#   statsmodels.sandbox.tools.cross_valR   R*   R   R6   R1   R<   R    t   listR   R7   t   appendR   (   RU   t
   attributesR   R6   R1   t   cv_itert   res_loot   inidxt   outidxt   attt   res_i(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   _get_drop_vari  s    	("c         C   s  d d l  m } d   } |  j j j } |  j j j } t j | j d t j	 } t j | j d t j	 } t j | j d t j	 } | |  j
  } x^ | D]V \ }	 }
 |  j | |	 | |	  j   } | j | |
 <| j | |
 <| |  | |
 <q Wt d | d | d |  S(   s9  collect required results from the LOOO loop

        all results will be attached.
        currently only 'params', 'mse_resid', 'det_cov_params' are stored

        regresses endog on exog dropping one observation at a time

        this uses a nobs loop, only attributes of the OLS instance are stored.
        i(   R   c         S   s   t  j j |  j    S(   N(   R   R   R   R   (   R:   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   get_det_cov_params  s    t   dtypeR   R   R   (   R   R   R*   R   R6   R1   R   t   zerosR2   t   floatRr   R   R7   R   R   R   (   RU   R   R   R6   R1   R   R   R   R   R   R   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    	 c         C   s   d d l  m } |  j j j } | j } g  | j D] } d | ^ q2 } | t d |  j d d |  j	 d |  j
 d |  j d d	 |  j d
 |  j d  d | } | |  j d | d | } | j |  S(   s  
        Creates a DataFrame with all available influence results.

        Returns
        -------
        frame : DataFrame
            A DataFrame with all results.

        Notes
        -----
        The resultant DataFrame contains six variables in addition to the
        DFBETAS. These are:

        * cooks_d : Cook's Distance defined in `Influence.cooks_distance`
        * standard_resid : Standardized residuals defined in
          `Influence.resid_studentized_internal`
        * hat_diag : The diagonal of the projection, or hat, matrix defined in
          `Influence.hat_matrix_diag`
        * dffits_internal : DFFITS statistics using internally Studentized
          residuals defined in `Influence.dffits_internal`
        * dffits : DFFITS statistics using externally Studentized residuals
          defined in `Influence.dffits`
        * student_resid : Externally Studentized residuals defined in
          `Influence.resid_studentized_external`
        i(   R   R   R   i    R   R   R   R   R   R   R   (   R$   R   R*   R   R   R	   R   R   R~   R   R   R   R   R   R{   R   (   RU   R   R   R	   R   R   R   Rw   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    	 						s   %6.3fc         C   sA  d t  j |  j  f d |  j f d |  j j f d |  j d f d |  j f d |  j f d |  j	 d f d	 |  j
 f d
 |  j d f g	 } t |   \ } } t  j |  } | |  _ d d l m } m } d d l m } d d l m } | |  }	 | |  }
 d g | g | j d d |	 d <| | d | d |	 d |
 S(   s  create a summary table with all influence and outlier measures

        This does currently not distinguish between statistics that can be
        calculated from the original regression results and for which a
        leave-one-observation-out loop is needed

        Returns
        -------
        res : SimpleTable
           SimpleTable instance with the results, can be printed

        Notes
        -----
        This also attaches table_data to the instance.



        t   obsR6   s   fitted
values   Cook's
di    s   student.
residuals   hat diags   dffits 
internals   ext.stud.
residualR   i(   t   SimpleTablet   default_html_fmt(   t   fmt_base(   t   deepcopys   %4di   t	   data_fmtst   headerst   txt_fmtt   html_fmt(   R   RA   Rr   R6   R*   R4   R~   R   R   R   R   R   R   R5   t
   table_datat   statsmodels.iolib.tableR   R   t!   statsmodels.iolib.tableformattingR   t   copyR   R2   (   RU   t	   float_fmtt	   table_rawt   colnamesR   R   R   R   R   t   fmtt   fmt_html(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   summary_table  s(     	#N(!   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R~   R   R   R{   Rw   R   R   R   R   R   R   R   t   TrueR   R   R   R   R   (    (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR   !  s6   	



"	
4	!	1c         C   sJ  d d l  m } d d l m } t |   } t j | j |  j  } | j	 j
 | d |  j  } t j |  j | | |  j | | g  } | |  d | } | \ }	 }
 } t j |
 | f  } t j |  j d | j  } t j t j |  j  d |  j j |  j | | d d  d f | d d  d f | d d  d f | d d  d f |  j | | j | j d g  } | } d	 d
 d d d d d d d d d d g } | } d d l m } m } d d l m } d d l m } | |  } | |  } d g d g | j d d | d <| | d | d | d | } | | | f S(   s  
    Generate summary table of outlier and influence similar to SAS

    Parameters
    ----------
    alpha : float
       significance level for confidence interval

    Returns
    -------
    st : SimpleTable
       table with results that can be printed
    data : ndarray
       calculated measures and statistics for the table
    ss2 : list of strings
       column_names for table (Note: rows of table are observations)
    i(   R   (   t   wls_prediction_stdg       @R   i   Ni    t   Obss   Dep Var
Populations   Predicted
Values   Std Error
Mean Predicts   Mean ci
95% lows   Mean ci
95% upps   Predict ci
95% lows   Predict ci
95% uppt   Residuals   Std Error
Residuals   Student
Residuals   Cook's
D(   R   R   (   R   (   R   s   %4ds   %6.3fR   R   R   R   (   R   R   t&   statsmodels.sandbox.regression.predstdR   R   R   R   R   R   R    t   isfR   R5   R4   RA   Rr   R   R6   R+   R   R~   R   R   R   R   R   R   R   R2   (   R:   R   R   R   R)   t   predict_mean_set   tppft   predict_mean_cit   tmpt
   predict_set   predict_ci_lowt   predict_ci_uppt
   predict_cit   resid_set   table_smR   t   ss2R   R   R   R   R   R   R   t   st(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR   *  sP    				#	t   GLMInfluencec           B   s   e  Z d  Z e d    Z e d    Z e d    Z e d    Z e d    Z	 e d    Z
 e d    Z e d    Z e d	    Z RS(
   s3  Influence and outlier measures (experimental)

    This uses partly formulas specific to GLM, specifically cooks_distance
    is based on the hessian, i.e. observed or expected information matrix and
    not on cov_params, in contrast to MLEInfluence.
    Standardization for changes in parameters, in fittedvalues and in
    the linear predictor are based on cov_params.

    Parameters
    ----------
    results : instance of results class
        This only works for model and results classes that have the necessary
        helper methods.
    other arguments are only to override default behavior and are used instead
    of the corresponding attribute of the results class.
    By default resid_pearson is used as resid.

    Attributes
    ----------
    dbetas
        change in parameters divided by the standard error of parameters from
        the full model results, ``bse``.
    d_fittedvalues_scaled
        same as d_fittedvalues but scaled by the standard errors of a
        predicted mean of the response.
    d_linpred
        local change in linear prediction.
    d_linpred_scale
        local change in linear prediction scaled by the standard errors for
        the prediction based on cov_params.

    Notes
    -----
    This has not yet been tested for correctness when offset or exposure
    are used, although they should be supported by the code.

    Some GLM specific measures like d_deviance are still missing.

    Computing an explicit leave-one-observation-out (LOOO) loop is included
    but no influence measures are currently computed from it.
    c         C   s'   t  |  d  r |  j S|  j j   Sd S(   s   
        Diagonal of the hat_matrix for GLM

        Notes
        -----
        This returns the diagonal of the hat matrix that was provided as
        argument to GLMInfluence or computes it using the results method
        `get_hat_matrix`.
        R   N(   RS   R   R*   t   get_hat_matrix(   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    c         C   s=   t  j j |  j  |  j } | t  j d |  j  :} | j S(   s   Change in parameter estimates

        Notes
        -----
        This uses one-step approximation of the parameter change to deleting
        one observation.
        i   (   R   R   t   pinvR1   R   R   R   R   (   RU   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    
c         C   s(   |  j  } |  j t j |  j d |  S(   s#  
        Internally studentized pearson residuals

        Notes
        -----
        residuals / sqrt( scale * (1 - hii))

        where residuals are those provided to GLMInfluence which are
        pearson residuals by default, and
        hii is the diagonal of the hat matrix.
        i   (   R   R+   R   R   R   (   RU   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     s    	c         C   sj   |  j  } |  j d |  j } | | d | 9} d d l m } | j j | |  j |  j j  } | | f S(   s  Cook's distance

        Notes
        -----
        Based on one step approximation using resid_studentized and
        hat_matrix_diag for the computation.

        Cook's distance divides by the number of explanatory variables.

        Computed using formulas for GLM and does not use results.cov_params.
        It includes p-values based on the F-distribution which are only
        approximate outside of linear Gaussian models.
        i   i   i(   R   (	   R   R   R<   R   R   R   R!   R*   R   (   RU   R   R   R   R   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR~     s    	!c         C   s#   |  j  j j } | |  j j d  S(   s   
        Change in linear prediction

        This uses one-step approximation of the parameter change to deleting
        one observation ``d_params``.
        i   (   R*   R   R1   R   R   (   RU   R1   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt	   d_linpred  s    
c         C   s   |  j  |  j j j S(   s  
        Change in linpred scaled by standard errors

        This uses one-step approximation of the parameter change to deleting
        one observation ``d_params``, and divides by the standard errors
        for linpred provided by results.get_prediction.
        (   R  R   t   linpredR   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   d_linpred_scaled  s    c         C   s|   d d l  } | j d t  |  j j j } t j g  t |  j	  D]( \ } } |  j j j
 | | |  ^ qA  } | j   S(   s   experimental code
        iNs    this ignores offset and exposure(   t   warningst   warnt   UserWarningR*   R   R1   R   t   arrayt	   enumerateR   t   predictt   squeeze(   RU   R  R1   R   t   pit   fitted(    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   _fittedvalues_one
  s    	>c         C   s   |  j  j   |  j S(   s   experimental code
        (   R*   R  R   (   RU   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   _diff_fittedvalues_one  s    c         C   sJ  d d l  m } d   } |  j j j } |  j j j } |  j j j   } | j d  } | j d  } | j d  } }	 | j d  }
 } | j d d  } t	 | d	 d
  r t
 } n t } t j | j d t j } t j | j d t j } t j | j d t j } | |  j  } x| D] \ } } | d k	 rM| | }	 n  |
 d k	 rf|
 | } n  | d k	 r| | | d <n  |  j | | | | d |	 d | d | | d | | | } | r| d | j _ n  | j d |  j j d d  } | j j   | | <| j | | <| |  | | <q(Wt d | d | d | d |  S(   s  collect required results from the LOOO loop

        all results will be attached.
        currently only 'params', 'mse_resid', 'det_cov_params' are stored

        Reestimates the model with endog and exog dropping one observation
        at a time

        This uses a nobs loop, only attributes of the results instance are
        stored.

        Warning: This will need refactoring and API changes to be able to
        add options.
        i(   R   c         S   s   t  j j |  j    S(   N(   R   R   R   R   (   R:   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   <lambda>/  RX   t   freq_weightst   var_weightst   offsett   exposuret   n_trialst   familyt
   initializeR   t   start_paramsR   t   newtonR   R   R   R   N(   R   R   R*   R   R6   R1   t   _get_init_kwdst   popR   RS   R   t   FalseR   R   R2   R   Rr   R   R(  t   nR7   R   R   R   R   (   RU   R   R   R6   R1   t	   init_kwdsR#  R$  R%  t   offset_R&  t	   exposure_R'  t   is_binomialR   R   R   R   R   R   t   mod_iR   (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR     sN    		
		(   R   R   R   R   R   R   R   R~   R   R  R  R   R!  R   (    (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyR  y  s   )(   R   t   collectionsR    t   numpyR   t   statsmodels.compat.pythonR   t)   statsmodels.graphics._regressionplots_docR   t#   statsmodels.regression.linear_modelR   t   statsmodels.stats.multitestR   t   statsmodels.tools.decoratorsR   t   statsmodels.tools.toolsR   R   R.  R0   R@   RH   t   objectRI   R   R   R   R  (    (    (    sC   lib/python2.7/site-packages/statsmodels/stats/outliers_influence.pyt   <module>   s&   	Q$	0k  O