
p7]c           @   s  d  Z  d d l Z d d l j Z d d l m Z d d l j j	 Z
 d d l j j Z d d l j j Z d d l j j Z d d l j j Z d d l j j Z d g Z d   Z d e j f d     YZ d e j f d     YZ d	 e
 j f d
     YZ  e j! e  e  e" d k rd d l# j$ Z% e j& d d d d d d d d d d d d d d d d d d d d d  d! d" d# d$ g  Z' e j& d% d& d& d' d( d% d) d% d* d+ d, d- d' d( d. d- d( d% d& d/ d- d0 d. d1 d' g d2 d3 d4 d5 d6 d7 d8 d9 d: d; d< d= d> d? d@ dA dB dC dD dE dF dG dH dI d6 g g  Z( e( j) Z( e% j* e(  Z( d dJ l+ m, Z, e, dK e-  Z. e% j* e. j(  e. _( e e. j' e. j( dL e j/   Z0 e0 j1 dM e j2    Z3 n  d S(N   s  
Robust linear models with support for the M-estimators  listed under
:ref:`norms <norms>`.

References
----------
PJ Huber.  'Robust Statistics' John Wiley and Sons, Inc., New York.  1981.

PJ Huber.  1973,  'The 1972 Wald Memorial Lectures: Robust Regression:
    Asymptotics, Conjectures, and Monte Carlo.'  The Annals of Statistics,
    1.5, 799-821.

R Venables, B Ripley. 'Modern Applied Statistics in S'  Springer, New York,
    2002.
iN(   t   cache_readonlyt   RLMc         C   s9   t  j t  j |  | |  | d  | k  o7 | | k  S(   Ni   (   t   npt   anyt   fabs(   t	   criteriont	   iterationt   tolt   maxiter(    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   _check_convergence   s    c           B   s   e  Z d  i e j d 6e j d 6Z d d d  Z d   Z d   Z	 d   Z
 d d  Z d	   Z d
   Z d   Z d   Z d d d d d e d d  Z RS(   sR  
    Robust Linear Models

    Estimate a robust linear model via iteratively reweighted least squares
    given a robust criterion estimator.

    %(params)s
    M : statsmodels.robust.norms.RobustNorm, optional
        The robust criterion function for downweighting outliers.
        The current options are LeastSquares, HuberT, RamsayE, AndrewWave,
        TrimmedMean, Hampel, and TukeyBiweight.  The default is HuberT().
        See statsmodels.robust.norms for more information.
    %(extra_params)s

    Attributes
    ----------

    df_model : float
        The degrees of freedom of the model.  The number of regressors p less
        one for the intercept.  Note that the reported model degrees
        of freedom does not count the intercept as a regressor, though
        the model is assumed to have an intercept.
    df_resid : float
        The residual degrees of freedom.  The number of observations n
        less the number of regressors p.  Note that here p does include
        the intercept as using a degree of freedom.
    endog : array
        See above.  Note that endog is a reference to the data so that if
        data is already an array and it is changed, then `endog` changes
        as well.
    exog : array
        See above.  Note that endog is a reference to the data so that if
        data is already an array and it is changed, then `endog` changes
        as well.
    M : statsmodels.robust.norms.RobustNorm
         See above.  Robust estimator instance instantiated.
    nobs : float
        The number of observations n
    pinv_wexog : array
        The pseudoinverse of the design / exogenous data array.  Note that
        RLM has no whiten method, so this is just the pseudo inverse of the
        design.
    normalized_cov_params : array
        The p x p normalized covariance of the design / exogenous data.
        This is approximately equal to (X.T X)^(-1)


    Examples
    --------
    >>> import statsmodels.api as sm
    >>> data = sm.datasets.stackloss.load(as_pandas=False)
    >>> data.exog = sm.add_constant(data.exog)
    >>> rlm_model = sm.RLM(data.endog, data.exog,                            M=sm.robust.norms.HuberT())

    >>> rlm_results = rlm_model.fit()
    >>> rlm_results.params
    array([  0.82938433,   0.92606597,  -0.12784672, -41.02649835])
    >>> rlm_results.bse
    array([ 0.11100521,  0.30293016,  0.12864961,  9.79189854])
    >>> rlm_results_HC2 = rlm_model.fit(cov="H2")
    >>> rlm_results_HC2.params
    array([  0.82938433,   0.92606597,  -0.12784672, -41.02649835])
    >>> rlm_results_HC2.bse
    array([ 0.11945975,  0.32235497,  0.11796313,  9.08950419])
    >>> mod = sm.RLM(data.endog, data.exog, M=sm.robust.norms.Hampel())
    >>> rlm_hamp_hub = mod.fit(scale_est=sm.robust.scale.HuberScale())
    >>> rlm_hamp_hub.params
    array([  0.73175452,   1.25082038,  -0.14794399, -40.27122257])
    t   paramst   extra_paramst   nonec         K   sj   | d  k	 r | n	 t j   |  _ t t j |   j | | d | | |  j   |  j	 j
 d d g  d  S(   Nt   missingt   weightst
   pinv_wexog(   t   Nonet   normst   HuberTt   Mt   supert   baset   LikelihoodModelt   __init__t   _initializet
   _data_attrt   extend(   t   selft   endogt   exogR   R   t   kwargs(    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR   l   s
    !

c         C   s   t  j j |  j  |  _ t  j |  j t  j |  j   |  _ t  j |  j j	 d t  j j
 |  j   |  _ t  j t  j j
 |  j  d  |  _ t |  j j	 d  |  _ d S(   so   
        Initializes the model for the IRLS fit.

        Resets the history and number of iterations.
        i    i   N(   R   t   linalgt   pinvR   R   t   dott	   transposet   normalized_cov_paramst   floatt   shapet   matrix_rankt   df_residt   df_modelR   t   nobs(   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR   u   s    %c         C   s
   t   d  S(   N(   t   NotImplementedError(   R   R
   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   score   s    c         C   s
   t   d  S(   N(   R*   (   R   R
   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   information   s    c         C   s(   | d k r |  j } n  t j | |  S(   s  
        Return linear predicted values from a design matrix.

        Parameters
        ----------
        params : array-like, optional after fit has been called
            Parameters of a linear model
        exog : array-like, optional.
            Design / exogenous data. Model exog is used if None.

        Returns
        -------
        An array of fitted values

        Notes
        -----
        If the model as not yet been fit, params is not optional.
        N(   R   R   R   R!   (   R   R
   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   predict   s    c         C   s
   t   d  S(   N(   R*   (   R   R
   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   loglike   s    c         C   s$   |  j  |  j | j | j  j   S(   sQ   
        Returns the (unnormalized) log-likelihood from the M estimator.
        (   R   R   t   fittedvaluest   scalet   sum(   R   t   tmp_results(    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   deviance   s    c         C   s   | d j  | j  | d j  | j  | d k rQ | d j  |  j |   nP | d k r{ | d j  | j | j  n& | d k r | d j  | j j  n  | S(   NR
   R0   t   devR3   t   sresidR   (   t   appendR
   R0   R3   t   residt   modelR   (   R   R2   t   historyt   conv(    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   _update_history   s    c         C   s   t  |  j t  rP |  j j   d k r: t j | d d St d |  j   nB t  |  j t j  r~ |  j |  j |  j	 |  St j |  |  d Sd S(   sU   
        Estimates the scale based on the option provided to the fit method.
        t   madt   centeri    s&   Option %s for scale_est not understoodi   N(
   t
   isinstancet	   scale_estt   strt   lowerR0   R<   t
   ValueErrort
   HuberScaleR'   R)   (   R   R7   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   _estimate_scale   s    i2   g:0yE>R<   t   H1R4   c      	   C   s  | j    d k r% t d |   n | j    |  _ | j   } | d k r_ t d	 |   n  | |  _ t j |  j |  j  j	   } | s |  j
 | j  |  _ n  t d
 t j g d g   }	 | d k r |	 d
 }
 n | d k r|	 j t d t j g   |	 d }
 nj | d k rB|	 j t d t j g   |	 d }
 n5 | d k rw|	 j t d t j g   |	 d }
 n  |  j | |	 |  }	 d } d } x | sH|  j j | j |  j  |  _ t j |  j |  j d |  j d t j	   } | t k r|  j
 | j  |  _ n  |  j | |	 |  }	 | d 7} t |
 | | |  } qWt |  | j |  j |  j  } | |	 d <|	 | _ t d | j    d | d |  j j j d |  | _ t |  S(   s  
        Fits the model using iteratively reweighted least squares.

        The IRLS routine runs until the specified objective converges to `tol`
        or `maxiter` has been reached.

        Parameters
        ----------
        conv : string
            Indicates the convergence criteria.
            Available options are "coefs" (the coefficients), "weights" (the
            weights in the iteration), "sresid" (the standardized residuals),
            and "dev" (the un-normalized log-likelihood for the M
            estimator).  The default is "dev".
        cov : string, optional
            'H1', 'H2', or 'H3'
            Indicates how the covariance matrix is estimated.  Default is 'H1'.
            See rlm.RLMResults for more information.
        init : string
            Specifies method for the initial estimates of the parameters.
            Default is None, which means that the least squares estimate
            is used.  Currently it is the only available choice.
        maxiter : int
            The maximum number of iterations to try. Default is 50.
        scale_est : string or HuberScale()
            'mad' or HuberScale()
            Indicates the estimate to use for scaling the weights in the IRLS.
            The default is 'mad' (median absolute deviation.  Other options are
            'HuberScale' for Huber's proposal 2. Huber's proposal 2 has
            optional keyword arguments d, tol, and maxiter for specifying the
            tuning constant, the convergence tolerance, and the maximum number
            of iterations. See statsmodels.robust.scale for more information.
        tol : float
            The convergence tolerance of the estimate.  Default is 1e-8.
        update_scale : Bool
            If `update_scale` is False then the scale estimate for the
            weights is held constant over the iteration.  Otherwise, it
            is updated for each fit in the iteration.  Default is True.

        Returns
        -------
        results : object
            statsmodels.rlm.RLMresults
        RE   t   H2t   H3s#   Covariance matrix %s not understoodR   t   coefsR4   R5   s&   Convergence argument %s not understoodR
   R0   R3   i   i    t   check_weightsR   t   covR?   t   normR:   (   RE   RF   RG   (   R   RH   R4   R5   (    t   upperRB   RJ   RA   R?   t   lmt   WLSR   R   t   fitRD   R7   R0   t   dictR   t   inft   updateR;   R   R   t	   reg_toolst   _MinimalWLSt   TrueR	   t
   RLMResultsR
   R#   t   fit_historyt	   __class__t   __name__t   fit_optionst   RLMResultsWrapper(   R   R   R   R?   t   initRJ   t   update_scaleR:   t   wls_resultsR9   R   R   t	   convergedt   results(    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyRO      sV    .			

	N(   RY   t
   __module__R   t   _model_params_doct   _missing_param_doct   __doc__R   R   R   R+   R,   R-   R.   R3   R;   RD   RU   RO   (    (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR   #   s   F								RV   c           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 e d
    Z d d d d d d  Z d d d d d d  Z RS(   s  
    Class to contain RLM results

    Attributes
    ----------

    bcov_scaled : array
        p x p scaled covariance matrix specified in the model fit method.
        The default is H1. H1 is defined as
        ``k**2 * (1/df_resid*sum(M.psi(sresid)**2)*scale**2)/
        ((1/nobs*sum(M.psi_deriv(sresid)))**2) * (X.T X)^(-1)``

        where ``k = 1 + (df_model +1)/nobs * var_psiprime/m**2``
        where ``m = mean(M.psi_deriv(sresid))`` and
        ``var_psiprime = var(M.psi_deriv(sresid))``

        H2 is defined as
        ``k * (1/df_resid) * sum(M.psi(sresid)**2) *scale**2/
        ((1/nobs)*sum(M.psi_deriv(sresid)))*W_inv``

        H3 is defined as
        ``1/k * (1/df_resid * sum(M.psi(sresid)**2)*scale**2 *
        (W_inv X.T X W_inv))``

        where `k` is defined as above and
        ``W_inv = (M.psi_deriv(sresid) exog.T exog)^(-1)``

        See the technical documentation for cleaner formulae.
    bcov_unscaled : array
        The usual p x p covariance matrix with scale set equal to 1.  It
        is then just equivalent to normalized_cov_params.
    bse : array
        An array of the standard errors of the parameters.  The standard
        errors are taken from the robust covariance matrix specified in the
        argument to fit.
    chisq : array
        An array of the chi-squared values of the paramter estimates.
    df_model
        See RLM.df_model
    df_resid
        See RLM.df_resid
    fit_history : dict
        Contains information about the iterations. Its keys are `deviance`,
        `params`, `iteration` and the convergence criteria specified in
        `RLM.fit`, if different from `deviance` or `params`.
    fit_options : dict
        Contains the options given to fit.
    fittedvalues : array
        The linear predicted values.  dot(exog, params)
    model : statsmodels.rlm.RLM
        A reference to the model instance
    nobs : float
        The number of observations n
    normalized_cov_params : array
        See RLM.normalized_cov_params
    params : array
        The coefficients of the fitted model
    pinv_wexog : array
        See RLM.pinv_wexog
    pvalues : array
        The p values associated with `tvalues`. Note that `tvalues` are assumed to be distributed
        standard normal rather than Student's t.
    resid : array
        The residuals of the fitted model.  endog - fittedvalues
    scale : float
        The type of scale is determined in the arguments to the fit method in
        RLM.  The reported scale is taken from the residuals of the weighted
        least squares in the last IRLS iteration if update_scale is True.  If
        update_scale is False, then it is the scale given by the first OLS
        fit before the IRLS iterations.
    sresid : array
        The scaled residuals.
    tvalues : array
        The "t-statistics" of params. These are defined as params/bse where bse are taken
        from the robust covariance matrix specified in the argument to fit.
    weights : array
        The reported weights are determined by passing the scaled residuals
        from the last weighted least squares fit in the IRLS algortihm.

    See Also
    --------
    statsmodels.base.model.LikelihoodModelResults
    c         C   sq   t  t |   j | | | |  | |  _ | j |  _ | j |  _ | j |  _ i  |  _ d g |  _ |  j	 |  _
 d  S(   NR5   (   R   RV   R   R8   R(   R'   R)   t   _cachet   data_in_cachet   bcov_scaledt   cov_params_default(   R   R8   R
   R#   R0   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR     s    
		c         C   s   t  j |  j j |  j  S(   N(   R   R!   R8   R   R
   (   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR/     s    c         C   s   |  j  j |  j S(   N(   R8   R   R/   (   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR7     s    c         C   s   |  j  |  j S(   N(   R7   R0   (   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR5     s    c         C   s   |  j  S(   N(   R#   (   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   bcov_unscaled  s    c         C   s
   |  j  j S(   N(   R8   R   (   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR     s    c         C   s  |  j  } t j | j j |  j   } t j | j j |  j   } d |  j d |  j | | d } | j	 d k r | d d |  j
 t j | j j |  j  d  |  j d d |  j t j | j j |  j   d | j St j | j j |  j  | j j | j  } t j j |  } | j	 d k r| d |  j
 t j | j j |  j  d  |  j d d |  j t j | j j |  j   | S| j	 d k r| d d |  j
 t j | j j |  j  d  |  j d t j t j | t j | j j | j   |  Sd  S(   Ni   i   RE   RF   RG   i(   R8   R   t   meanR   t	   psi_derivR5   t   varR(   R)   RJ   R'   R1   t   psiR0   R#   R!   R   t   TR   t   inv(   R   R8   t   mt   var_psiprimet   kt   Wt   W_inv(    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyRg     s    	$p"egc         C   s    t  j j t j |  j   d S(   Ni   (   t   statsRK   t   sfR   t   abst   tvalues(   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   pvalues  s    c         C   s   t  j t  j |  j   S(   N(   R   t   sqrtt   diagRg   (   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   bse  s    c         C   s   |  j  |  j d S(   Ni   (   R
   R|   (   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   chisq  s    i    g?t   textc         C   s1  d d  d d g f d |  j d g f d |  j d g f d	 |  j d
 g f d! d" d d |  j d g f g	 } d# d$ d% g } | d k	 r d } n  d d l m } |   }	 |	 j |  d | d | d | d | d | |	 j |  d | d | d | d |  j g  }
 d } |
 j |  |
 r-|	 j	 |
  n  |	 S(&   s;   
        This is for testing the new summary setup
        s   Dep. Variable:s   Model:s   Method:t   IRLSs   Norm:RK   s   Scale Est.:R?   s	   Cov Type:RJ   s   Date:s   Time:s   No. Iterations:s   %dR   s   No. Observations:s   Df Residuals:s	   Df Model:s&   Robust linear Model Regression Resultsi(   t   Summaryt   gleftt   grightt   ynamet   xnamet   titlet   alphat   use_ts   If the model instance has been used for another fit with different fit
parameters, then the fit options might not be the correct ones anymore .N(   s   Dep. Variable:N(   s   Model:N(   s   Date:N(   s   Time:N(   s   No. Observations:N(   s   Df Residuals:N(   s	   Df Model:N(
   R   RZ   RW   t   statsmodels.iolib.summaryR   t   add_table_2colst   add_table_paramsR   R6   t   add_extra_txt(   R   R   R   R   R   t
   return_fmtt   top_leftt	   top_rightR   t   smryt   etextt   wstr(    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   summary  s4    			
s   %.4fc         C   sN   d d l  m } | j   } | j d |  d | d | d | d | d |  | S(	   s  Experimental summary function for regression results

        Parameters
        ----------
        xname : List of strings of length equal to the number of parameters
            Names of the independent variables (optional)
        yname : string
            Name of the dependent variable (optional)
        title : string, optional
            Title for the top table. If not None, then this replaces the
            default title
        alpha : float
            significance level for the confidence intervals
        float_format: string
            print format for floats in parameters summary

        Returns
        -------
        smry : Summary instance
            this holds the summary tables and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary2.Summary : class to hold summary results
        i(   t   summary2R`   R   t   float_formatR   R   R   (   t   statsmodels.iolibR   R   t   add_base(   R   R   R   R   R   R   R   R   (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR     s
    N(   RY   Ra   Rd   R   R    R/   R7   R5   Ri   R   Rg   Ry   R|   R}   R   R   R   (    (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyRV   *  s   S	+R[   c           B   s   e  Z RS(    (   RY   Ra   (    (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyR[     s   t   __main__gGz0@g      '@g(\(@g(\-@g     +@g\(2@g       @gGz1@g(\S@g     5@g
ףp=*D@g      5@g      +@g     3@g      8@g      =@g33333.@g      3@g      #@ǧA@gfffff1@g)\(J@g     2@gGz3@g     %@i   i   i   i   i   i   i   i   i
   i	   i   i   i   i0  i   iT  iP   i   iJ  in   i   i  i]  i  i   i   i  i  i  i   i   i$   i  i   i*  i  i{  (   t   loadt	   as_pandasR   R?   (4   Rd   t   numpyR   t   scipy.statsRu   t   statsmodels.tools.decoratorsR    t#   statsmodels.regression.linear_modelt
   regressiont   linear_modelRM   t   statsmodels.regression._toolst   _toolsRS   t   statsmodels.robust.normst   robustR   t   statsmodels.robust.scaleR0   t   statsmodels.base.modelR   R8   t   statsmodels.base.wrappert   wrappert   wrapt   __all__R	   R   R   t   LikelihoodModelResultsRV   t   RegressionResultsWrapperR[   t   populate_wrapperRY   t   statsmodels.apit   apit   smt   arrayR   R   Rn   t   add_constantt   statsmodels.datasets.stacklossR   t   Falset   dataR   t
   m1_Huber_HRO   RC   t   results_Huber1_H(    (    (    sE   lib/python2.7/site-packages/statsmodels/robust/robust_linear_model.pyt   <module>   s@   		 96-	%!