
    M/PhFW                     B   d Z ddlZddlmZ ddlmc mZ ddlmc m	Z
 ddlmc mZ ddlmc mZ ddlmc mZ ddlmc mZ ddlmZ ddlmZ dgZd Z G d dej                  Z G d d	ej                  Z  G d
 dej!                  Z" e
j#        e"e            dS )a  
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.
    N)cache_readonly)ConvergenceWarningRLMc                     t          j        | |         | |dz
           z
            }t          j        ||k              o||k      S )N   )npabsany)	criterion	iterationtolmaxiterconds        f/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/robust/robust_linear_model.py_check_convergencer      sE    6)I&9q=)AABBDtcz"":y7':;;    c                        e Zd Zd                    ej        ej                  Zd fd	Zd Z	d Z
d Zdd	Zd
 Zd Zd Zd Z	 	 ddZ xZS )r   aE  
    Robust Linear Model

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

    {params}
    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}

    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 : ndarray
        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 : ndarray
        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 : ndarray
        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 : ndarray
        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()
    >>> 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])
    )paramsextra_paramsNnonec                    |                      |           ||nt          j                    | _         t	          t
          j        |           j        ||fd|i| |                                  | j	        
                    ddg           d S )Nmissingweights
pinv_wexog)_check_kwargsnormsHuberTMsuperbaseLikelihoodModel__init___initialize
_data_attrextend)selfendogexogr   r   kwargs	__class__s         r   r"   zRLM.__init__m   s    6"""m2d"D))25$ 	N 	N;B	NFL	N 	N 	N	<899999r   c                    t           j                            | j                  | _        t          j        | j        t          j        | j                            | _        t          | j        j	        d         t           j        
                    | j                  z
            | _        t          t           j        
                    | j                  dz
            | _        t          | j        j	        d                   | _        dS )zo
        Initializes the model for the IRLS fit.

        Resets the history and number of iterations.
        r   r   N)r   linalgpinvr(   r   dot	transposenormalized_cov_paramsfloatshapematrix_rankdf_residdf_modelr'   nobsr&   s    r   r#   zRLM._initializew   s     )..33%'VDO,.L,I,I&K &K"tyq1!y44TY?? @ A Abi33DI>>BCC$**1-..			r   c                     t           NNotImplementedErrorr&   r   s     r   scorez	RLM.score       !!r   c                     t           r9   r:   r<   s     r   informationzRLM.information   r>   r   c                 >    || j         }t          j        ||          S )a[  
        Return linear predicted values from a design matrix.

        Parameters
        ----------
        params : array_like
            Parameters of a linear model
        exog : array_like, optional.
            Design / exogenous data. Model exog is used if None.

        Returns
        -------
        An array of fitted values
        )r(   r   r.   )r&   r   r(   s      r   predictzRLM.predict   s"      <9DvdF###r   c                     t           r9   r:   r<   s     r   loglikezRLM.loglike   r>   r   c                 ~    | j         |j        z
  }|                     ||j        z                                            S )zQ
        Returns the (unnormalized) log-likelihood from the M estimator.
        )r'   fittedvaluesr   scalesum)r&   tmp_results	tmp_resids      r   deviancezRLM.deviance   s9     J!99	vvi+"334488:::r   c                    |d                              |j                   |d                              |j                   |dk    r/|d                              |                     |                     nZ|dk    r)|d                              |j        |j        z             n+|dk    r%|d                              |j        j                   |S )Nr   rG   devrK   sresidr   )appendr   rG   rK   residmodelr   )r&   rI   historyconvs       r   _update_historyzRLM._update_history   s      !3444 12225==J&&t}}['A'ABBBBXH$$[%69J%JKKKKYI%%k&7&?@@@r   c                 z   t          | j        t                    rJ| j                                        dk    rt	          j        |d          S t          d| j        z            t          | j        t          j                  r!|                     | j        | j	        |          S t	          j        | |          dz  S )zU
        Estimates the scale based on the option provided to the fit method.
        madr   )centerz&Option %s for scale_est not understood   )

isinstance	scale_eststrlowerrG   rV   
ValueError
HuberScaler4   r6   )r&   rP   s     r   _estimate_scalezRLM._estimate_scale   s     dnc** 		5~##%%..yq1111 !I!%"0 1 1 1(899 	5>>$-EBBB?4//144r   2   :0yE>rV   H1TrM   c	                    |                                 dvrt          d|z            |                                 | _        |                                }|dvrt          d|z            || _        |2t          j        | j        | j                  	                                }	nt          j        |t          j                                                  }|j        d         | j        j        d         k    s|j        dk    r2t          d	                    | j        j        d                             t#          j        | j        | j        t          j        | j                  d
          }
|
                    |          }	|s|                     |	j                  | _        t1          t          j        gg           }|dk    r	|d         }n|dk    r7|                    t1          t          j        g                     |d         }ny|dk    r7|                    t1          t          j        g                     |d         }n<|dk    r6|                    t1          t          j        g                     |d         }|                     |	||          }d}d}|s| j        dk    r ddl}|                    dt<                     n| j                             |	j        | j        z            | _         t#          j        | j        | j        | j         d          	                                }	|du r|                     |	j                  | _        |                     |	||          }|dz  }tC          ||||          }|tE          | |	j#        | j$        | j                  }||d<   ||_%        t1          |                                 || j        j&        j'        |          |_(        tS          |          S )a  
        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 : str
            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 : str, optional
            'H1', 'H2', or 'H3'
            Indicates how the covariance matrix is estimated.  Default is 'H1'.
            See rlm.RLMResults for more information.
        init : str
            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 : str 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.
        start_params : array_like, optional
            Initial guess of the solution of the optimizer. If not provided,
            the initial parameters are computed using OLS.

        Returns
        -------
        results : statsmodels.rlm.RLMresults
            Results instance
        )rb   H2H3z#Covariance matrix %s not understood)r   coefsrM   rN   z&Convergence argument %s not understoodN)dtyper   r   z/start_params must by a 1-d array with {} valuesF)r   check_weights)r   rG   rf   r   rM   )rK   rK   rN   )rN   r   )r           zkEstimated scale is 0.0 indicating that the most last iteration produced a perfect fit of the weighted data.Tr   )covrZ   normrS   )*upperr]   rj   r\   rZ   lmWLSr'   r(   fitr   asarraydoublesqueezer2   ndimformat	reg_tools_MinimalWLS	ones_likeresultsr_   rP   rG   dictinfupdaterT   warningswarnr   r   r   r   
RLMResultsr   r0   fit_historyr*   __name__fit_optionsRLMResultsWrapper)r&   r   r   rZ   initrj   update_scalerS   start_paramswls_resultsfake_wlsrR   r   r   	convergedr|   rx   s                    r   ro   zRLM.fit   s   b 99;;000BSHIIIyy{{DHzz||<<<ELMMM"&TY77;;==KK:l")DDDLLNNL"1%);;; %**  "**0&1C*D*DF F F ,TZ57\$*5M5M;@B B BH #**<88K 	A--k.?@@DJrvhb1117??)IIU]]NN4"&222333
+IIXNN4x000111)IIYNN4111222	*I &&{GTBB		 	OzS   /0BD D D 6>>+*;dj*HIIDL#/
DI8<>BD D DDGCEE  t##!11+2CDD
**;FFGNI*9igNNI  	O  T;#5!7E E  )%"syy{{i(,(8(AN N N !)))r   )Nr   r9   )r`   ra   rV   Nrb   TrM   N)r   
__module____qualname__rt   r    _model_params_doc_missing_param_doc__doc__r"   r#   r=   r@   rB   rD   rK   rT   r_   ro   __classcell__r*   s   @r   r   r   $   s       DH 	%D4K 	 	 	I P: : : : : :/ / /" " "" " "$ $ $ $(" " "; ; ;	 	 	5 5 5 IM8<w* w* w* w* w* w* w* w*r   c                        e Zd ZdZ f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Z	 	 ddZ xZS )r~   a  
    Class to contain RLM results

    Attributes
    ----------

    bcov_scaled : ndarray
        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 : ndarray
        The usual p x p covariance matrix with scale set equal to 1.  It
        is then just equivalent to normalized_cov_params.
    bse : ndarray
        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 : ndarray
        An array of the chi-squared values of the parameter 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 : ndarray
        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 : ndarray
        See RLM.normalized_cov_params
    params : ndarray
        The coefficients of the fitted model
    pinv_wexog : ndarray
        See RLM.pinv_wexog
    pvalues : ndarray
        The p values associated with `tvalues`. Note that `tvalues` are assumed
        to be distributed standard normal rather than Student's t.
    resid : ndarray
        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 : ndarray
        The scaled residuals.
    tvalues : ndarray
        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 : ndarray
        The reported weights are determined by passing the scaled residuals
        from the last weighted least squares fit in the IRLS algorithm.

    See Also
    --------
    statsmodels.base.model.LikelihoodModelResults
    c                    t                                          ||||           || _        |j        | _        |j        | _        |j        | _        i | _        | j                            dg           | j	        | _
        d S )NrN   )r   r"   rQ   r5   r4   r6   _cache_data_in_cacher%   bcov_scaledcov_params_default)r&   rQ   r   r0   rG   r*   s        r   r"   zRLMResults.__init__  su    (=uEEE
J	""H:..."&"2r   c                 J    t          j        | j        j        | j                  S r9   )r   r.   rQ   r(   r   r7   s    r   rF   zRLMResults.fittedvalues  s    vdjot{333r   c                 *    | j         j        | j        z
  S r9   )rQ   r'   rF   r7   s    r   rP   zRLMResults.resid  s    z$"333r   c                 z    | j         dk    r"| j                                        }d|d d <   |S | j        | j         z  S )Nri   )rG   rP   copy)r&   rN   s     r   rN   zRLMResults.sresid  sA    :Z__&&FF111IMzDJ&&r   c                     | j         S r9   )r0   r7   s    r   bcov_unscaledzRLMResults.bcov_unscaled  s    ))r   c                     | j         j        S r9   )rQ   r   r7   s    r   r   zRLMResults.weights  s    z!!r   c           
         | j         }t          j        |j                            | j                            }t          j        |j                            | j                            }d| j        dz   | j        z  |z  |dz  z  z   }|j	        dk    rt          j
        |j                            | j                  dz            }t          j
        |j                            | j                            }|dz  d| j        z  |z  | j        dz  z  z  d| j        z  |z  dz  z  |j        z  S t          j        |j                            | j                  |j        j        z  |j                  }t          j                            |          }|j	        dk    r|d| j        z  z  t          j
        |j                            | j                  dz            z  | j        dz  z  d| j        z  t          j
        |j                            | j                            z  z  |z  S |j	        dk    r|dz  dz  | j        z  t          j
        |j                            | j                  dz            z  | j        dz  z  t          j        t          j        |t          j        |j        j        |j                            |          z  S d S )Nr   rX   rb   rd   re   )rQ   r   meanr   	psi_derivrN   varr5   r6   rj   rH   psir4   rG   r0   r.   r(   Tr,   inv)	r&   rQ   mvar_psiprimekss_psis_psi_derivWW_invs	            r   r   zRLMResults.bcov_scaled  s   
GEG%%dk2233veg//<<=="di/,>aGG9VEGKK449::F&!2!24;!?!?@@K6Q.7$*/IJdi-+-!35+, , uw((55
Dz# #AIMM!$$E yD  A-.GKK,,123 23 359Z1_Ety=&!2!24;!?!?@@AB EJJ J d""Bw{T]2RVGKK,,163 63 359Z1_EF5"&uz"B"BCC   #"r   c                 t    t           j                            t          j        | j                            dz  S NrX   )statsrk   sfr   r	   tvaluesr7   s    r   pvalueszRLMResults.pvalues  s'    z}}RVDL1122Q66r   c                 X    t          j        t          j        | j                            S r9   )r   sqrtdiagr   r7   s    r   bsezRLMResults.bse  s    wrwt/00111r   c                 &    | j         | j        z  dz  S r   )r   r   r7   s    r   chisqzRLMResults.chisq  s    dh&1,,r   Nr   皙?textc                    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         z  gfg	}g d}|d}ddlm}  |            }	|	                    | |||||           |	                    | |||| j                   g }
d}|
                    |           |
r|	                    |
           |	S )z;
        This is for testing the new summary setup
        )zDep. Variable:N)zModel:NzMethod:IRLSzNorm:rk   zScale Est.:rZ   z	Cov Type:rj   )zDate:N)zTime:NzNo. Iterations:z%dr   ))zNo. Observations:N)zDf Residuals:N)z	Df Model:NNz&Robust linear Model Regression Resultsr   )Summary)gleftgrightynamexnametitle)r   r   alphause_tzIf the model instance has been used for another fit with different fit parameters, then the fit options might not be the correct ones anymore .)	r   r   statsmodels.iolib.summaryr   add_table_2colsadd_table_paramsr   rO   add_extra_txt)r&   r   r   r   r   
return_fmttop_left	top_rightr   smryetextwstrs               r   summaryzRLMResults.summary  sI   
 -$)t/789"T%5k%B$CD 4#3E#:";<##&0@0M)M(NO	  	
 <E 	655555wyyT)#(U 	 	D 	D 	Dd%uE$(J 	 	0 	0 	0 - 	T 	&u%%%r   %.4fc                 p    ddl m} |                                }|                    | |||||           |S )a  Experimental summary function for regression results

        Parameters
        ----------
        yname : str
            Name of the dependent variable (optional)
        xname : list[str], optional
            Names for the exogenous variables. Default is `var_##` for ## in
            the number of regressors. Must match the number of parameters
            in the model
        title : str, 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 : str
            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
        r   )summary2)rx   r   float_formatr   r   r   )statsmodels.iolibr   r   add_base)r&   r   r   r   r   r   r   r   s           r   r   zRLMResults.summary2  sV    < 	/.....!!d%l!e 	 	= 	= 	= r   )NNr   r   r   )NNNr   r   )r   r   r   r   r"   r   rF   rP   rN   r   r   r   r   r   r   r   r   r   r   s   @r   r~   r~   =  st       S Sj
3 
3 
3 
3 
3 4 4 ^4 4 4 ^4 ' ' ^' * * ^* " " ^"   ^> 7 7 ^7 2 2 ^2 - - ^- >A!) ) ) )V BE$# # # # # # # #r   r~   c                       e Zd ZdS )r   N)r   r   r    r   r   r   r   5  s        Dr   r   )$r   numpyr   scipy.statsr   statsmodels.base.modelr    rQ   statsmodels.base.wrapperwrapperwrapstatsmodels.regression._tools
regression_toolsru   #statsmodels.regression.linear_modellinear_modelrm   statsmodels.robust.normsrobustr   statsmodels.robust.scalerG   statsmodels.tools.decoratorsr   statsmodels.tools.sm_exceptionsr   __all__r   r!   r   LikelihoodModelResultsr~   RegressionResultsWrapperr   populate_wrapperr   r   r   <module>r      s              % % % % % % % % % ' ' ' ' ' ' ' ' ' 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( 7 7 7 7 7 7 > > > > > >'< < <
V* V* V* V* V*$
 V* V* V*ru u u u u, u u up	 	 	 	 	3 	 	 	  ' 4 4 4 4 4r   