
    M/Ph                   d   d Z ddlmZ ddlmZ ddlmZmZ ddlm	Z	 ddl
mZ ddlZddlZddlmZmZ dd	lmZmZ dd
l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dl!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z. ddl/m0Z1 dZ2g dZ3dZ4d Z5 G d dej6                  Z7 G d de7          Z8 G d de7          Z9 G d de9          Z: G d  d!e8          Z;	 	 d-d%Z<d.d&Z= G d' d(ej>                  Z? G d) d*e?          Z@ G d+ d,ejA                  ZB ejC        eBe?           dS )/aH  
This module implements standard regression models:

Generalized Least Squares (GLS)
Ordinary Least Squares (OLS)
Weighted Least Squares (WLS)
Generalized Least Squares with autoregressive error terms GLSAR(p)

Models are specified with an endogenous response variable and an
exogenous design matrix and are fit using their `fit` method.

Subclasses that have more complicated covariance matrices
should write over the 'whiten' method as the fit method
prewhitens the response by calling 'whiten'.

General reference for regression models:

D. C. Montgomery and E.A. Peck. "Introduction to Linear Regression
    Analysis." 2nd. Ed., Wiley, 1992.

Econometrics references for regression models:

R. Davidson and J.G. MacKinnon.  "Econometric Theory and Methods," Oxford,
    2004.

W. Green.  "Econometric Analysis," 5th ed., Pearson, 2003.
    )annotations)Appender)lrangelzip)Literal)SequenceN)optimizestats)choleskytoeplitz)dtrtri)
_ELRegOpts)PredictionResults)cache_readonlycache_writable)InvalidTestWarningValueWarning)pinv_extended)Float64Array)	bool_like
float_likestring_like   )_predictionzrestructuredtext en)GLSWLSOLSGLSARr   RegressionResultsWrappera,  
        Return a regularized fit to a linear regression model.

        Parameters
        ----------
        method : str
            Either 'elastic_net' or 'sqrt_lasso'.
        alpha : scalar or array_like
            The penalty weight.  If a scalar, the same penalty weight
            applies to all variables in the model.  If a vector, it
            must have the same length as `params`, and contains a
            penalty weight for each coefficient.
        L1_wt : scalar
            The fraction of the penalty given to the L1 penalty term.
            Must be between 0 and 1 (inclusive).  If 0, the fit is a
            ridge fit, if 1 it is a lasso fit.
        start_params : array_like
            Starting values for ``params``.
        profile_scale : bool
            If True the penalized fit is computed using the profile
            (concentrated) log-likelihood for the Gaussian model.
            Otherwise the fit uses the residual sum of squares.
        refit : bool
            If True, the model is refit using only the variables that
            have non-zero coefficients in the regularized fit.  The
            refitted model is not regularized.
        **kwargs
            Additional keyword arguments that contain information used when
            constructing a model using the formula interface.

        Returns
        -------
        statsmodels.base.elastic_net.RegularizedResults
            The regularized results.

        Notes
        -----
        The elastic net uses a combination of L1 and L2 penalties.
        The implementation closely follows the glmnet package in R.

        The function that is minimized is:

        .. math::

            0.5*RSS/n + alpha*((1-L1\_wt)*|params|_2^2/2 + L1\_wt*|params|_1)

        where RSS is the usual regression sum of squares, n is the
        sample size, and :math:`|*|_1` and :math:`|*|_2` are the L1 and L2
        norms.

        For WLS and GLS, the RSS is calculated using the whitened endog and
        exog data.

        Post-estimation results are based on the same data used to
        select variables, hence may be subject to overfitting biases.

        The elastic_net method uses the following keyword arguments:

        maxiter : int
            Maximum number of iterations
        cnvrg_tol : float
            Convergence threshold for line searches
        zero_tol : float
            Coefficients below this threshold are treated as zero.

        The square root lasso approach is a variation of the Lasso
        that is largely self-tuning (the optimal tuning parameter
        does not depend on the standard deviation of the regression
        errors).  If the errors are Gaussian, the tuning parameter
        can be taken to be

        alpha = 1.1 * np.sqrt(n) * norm.ppf(1 - 0.05 / (2 * p))

        where n is the sample size and p is the number of predictors.

        The square root lasso uses the following keyword arguments:

        zero_tol : float
            Coefficients below this threshold are treated as zero.

        The cvxopt module is required to estimate model using the square root
        lasso.

        References
        ----------
        .. [*] Friedman, Hastie, Tibshirani (2008).  Regularization paths for
           generalized linear models via coordinate descent.  Journal of
           Statistical Software 33(1), 1-22 Feb 2010.

        .. [*] A Belloni, V Chernozhukov, L Wang (2011).  Square-root Lasso:
           pivotal recovery of sparse signals via conic programming.
           Biometrika 98(4), 791-806. https://arxiv.org/pdf/1009.5689.pdf
        c                8   | dS t          j        |                                           } | j        dk    rt          j        | |          } | j        dk    r<| j        |fk    rt          d|d|d|          dt          j        |           z  }n| j        ||fk    rt          d|d|d|          t          t          | d	          dd
          \  }}|dk    rt           j
                            d          |dk     rt          d|z            | |fS )z
    Returns sigma (matrix, nobs by nobs) for GLS and the inverse of its
    Cholesky decomposition.  Handles dimensions and checks integrity.
    If sigma is None, returns None, None. Otherwise returns sigma,
    cholsigmainv.
    NNNr   r   z%Sigma must be a scalar, 1d of length z or a 2d array of shape z x T)lower)r"   overwrite_cz8Cholesky decomposition of sigma yields a singular matrixz#Invalid input to dtrtri (info = %d))npasarraysqueezendimrepeatshape
ValueErrorsqrtr   r   linalgLinAlgError)sigmanobscholsigmainvinfos       c/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/regression/linear_model.py
_get_sigmar3      sd    }zJu%%''EzQ	%&&zQ;4'!!*9=tttTTK L L L';4,&&*9=tttTTK L L L#HU$$?$?$?*.DB B Bd!88)'' )C D D DAXXBTIJJJ,    c                       e Zd ZdZ fdZd Zed             Zej        d             Zed             Z	e	j        d             Z	d Z
	 	 	 	 dddZddZddZ xZS )RegressionModelzp
    Base class for linear regression models. Should not be directly called.

    Intended for subclassing.
    c                     t                      j        ||fi | d | _        | j                            g d           d S )N)
pinv_wexogwendogwexogweights)super__init__r8   
_data_attrextend)selfendogexogkwargs	__class__s       r2   r=   zRegressionModel.__init__   sN    //////3KKKLLLLLr4   c                    |                      | j                  | _        |                      | j                  | _        t          | j        j        d                   | _        d| _        d| _	        d| _
        dS )zInitialize model components.r   N)whitenrB   r:   rA   r9   floatr)   r/   	_df_model	_df_residrankr@   s    r2   
initializezRegressionModel.initialize   s^    [[++
kk$*--$**1-..				r4   c                    | j         Q| j        )t          j                            | j                  | _        t          | j        | j        z
            | _         | j         S )z
        The model degree of freedom.

        The dof is defined as the rank of the regressor matrix minus 1 if a
        constant is included.
        )rH   rJ   r$   r,   matrix_rankrB   rG   
k_constantrK   s    r2   df_modelzRegressionModel.df_model   sM     >!y I11$)<<	"49t#>??DN~r4   c                    || _         d S N)rH   r@   values     r2   rP   zRegressionModel.df_model       r4   c                    | j         D| j        )t          j                            | j                  | _        | j        | j        z
  | _         | j         S )z
        The residual degree of freedom.

        The dof is defined as the number of observations minus the rank of
        the regressor matrix.
        )rI   rJ   r$   r,   rN   rB   r/   rK   s    r2   df_residzRegressionModel.df_resid   sE     >!y I11$)<<	!Y2DN~r4   c                    || _         d S rR   )rI   rS   s     r2   rW   zRegressionModel.df_resid   rU   r4   c                     t          d          )z
        Whiten method that must be overwritten by individual models.

        Parameters
        ----------
        x : array_like
            Data to be whitened.
        zSubclasses must implement.)NotImplementedErrorr@   xs     r2   rF   zRegressionModel.whiten   s     "">???r4   pinv	nonrobustNmethodLiteral['pinv', 'qr']cov_typenLiteral['nonrobust', 'fixed scale', 'HC0', 'HC1', 'HC2', 'HC3', 'HAC', 'hac-panel', 'hac-groupsum', 'cluster']use_tbool | Nonec                $   |dk    rt          | d          r t          | d          rt          | d          st          | j                  \  | _        }t	          j        | j        t	          j        | j                            | _        || _        t          j	        
                    t	          j        |                    | _        t	          j        | j        | j                  }n|dk    r{t          | d          r0t          | d          r t          | d          rt          | d          st          j	                            | j                  \  }}	||	c| _        | _        t          j	                            t	          j        |	j        |	                    | _        t          j	                            |	dd          | _        t          j	        
                    |	          | _        n| j        | j        }	}t          j	                            | j                  | _        t	          j        |j        | j                  x| _        }
t          j	                            |	|
          }nt/          d	          | j        !t3          | j        | j        z
            | _        | j        | j        | j        z
  | _        t=          | t>                    rtA          | || j        |||          }ntC          | |f| j        |||d|}tE          |          S )a  
        Full fit of the model.

        The results include an estimate of covariance matrix, (whitened)
        residuals and an estimate of scale.

        Parameters
        ----------
        method : str, optional
            Can be "pinv", "qr".  "pinv" uses the Moore-Penrose pseudoinverse
            to solve the least squares problem. "qr" uses the QR
            factorization.
        cov_type : str, optional
            See `regression.linear_model.RegressionResults` for a description
            of the available covariance estimators.
        cov_kwds : list or None, optional
            See `linear_model.RegressionResults.get_robustcov_results` for a
            description required keywords for alternative covariance
            estimators.
        use_t : bool, optional
            Flag indicating to use the Student's t distribution when computing
            p-values.  Default behavior depends on cov_type. See
            `linear_model.RegressionResults.get_robustcov_results` for
            implementation details.
        **kwargs
            Additional keyword arguments that contain information used when
            constructing a model using the formula interface.

        Returns
        -------
        RegressionResults
            The model estimation results.

        See Also
        --------
        RegressionResults
            The results container.
        RegressionResults.get_robustcov_results
            A method to change the covariance estimator used when fitting the
            model.

        Notes
        -----
        The fit method uses the pseudoinverse of the design/exogenous variables
        to solve the least squares minimization.
        r]   r8   normalized_cov_paramsrJ   qrexog_Qexog_Rr   zmethod has to be "pinv" or "qr"N)rf   ra   cov_kwdsrc   )#hasattrr   r:   r8   r$   dot	transposerf   wexog_singular_valuesr,   rN   diagrJ   r9   rg   rh   ri   invTsvdr]   effectssolver*   rH   rG   rO   rI   r/   rW   
isinstancer   
OLSResultsRegressionResultsr   )r@   r_   ra   rj   rc   rC   singular_valuesbetaQRrs   lfits               r2   fitzRegressionModel.fit  s   B VD,// 
LD"9::
LD&))
L 4A3L3L0-/VOR\$/%B%B.D .D* .=*I11"'/2J2JKK	6$/4;77DDt^^D(++ 0D(++0D"9::0 D&))0 y||DJ//1+,a(T[-/Y]]26!#q>>-J-J* .0Y]]1a-C-C*I11!44		{DK1 innTZ88DO%'VAC%=%==DL79??1g..DD>???>!"49t#>??DN>! I	1DMdC   
	d&*&@!HEC C CDD
 %d&*&@!HE  	 D
 (---r4   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
        -------
        array_like
            An array of fitted values.

        Notes
        -----
        If the model has not yet been fit, params is not optional.
        )rB   r$   rl   )r@   paramsrB   s      r2   predictzRegressionModel.predict  s"    . <9DvdF###r4   c                    |                      ||          }|ddlm} |} ||t          j        |                    }|S )a  
        Construct a random number generator for the predictive distribution.

        Parameters
        ----------
        params : array_like
            The model parameters (regression coefficients).
        scale : scalar
            The variance parameter.
        exog : array_like
            The predictor variable matrix.
        dist_class : class
            A random number generator class.  Must take 'loc' and 'scale'
            as arguments and return a random number generator implementing
            an ``rvs`` method for simulating random values. Defaults to normal.

        Returns
        -------
        gen
            Frozen random number generator object with mean and variance
            determined by the fitted linear model.  Use the ``rvs`` method
            to generate random values.

        Notes
        -----
        Due to the behavior of ``scipy.stats.distributions objects``,
        the returned random number generator must be called with
        ``gen.rvs(n)`` where ``n`` is the number of observations in
        the data set used to fit the model.  If any other value is
        used for ``n``, misleading results will be produced.
        Nr   )norm)locscale)r   scipy.stats.distributionsr   r$   r+   )r@   r   r   rB   
dist_classr}   r   gens           r2   get_distributionz RegressionModel.get_distribution  sV    @ ll64((666666JjS777
r4   )r]   r^   NN)r_   r`   ra   rb   rc   rd   rR   r!   )__name__
__module____qualname____doc__r=   rL   propertyrP   setterrW   rF   r}   r   r   __classcell__rD   s   @r2   r6   r6      s/        
M M M M M
	 	 	   X _  _   X _  _	@ 	@ 	@ -3 !%!v. v. v. v. v.p$ $ $ $8% % % % % % % %r4   r6   c                       e Zd Zd                    ej        ej        ej        z             Zd fd	Z	d Z
d Zdd	Z ee          	 	 	 dd            Z xZS )r   a
  
    Generalized Least Squares

    {params}
    sigma : scalar or array
        The array or scalar `sigma` is the weighting matrix of the covariance.
        The default is None for no scaling.  If `sigma` is a scalar, it is
        assumed that `sigma` is an n x n diagonal matrix with the given
        scalar, `sigma` as the value of each diagonal element.  If `sigma`
        is an n-length vector, then `sigma` is assumed to be a diagonal
        matrix with the given `sigma` on the diagonal.  This should be the
        same as WLS.
    {extra_params}

    Attributes
    ----------
    pinv_wexog : ndarray
        `pinv_wexog` is the p x n Moore-Penrose pseudoinverse of `wexog`.
    cholsimgainv : ndarray
        The transpose of the Cholesky decomposition of the pseudoinverse.
    df_model : float
        p - 1, where p is the number of regressors including the intercept.
        of freedom.
    df_resid : float
        Number of observations n less the number of parameters p.
    llf : float
        The value of the likelihood function of the fitted model.
    nobs : float
        The number of observations n.
    normalized_cov_params : ndarray
        p x p array :math:`(X^{{T}}\Sigma^{{-1}}X)^{{-1}}`
    results : RegressionResults instance
        A property that returns the RegressionResults class if fit.
    sigma : ndarray
        `sigma` is the n x n covariance structure of the error terms.
    wexog : ndarray
        Design matrix whitened by `cholsigmainv`
    wendog : ndarray
        Response variable whitened by `cholsigmainv`

    See Also
    --------
    WLS : Fit a linear model using Weighted Least Squares.
    OLS : Fit a linear model using Ordinary Least Squares.

    Notes
    -----
    If sigma is a function of the data making one of the regressors
    a constant, then the current postestimation statistics will not be correct.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> data = sm.datasets.longley.load()
    >>> data.exog = sm.add_constant(data.exog)
    >>> ols_resid = sm.OLS(data.endog, data.exog).fit().resid
    >>> res_fit = sm.OLS(ols_resid[1:], ols_resid[:-1]).fit()
    >>> rho = res_fit.params

    `rho` is a consistent estimator of the correlation of the residuals from
    an OLS fit of the longley data.  It is assumed that this is the true rho
    of the AR process data.

    >>> from scipy.linalg import toeplitz
    >>> order = toeplitz(np.arange(16))
    >>> sigma = rho**order

    `sigma` is an n x n matrix of the autocorrelation structure of the
    data.

    >>> gls_model = sm.GLS(data.endog, data.exog, sigma=sigma)
    >>> gls_results = gls_model.fit()
    >>> print(gls_results.summary())
    r   extra_paramsNnonec                   t          |           t          u r|                     |           t          |t	          |                    \  }} t                      j        ||f||||d| | j                            ddg           d S )N)missinghasconstr.   r0   r.   r0   )	typer   _check_kwargsr3   lenr<   r=   r>   r?   )	r@   rA   rB   r.   r   r   rC   r0   rD   s	           r2   r=   zGLS.__init__  s    ::v&&& )E

;;| 	Gg+35/;	G 	G?E	G 	G 	G
 	899999r4   c                   t          j        |          }| j        | j        j        dk    r|S | j        j        dk    r)|j        dk    r
|| j        z  S || j        dddf         z  S t          j        | j        |          S )aG  
        GLS whiten method.

        Parameters
        ----------
        x : array_like
            Data to be whitened.

        Returns
        -------
        ndarray
            The value np.dot(cholsigmainv,X).

        See Also
        --------
        GLS : Fit a linear model using Generalized Least Squares.
        N r   )r$   r%   r.   r)   r'   r0   rl   r[   s     r2   rF   z
GLS.whiten  s    $ JqMM:!1R!7!7HZ_!!v{{4,,,4,QQQW5556$+Q///r4   c                *   | j         dz  }t          j        | j        t          j        | j        |          z
  dz  d          }t          j        |           |z  }|dt          j        t          j        |z            z   |z  z  }t          j        | j	                  rt| j	        j
        dk    r3t          j                            | j	                  }|d|d         z  z  }n1|dt          j        t          j        | j	                            z  z  }|S )aU  
        Compute the value of the Gaussian log-likelihood function at params.

        Given the whitened design matrix, the log-likelihood is evaluated
        at the parameter vector `params` for the dependent variable `endog`.

        Parameters
        ----------
        params : array_like
            The model parameters.

        Returns
        -------
        float
            The value of the log-likelihood function for a GLS Model.

        Notes
        -----
        The log-likelihood function for the normal distribution is

        .. math:: -\frac{n}{2}\log\left(\left(Y-\hat{Y}\right)^{\prime}
                   \left(Y-\hat{Y}\right)\right)
                  -\frac{n}{2}\left(1+\log\left(\frac{2\pi}{n}\right)\right)
                  -\frac{1}{2}\log\left(\left|\Sigma\right|\right)

        Y and Y-hat are whitened.
               @   r   axisr         ?)r/   r$   sumr9   rl   r:   logpianyr.   r'   r,   slogdet)r@   r   nobs2SSRllfdets         r2   loglikezGLS.loglike<  s    : 	CfdkBF4:v$>$>>BKKKvc{{lU""&u%%%u,,6$* 	6z!##i''
33r#a&y s26"&"4"45555
r4   Tc                    | j         | j         j        dk    r$t          j        | j        j        d                   S | j         j        dk    r| j        S t          j        | j                  S )a  
        Compute weights for calculating Hessian.

        Parameters
        ----------
        params : ndarray
            The parameter at which Hessian is evaluated.
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.
        observed : bool
            If True, then the observed Hessian is returned. If false then the
            expected information matrix is returned.

        Returns
        -------
        ndarray
            A 1d weight vector used in the calculation of the Hessian.
            The hessian is obtained by `(exog.T * hessian_factor).dot(exog)`.
        Nr   r   r   )r.   r)   r$   onesrB   r'   r0   ro   r@   r   r   observeds       r2   hessian_factorzGLS.hessian_factorg  s_    . :!1R!7!7749?1-...Z_!!$$74,---r4   elastic_net              ?Fc           
         t          j        |          st          j        |          }| j        | j        j        dk    rt          j        | j                  }n'| j        j        dk    r| j        }nt          d          |t          j        d|z            z  t          | j	                  z  } t          | j        | j                  j        d||||||d|}	ddlm}
m}  |
| |	j                  } ||          S )Nr   r   zsigma should be 1-dim or 2-dimr_   alphaL1_wtstart_paramsprofile_scalerefitr   RegularizedResultsRegularizedResultsWrapperr   )r$   isscalarr%   r.   r'   ro   r*   r   r   rA   r   r9   r:   fit_regularizedstatsmodels.base.elastic_netr   r   r   )r@   r_   r   r   r   r   r   rC   var_obsrsltr   r   rrslts                r2   r   zGLS.fit_regularized  s3    {5!! 	&Ju%%E :!z!##'$*--A%%* !ABBBBF1w;///#dj//AE;s4;
++; #%'# #
 "# #	
 	
 	
 	
 	
 	
 	
 	
 #"455((///r4   Nr   NNTr   r   r   NFFr   r   r   formatbase_model_params_doc_missing_param_doc_extra_param_docr   r=   rF   r   r   r   _fit_regularized_docr   r   r   s   @r2   r   r     s        IR 	d,/$2GG 	 	I 	IS X: : : : : :0 0 0:) ) )V. . . .< X"##:<CH#0 0 0 $#0 0 0 0 0r4   r   c                       e Zd Zd                    ej        ej        ej        z             Zd fd	Z	d Z
d Zdd
Z ee          	 	 	 dd            Z xZS )r   ai  
    Weighted Least Squares

    The weights are presumed to be (proportional to) the inverse of
    the variance of the observations.  That is, if the variables are
    to be transformed by 1/sqrt(W) you must supply weights = 1/W.

    {params}
    weights : array_like, optional
        A 1d array of weights.  If you supply 1/W then the variables are
        pre- multiplied by 1/sqrt(W).  If no weights are supplied the
        default value is 1 and WLS results are the same as OLS.
    {extra_params}

    Attributes
    ----------
    weights : ndarray
        The stored weights supplied as an argument.

    See Also
    --------
    GLS : Fit a linear model using Generalized Least Squares.
    OLS : Fit a linear model using Ordinary Least Squares.

    Notes
    -----
    If the weights are a function of the data, then the post estimation
    statistics such as fvalue and mse_model might not be correct, as the
    package does not yet support no-constant regression.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> Y = [1,3,4,5,2,3,4]
    >>> X = range(1,8)
    >>> X = sm.add_constant(X)
    >>> wls_model = sm.WLS(Y,X, weights=list(range(1,8)))
    >>> results = wls_model.fit()
    >>> results.params
    array([ 2.91666667,  0.0952381 ])
    >>> results.tvalues
    array([ 2.0652652 ,  0.35684428])
    >>> print(results.t_test([1, 0]))
    <T test: effect=array([ 2.91666667]), sd=array([[ 1.41224801]]),
     t=array([[ 2.0652652]]), p=array([[ 0.04690139]]), df_denom=5>
    >>> print(results.f_test([0, 1]))
    <F test: F=array([[ 0.12733784]]), p=[[ 0.73577409]], df_denom=5, df_num=1>
    r   r   r   Nc                   t          |           t          u r|                     |           t          j        |          }|j        dk    r]|dk    r5d|v r1|d         )t          j        |t          |d                             }n"t          j        |t          |                    }t          |          dk    r(t          j        |                                g          }n|                                } t                      j
        ||f|||d| | j        j        d         }| j        }|j        |k    r |j        d         |k    rt          d          d S d S )Nr   dropmissing_idxr   )r   r;   r   r   z/Weights must be scalar or same length as design)r   r   r   r$   arrayr)   r(   r   r&   r<   r=   rB   r;   sizer*   )	r@   rA   rB   r;   r   r   rC   r/   rD   s	           r2   r=   zWLS.__init__  sg   ::v&&&(7##=B6!!mv&=&==)5)GS1F-G-GHH)GSZZ88w<<1h 1 1233GGoo''G 	Pg*1H	P 	PHN	P 	P 	Pyq!,<4GM!$4$<$<NOOO  $<$<r4   c                    t          j        |          }|j        dk    r|t          j        | j                  z  S |j        dk    r&t          j        | j                  dddf         |z  S dS )a  
        Whitener for WLS model, multiplies each column by sqrt(self.weights).

        Parameters
        ----------
        x : array_like
            Data to be whitened.

        Returns
        -------
        array_like
            The whitened values sqrt(weights)*X.
        r   r   N)r$   r%   r'   r+   r;   r[   s     r2   rF   z
WLS.whiten  si     JqMM6Q;;rwt|,,,,Vq[[74<((D1A55 [r4   c                r   | j         dz  }t          j        | j        t          j        | j        |          z
  dz  d          }t          j        |           |z  }|dt          j        t          j        |z            z   |z  z  }|dt          j        t          j        | j                            z  z  }|S )a  
        Compute the value of the gaussian log-likelihood function at params.

        Given the whitened design matrix, the log-likelihood is evaluated
        at the parameter vector `params` for the dependent variable `Y`.

        Parameters
        ----------
        params : array_like
            The parameter estimates.

        Returns
        -------
        float
            The value of the log-likelihood function for a WLS Model.

        Notes
        -----
        .. math:: -\frac{n}{2}\log SSR
                  -\frac{n}{2}\left(1+\log\left(\frac{2\pi}{n}\right)\right)
                  +\frac{1}{2}\log\left(\left|W\right|\right)

        where :math:`W` is a diagonal weight matrix,
        :math:`\left|W\right|` is its determinant, and
        :math:`SSR=\left(Y-\hat{Y}\right)^\prime W \left(Y-\hat{Y}\right)` is
        the sum of the squared weighted residuals.
        r   r   r   r   r   r   )	r/   r$   r   r9   rl   r:   r   r   r;   )r@   r   r   r   r   s        r2   r   zWLS.loglike  s    8 	CfdkBF4:v$>$>>BKKKvc{{lU""&u%%%u,,sRVBF4<001111
r4   Tc                    | j         S )a  
        Compute the weights for calculating the Hessian.

        Parameters
        ----------
        params : ndarray
            The parameter at which Hessian is evaluated.
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.
        observed : bool
            If True, then the observed Hessian is returned. If false then the
            expected information matrix is returned.

        Returns
        -------
        ndarray
            A 1d weight vector used in the calculation of the Hessian.
            The hessian is obtained by `(exog.T * hessian_factor).dot(exog)`.
        r;   r   s       r2   r   zWLS.hessian_factor)  s    . |r4   r   r   Fc           
     T   t          j        |          st          j        |          }|t          j        | j                  z  t          | j                  z  } t          | j        | j                  j	        d||||||d|}ddl
m}	m}
  |	| |j                  } |
|          S )Nr   r   r   r   )r$   r   r%   r   r;   r   r   r9   r:   r   r   r   r   r   )r@   r_   r   r   r   r   r   rC   r   r   r   r   s               r2   r   zWLS.fit_regularizedB  s    
 {5!! 	&Ju%%E t|,,,s4</@/@@;s4;
++; #%'# #
 "# #	
 	
 	
 	
 	
 	
 	
 	
 #"455((///r4   )r   r   Nr   r   r   r   s   @r2   r   r     s        /^ 	d,/$2GG 	 	I 	I_ dP P P P P P06 6 6*! ! !F   2 X"##:<CH#0 0 0 $#0 0 0 0 0r4   r   c                       e Zd Zd                    ej        ej        ej        z             Zd fd	Z	ddZ
d ZddZd	 Zdd
ZddZ ee          	 	 	 dd            Zd Zd Z xZS )r   aL  
    Ordinary Least Squares

    {params}
    {extra_params}

    Attributes
    ----------
    weights : scalar
        Has an attribute weights = array(1.0) due to inheritance from WLS.

    See Also
    --------
    WLS : Fit a linear model using Weighted Least Squares.
    GLS : Fit a linear model using Generalized Least Squares.

    Notes
    -----
    No constant is added by the model unless you are using formulas.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> import numpy as np
    >>> duncan_prestige = sm.datasets.get_rdataset("Duncan", "carData")
    >>> Y = duncan_prestige.data['income']
    >>> X = duncan_prestige.data['education']
    >>> X = sm.add_constant(X)
    >>> model = sm.OLS(Y,X)
    >>> results = model.fit()
    >>> results.params
    const        10.603498
    education     0.594859
    dtype: float64

    >>> results.tvalues
    const        2.039813
    education    6.892802
    dtype: float64

    >>> print(results.t_test([1, 0]))
                                 Test for Constraints
    ==============================================================================
                     coef    std err          t      P>|t|      [0.025      0.975]
    ------------------------------------------------------------------------------
    c0            10.6035      5.198      2.040      0.048       0.120      21.087
    ==============================================================================

    >>> print(results.f_test(np.identity(2)))
    <F test: F=array([[159.63031026]]), p=1.2607168903696672e-20,
     df_denom=43, df_num=2>
    r   Nr   c                (   d|v rd}t          j        |t                      t                      j        ||f||d| d| j        v r| j                            d           t          |           t          u r| 	                    |dg           d S d S )Nr;   zdWeights are not supported in OLS and will be ignoredAn exception will be raised in the next version.r   r   offset)
warningswarnr   r<   r=   
_init_keysremover   r   r   )r@   rA   rB   r   r   rC   msgrD   s          r2   r=   zOLS.__init__  s    FCM#|,,, 	?g+3	? 	?7=	? 	? 	?''O""9---::vz22222 r4   c                   | j         dz  }t          | j                   }| j        t          j        | j        |          z
  }t          | d          r
|| j        z  }t          j        |dz            }|D| t          j	        dt          j
        z            z  |t          j	        ||z            z  z
  |z
  }n1| t          j	        dt          j
        z  |z            z  |d|z  z  z
  }|S )a  
        The likelihood function for the OLS model.

        Parameters
        ----------
        params : array_like
            The coefficients with which to estimate the log-likelihood.
        scale : float or None
            If None, return the profile (concentrated) log likelihood
            (profiled over the scale parameter), else return the
            log-likelihood using the given scale value.

        Returns
        -------
        float
            The likelihood function evaluated at params.
        r   r   r   )r/   rG   rA   r$   rl   rB   rk   r   r   r   r   )r@   r   r   r   r/   residssrr   s           r2   r   zOLS.loglike  s    $ 	CTY
RVDIv6664"" 	!T[ EfUAX=&"%(5d
1C1C+CCeKCC &26!be)e"3444sagFC
r4   c                    |S )aO  
        OLS model whitener does nothing.

        Parameters
        ----------
        x : array_like
            Data to be whitened.

        Returns
        -------
        array_like
            The input array unmodified.

        See Also
        --------
        OLS : Fit a linear model using Ordinary Least Squares.
        r   r[   s     r2   rF   z
OLS.whiten  s	    $ r4   c                D   t          | d          s|                                  t          j        | j        |          }| j         |z   }|P| j        dt          j        | j        j        |          z  z
  }|t          j        ||          z  }| j         |z  |z  S | |z  S )a  
        Evaluate the score function at a given point.

        The score corresponds to the profile (concentrated)
        log-likelihood in which the scale parameter has been profiled
        out.

        Parameters
        ----------
        params : array_like
            The parameter vector at which the score function is
            computed.
        scale : float or None
            If None, return the profile (concentrated) log likelihood
            (profiled over the scale parameter), else return the
            log-likelihood using the given scale value.

        Returns
        -------
        ndarray
            The score vector.
        _wexog_xprodNr   )	rk   _setup_score_hessr$   rl   r   _wexog_x_wendog_wendog_xprodrq   r/   )r@   r   r   xtxbsdrr   s         r2   scorez	OLS.score  s    0 t^,, 	%""$$$vd'00##d*=$q26$2F2H28,: ,: (: :C26&$'''CI:#c))4%<r4   c                   | j         }t          | d          r
|| j        z
  }t          j        ||z            | _        t          j        | j        j        | j                  | _	        t          j        | j        j        |          | _
        d S )Nr   )r9   rk   r   r$   r   r   rl   r:   rq   r   r   )r@   ys     r2   r   zOLS._setup_score_hess  sr    K4"" 	 DKAVAE]]F4:<<<!vdjlA66r4   c                   t          | d          s|                                  t          j        | j        |          }|| j        dt          j        | j        j        |          z  z
  }|t          j        ||          z  }d| j        z  d|z  z   }| j        |z  t          j        ||          |dz  z  z
  }| j	         |z  dz  S | j         |z  S )a  
        Evaluate the Hessian function at a given point.

        Parameters
        ----------
        params : array_like
            The parameter vector at which the Hessian is computed.
        scale : float or None
            If None, return the profile (concentrated) log likelihood
            (profiled over the scale parameter), else return the
            log-likelihood using the given scale value.

        Returns
        -------
        ndarray
            The Hessian matrix.
        r   Nr   )
rk   r   r$   rl   r   r   r   rq   outerr/   )r@   r   r   r   r   ssrphms          r2   hessianzOLS.hessian  s    & t^,, 	%""$$$vd'00=$q26$2F2H28,: ,: (: :C26&$'''Cd**QtV3D"S(28D$+?+?#q&+HHBI:?Q&&%%--r4   Tc                J    t          j        | j        j        d                   S )a  
        Calculate the weights for the Hessian.

        Parameters
        ----------
        params : ndarray
            The parameter at which Hessian is evaluated.
        scale : None or float
            If scale is None, then the default scale will be calculated.
            Default scale is defined by `self.scaletype` and set in fit.
            If scale is not None, then it is used as a fixed scale.
        observed : bool
            If True, then the observed Hessian is returned. If false then the
            expected information matrix is returned.

        Returns
        -------
        ndarray
            A 1d weight vector used in the calculation of the Hessian.
            The hessian is obtained by `(exog.T * hessian_factor).dot(exog)`.
        r   )r$   r   rB   r)   r   s       r2   r   zOLS.hessian_factor%  s    . wtyq)***r4   r   r   r   Fc                ~   |dvrd|z  }t          |          dddd}	|	                    |           |dk    r<dd	lm}
m} |                     |||	d
                   } |
| |          } ||          S ddlm} |dk    r|                     |          S |ri }i }i }nddi}ddi}ddi} || f||||||||dd	|	S )N)r   
sqrt_lassoz'Unknown method '%s' for fit_regularized2   绽|=g:0yE>)maxiter	cnvrg_tolzero_tolr   r   r   r   )fit_elasticnetr   r   F)	r_   r   r   r   loglike_kwds
score_kwds	hess_kwdsr   
check_step)r*   updater   r   r   _sqrt_lassor   
_fit_ridge)r@   r_   r   r   r   r   r   rC   r   defaultsr   r   r   resultsr   r   r  r  s                     r2   r   zOLS.fit_regularized>  si    666;fDCS//! !# $& &\!!        %%eUHZ4HIIF((v66G,,W555??????A::??5)))
  	%LJII#Q<L!1J !I~d 	*6$)$)+7+7)3(1$)).	* 	* !)	* 	* 		*r4   c                   	 dd l }n# t          $ r d}t          |          w xY wt          | j                  }| j        j        d         }|                    dd|z  dz   df          }|                    d|dz   df          }	|                    | j        |df          |	dd df<   |                    g g g d|z  dz   d|z  dz   f          }
t          dd|z  dz             D ]	}d|
||f<   
|                    d|dz   d|z  dz   f          }d|d<   | j        |dd d|dz   f<   | j         |dd |dz   d f<   |                    ||z  d|z  dz   df          }dt          j        |          z  |d<   ddl m} d	|j        d
<   |                    ||
||g|	g          }t          j        |d                   j        }|d|dz            }||dz   d          }||z
  }|s|S t          j        t          j        |          |k              }t'          | j        | j        d d |f                                                   }|dz  }|j        ||<   |S )Nr   z-sqrt_lasso fitting requires the cvxopt moduler   r   r   )r   r   )solversFshow_progress)GlhlGqhqr\   )cvxoptImportErrorr*   r   rA   rB   r)   matrixspmatrixranger$   r+   r  optionssocpr%   flatflatnonzeroabsr   r}   r   )r@   r   r   r   r  r   nph0h1G0iG1cr  r   r\   bpbnr   iirfrs                         r2   r  zOLS._sqrt_lassor  s   	"MMMM 	" 	" 	"ACS//!	" 
OOIOA]]2!Aqz**]]2!Qx((MM$*q!f55122q5	__RR!A#a%1Q88q!A#a% 	 	ABq!tHH]]2!QqSU|,,4	122q1u9	z122qstt8MM%!)acAgq\22271::~!""""""+0(||A""|>>JtCy!!&q1uXqsttWb 	M^BF6NNX566$*di2.//3355!Zr
s    #c                   t           j                            | j        d          \  }}}|j        }t          j        |j        | j                  |z  }||z  }t          j        |          r(||| j        z  z   }||z  }	t          j        ||	          }	nt          j	        |          }| j        t          j        ||dddf         |z            z  }
t          j
        |
          |z   }t          j        |
|           t           j                            |
|          }t          j        ||          }	ddlm}  || |	          S )a  
        Fit a linear model using ridge regression.

        Parameters
        ----------
        alpha : scalar or array_like
            The penalty weight.  If a scalar, the same penalty weight
            applies to all variables in the model.  If a vector, it
            must have the same length as `params`, and contains a
            penalty weight for each coefficient.

        Notes
        -----
        Equivalent to fit_regularized with L1_wt = 0 (but implemented
        more efficiently).
        r   N)r   )r$   r,   rr   rB   rq   rl   rA   r   r/   r%   ro   fill_diagonalrt   r   r   )r@   r   usvtvqs2sdr   vtavdrr   s                 r2   r  zOLS._fit_ridge  s0   $ 9==A..1bDF13
##a'U;u 
	"edi''BVFVAv&&FFJu%%E9rvb%4.1*<===D"AT1%%%	a((AVAq\\FCCCCCC!!$///r4   r   rR   r   r   )r   r   r   r   r   r   r   r   r   r=   r   rF   r   r   r   r   r   r   r   r  r  r   r   s   @r2   r   r   \  s;       3f 	d,/$2GG 	 	I 	Ig l3 3 3 3 3 3   @  ($  $  $  $ L7 7 7 .  .  .  .D+ + + +2 X"##:<CH#1* 1* 1* $#1*f+ + +Z#0 #0 #0 #0 #0 #0 #0r4   r   c                       e Zd Zd                    ej        ej        ej        z             Zd fd	Z	dd	Z
d
 Z xZS )r   a  
    Generalized Least Squares with AR covariance structure

    {params}
    rho : int
        The order of the autoregressive covariance.
    {extra_params}

    Notes
    -----
    GLSAR is considered to be experimental.
    The linear autoregressive process of order p--AR(p)--is defined as:
    TODO

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> X = range(1,8)
    >>> X = sm.add_constant(X)
    >>> Y = [1,3,4,5,8,10,9]
    >>> model = sm.GLSAR(Y, X, rho=2)
    >>> for i in range(6):
    ...     results = model.fit()
    ...     print("AR coefficients: {{0}}".format(model.rho))
    ...     rho, sigma = sm.regression.yule_walker(results.resid,
    ...                                            order=model.order)
    ...     model = sm.GLSAR(Y, X, rho)
    ...
    AR coefficients: [ 0.  0.]
    AR coefficients: [-0.52571491 -0.84496178]
    AR coefficients: [-0.6104153  -0.86656458]
    AR coefficients: [-0.60439494 -0.857867  ]
    AR coefficients: [-0.6048218  -0.85846157]
    AR coefficients: [-0.60479146 -0.85841922]
    >>> results.params
    array([-0.66661205,  1.60850853])
    >>> results.tvalues
    array([ -2.10304127,  21.8047269 ])
    >>> print(results.t_test([1, 0]))
    <T test: effect=array([-0.66661205]), sd=array([[ 0.31697526]]),
     t=array([[-2.10304127]]), p=array([[ 0.06309969]]), df_denom=3>
    >>> print(results.f_test(np.identity(2)))
    <F test: F=array([[ 1815.23061844]]), p=[[ 0.00002372]],
     df_denom=3, df_num=2>

    Or, equivalently

    >>> model2 = sm.GLSAR(Y, X, rho=2)
    >>> res = model2.iterative_fit(maxiter=6)
    >>> model2.rho
    array([-0.60479146, -0.85841922])
    r   Nr   r   c                   t          |t          t          j        f          r>t          |          | _        t          j        | j        t          j                  | _        nt          j        t          j	        |                    | _        t          | j        j                  dvrt          d          | j        j        dk    rd| j        _        | j        j        d         | _        |? t                      j        |t          j        |j        d         df          f|d d| d S  t                      j        ||fd|i| d S )	N)r   r   z*AR parameters must be a scalar or a vectorr   )r   r   r   r   r   )ru   intr$   integerorderzerosfloat64rhor&   r%   r   r)   r*   r<   r=   r   )r@   rA   rB   r:  r   r   rC   rD   s          r2   r=   zGLSAR.__init__  sF    cC,-- 		+SDJx
BJ77DHHz"*S//22DH48>""&00 !MNNNx~##!%*DJ< EGGUBGU[^Q,?$@$@ 207$2 2*02 2 2 2 2 EGGUD 2 2' 2*02 2 2 2 2r4      -C6?c                \   d}d}g | j         gd}t          |dz
            D ]}t          | d          r| `|                                  |                                 }|d                             |j                   |dk    r|j        }nTt          j	        t          j
        ||j        z
            t          j
        |          z            }	|	|k     rd} nM|j        }t          |j        | j        d	
          \  | _         }
|d                             | j                    |s,|dk    r&t          | d          r| `|                                   | j        dd|i|}|dz   |_        |s5|j        d                             |j                   |xj        dz  c_        ||_        |S )a  
        Perform an iterative two-stage procedure to estimate a GLS model.

        The model is assumed to have AR(p) errors, AR(p) parameters and
        regression coefficients are estimated iteratively.

        Parameters
        ----------
        maxiter : int, optional
            The number of iterations.
        rtol : float, optional
            Relative tolerance between estimated coefficients to stop the
            estimation.  Stops if max(abs(last - current) / abs(last)) < rtol.
        **kwargs
            Additional keyword arguments passed to `fit`.

        Returns
        -------
        RegressionResults
            The results computed using an iterative fit.
        Fr
  )r   r:  r   r8   r   r   TN)r7  dfr:  historyr   )r:  r  rk   r8   rL   r}   appendr   r$   maxr  yule_walkerr   r7  iterr?  	converged)r@   r   rtolrC   rD  r   r?  r  lastdiff_s              r2   iterative_fitzGLSAR.iterative_fit  s   . 	
33w{## 	, 	,At\** $OOOhhjjGH$$W^444Avv~vbfTGN%:;;bfTllJKK$;; $IE~%gm,0J4A A AKDHaEN!!$(++++  	Wq[[t\** $OOO $(5575f551u 	OH%,,W^<<<LLALL%r4   c                   t          j        |t           j                  }|                                }t	          | j                  D ]4}||dz   d         | j        |         |d|dz             z  z
  ||dz   d<   5|| j        d         S )aR  
        Whiten a series of columns according to an AR(p) covariance structure.

        Whitening using this method drops the initial p observations.

        Parameters
        ----------
        x : array_like
            The data to be whitened.

        Returns
        -------
        ndarray
            The whitened data.
        r   Nr   )r$   r%   r9  copyr  r7  r:  )r@   r\   _xr   s       r2   rF   zGLSAR.whitenV  s    " Jq"*%%VVXX tz"" 	F 	FAq1uhh<$(1+!a!eH**EEBAxxLL$*++r4   )Nr   r   N)r;  r<  )r   r   r   r   r   r   r   r   r   r=   rI  rF   r   r   s   @r2   r   r     s        3f 	d,/$2GG 	 	I 	Ig n2 2 2 2 2 20? ? ? ?B      r4   r   adjustedFTc                `   t          |dd          }|dk    rt          j        dt                     d}|dvrt	          d          t          j        | t
          j        	          } |r9| j        j	        st          j
        | d
          } | |                                 z  } |p| j        d         }|dk    }| j        dk    r | j        d         dk    rt	          d          t          j        |dz   t
          j                  }| dz                                  |z  |d<   t!          d|dz             D ]6}	| d|	          | |	d         z                                  ||	|z  z
  z  ||	<   7t#          |dd                   }
	 t
          j                            |
|dd                   }nx# t
          j        j        $ ra}dt+          |          v rEt          j        dt,                     t
          j                            |
          |dd         z  }n Y d}~nd}~ww xY w|d         |dd         |z                                  z
  }t          j        |          s|dk    rt          j        |          }nt
          j        }|r"||t
          j                            |
          fS ||fS )a  
    Estimate AR(p) parameters from a sequence using the Yule-Walker equations.

    Adjusted or maximum-likelihood estimator (mle)

    Parameters
    ----------
    x : array_like
        A 1d array.
    order : int, optional
        The order of the autoregressive process.  Default is 1.
    method : str, optional
       Method can be 'adjusted' or 'mle' and this determines
       denominator in estimate of autocorrelation function (ACF) at
       lag k. If 'mle', the denominator is n=X.shape[0], if 'adjusted'
       the denominator is n-k.  The default is adjusted.
    df : int, optional
       Specifies the degrees of freedom. If `df` is supplied, then it
       is assumed the X has `df` degrees of freedom rather than `n`.
       Default is None.
    inv : bool
        If inv is True the inverse of R is also returned.  Default is
        False.
    demean : bool
        True, the mean is subtracted from `X` before estimation.

    Returns
    -------
    rho : ndarray
        AR(p) coefficients computed using the Yule-Walker method.
    sigma : float
        The estimate of the residual standard deviation.

    See Also
    --------
    burg : Burg's AR estimator.

    Notes
    -----
    See https://en.wikipedia.org/wiki/Autoregressive_moving_average_model for
    further details.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> from statsmodels.datasets.sunspots import load
    >>> data = load()
    >>> rho, sigma = sm.regression.yule_walker(data.endog, order=4,
    ...                                        method="mle")

    >>> rho
    array([ 1.28310031, -0.45240924, -0.20770299,  0.04794365])
    >>> sigma
    16.808022730464351
    r_   )rM  unbiasedmle)r  rO  zunbiased is deprecated in factor of adjusted to reflect that the term is adjusting the sample size used in the autocovariance calculation rather than estimating an unbiased autocovariance. After release 0.13, using 'unbiased' will raise.rM  )rM  rP  z1ACF estimation method must be 'adjusted' or 'MLE')dtypeW)requirementsr   r   z,expecting a vector to estimate AR parametersr   Nr
  zSingular matrixzMatrix is singular. Using pinv.)r   r   r   FutureWarningr*   r$   r   r9  flags	writeablerequiremeanr)   r'   r8  r   r  r   r,   rt   r-   strr   r]   isnanr+   nanrp   )r\   r7  r_   r>  rp   demeanr  
adj_neededr2  kr{   r:  errsigmasqr.   s                  r2   rB  rB  p  s   z "A  F ? 	
 	
 	
 (((LMMM
"*%%%A w  	0
13///A	QVVXX
agajA :%JvzzagajAooGHHH
q"*%%AF<<>>AAaD1eAg > >!QB$!ABB%$$&&!a*n*<=!3B3Aiooa122''9    C((M;\JJJ)..##ae+CC CCCC daeCi__&&&G8G 1  
 E29==++++Ezs   (F- -H"AHH"c                ^   ddl m}m} t          j        t          j        |                     } | j        dk    rt          d          t          |          }|dk     rt          d          |r| | 	                                z
  }  || ||          \  }} ||          \  }}||d         fS )a  
    Compute Burg's AP(p) parameter estimator.

    Parameters
    ----------
    endog : array_like
        The endogenous variable.
    order : int, optional
        Order of the AR.  Default is 1.
    demean : bool, optional
        Flag indicating to subtract the mean from endog before estimation.

    Returns
    -------
    rho : ndarray
        The AR(p) coefficients computed using Burg's algorithm.
    sigma2 : float
        The estimate of the residual variance.

    See Also
    --------
    yule_walker : Estimate AR parameters using the Yule-Walker method.

    Notes
    -----
    AR model estimated includes a constant that is estimated using the sample
    mean (see [1]_). This value is not reported.

    References
    ----------
    .. [1] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
        and forecasting. Springer.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> from statsmodels.datasets.sunspots import load
    >>> data = load()
    >>> rho, sigma2 = sm.regression.linear_model.burg(data.endog, order=4)

    >>> rho
    array([ 1.30934186, -0.48086633, -0.20185982,  0.05501941])
    >>> sigma2
    271.2467306963966
    r   )levinson_durbin_pacf	pacf_burgr   z'endog must be 1-d or squeezable to 1-d.z&order must be an integer larger than 1)r\  r
  )
statsmodels.tsa.stattoolsrb  rc  r$   r&   r%   r'   r*   r5  rX  )	rA   r7  r\  rb  rc  pacfr.   arrH  s	            r2   burgrg    s    ^ JIIIIIIIJrz%(())EzQBCCCJJEqyyABBB %

$)E5888KD%  &&EBuRy=r4   c                  ~    e Zd ZdZi Z	 	 dA fd	ZdB 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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dCdZed             Zed             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* Z*dDd-Z+d. Z,dEd/Z-dFd1Z. e/e0j1        j                  	 	 dGd2            Z1	 	 	 	 	 dHdId<Z2	 	 	 	 	 dJdKd@Z3 xZ4S )Lrw   a  
    This class summarizes the fit of a linear regression model.

    It handles the output of contrasts, estimates of covariance, etc.

    Parameters
    ----------
    model : RegressionModel
        The regression model instance.
    params : ndarray
        The estimated parameters.
    normalized_cov_params : ndarray
        The normalized covariance parameters.
    scale : float
        The estimated scale of the residuals.
    cov_type : str
        The covariance estimator used in the results.
    cov_kwds : dict
        Additional keywords used in the covariance specification.
    use_t : bool
        Flag indicating to use the Student's t in inference.
    **kwargs
        Additional keyword arguments used to initialize the results.

    Attributes
    ----------
    pinv_wexog
        See model class docstring for implementation details.
    cov_type
        Parameter covariance estimator used for standard errors and t-stats.
    df_model
        Model degrees of freedom. The number of regressors `p`. Does not
        include the constant if one is present.
    df_resid
        Residual degrees of freedom. `n - p - 1`, if a constant is present.
        `n - p` if a constant is not included.
    het_scale
        adjusted squared residuals for heteroscedasticity robust standard
        errors. Is only available after `HC#_se` or `cov_HC#` is called.
        See HC#_se for more information.
    history
        Estimation history for iterative estimators.
    model
        A pointer to the model instance that called fit() or results.
    params
        The linear coefficients that minimize the least squares
        criterion.  This is usually called Beta for the classical
        linear model.
    Nr   r^   c                   t                                          ||||           i | _        t          |d          r|j        | _        nd | _        |j        | _        |j        | _        |dk    rd| _        ddi| _	        |d}|| _
        n2|i }d|v r|                    d          }	||	} | j        d|d|d| |D ]}
t          | |
||
                    d S )	Nrn   r^   descriptionzWStandard Errors assume that the covariance matrix of the errors is correctly specified.Trc   )ra   use_selfrc   r   )r<   r=   _cacherk   rn   _wexog_singular_valuesrP   rW   ra   rj   rc   popget_robustcov_resultssetattr)r@   modelr   rf   r   ra   rj   rc   rC   use_t_2keyrD   s              r2   r=   zRegressionResults.__init__U  s>   60%	9 	9 	9 5122 	/*/*ED''*.D'{""'DM  DM }DJJ(""",,w//=#E&D& @4-2@ @6>@ @ @ 	, 	,CD#vc{++++	, 	,r4   皙?c                N    t                                          ||          }|S )a8  
        Compute the confidence interval of the fitted parameters.

        Parameters
        ----------
        alpha : float, optional
            The `alpha` level for the confidence interval. The default
            `alpha` = .05 returns a 95% confidence interval.
        cols : array_like, optional
            Columns to include in returned confidence intervals.

        Returns
        -------
        array_like
            The confidence intervals.

        Notes
        -----
        The confidence interval is based on Student's t-distribution.
        )r   cols)r<   conf_int)r@   r   rv  cirD   s       r2   rw  zRegressionResults.conf_intz  s&    , WWE55	r4   c                J    t          | j        j        j        d                   S )zNumber of observations n.r   )rG   rq  r:   r)   rK   s    r2   r/   zRegressionResults.nobs  s     TZ%+A.///r4   c                V    | j                             | j        | j         j                  S )z:The predicted values for the original (unwhitened) design.)rq  r   r   rB   rK   s    r2   fittedvalueszRegressionResults.fittedvalues  s"     z!!$+tz???r4   c                p    | j         j        | j                             | j        | j         j                  z
  S )zX
        The residuals of the transformed/whitened regressand and regressor(s).
        )rq  r9   r   r   r:   rK   s    r2   wresidzRegressionResults.wresid  s6    
 z 4:#5#5K)$+ $+ + 	+r4   c                p    | j         j        | j                             | j        | j         j                  z
  S )zThe residuals of the model.)rq  rA   r   r   rB   rK   s    r2   r   zRegressionResults.resid  s5     z$*"4"4K#* #* * 	*r4   c                J    | j         }t          j        ||          | j        z  S )z
        A scale factor for the covariance matrix.

        The Default value is ssr/(n-p).  Note that the square root of `scale`
        is often called the standard error of the regression.
        )r}  r$   rl   rW   r@   r}  s     r2   r   zRegressionResults.scale  s$     vff%%55r4   c                :    | j         }t          j        ||          S )z$Sum of squared (whitened) residuals.)r}  r$   rl   r  s     r2   r   zRegressionResults.ssr  s     vff%%%r4   c                j   | j         }t          |dd          }t          |dd          }|=t          j        |j        |          }t          j        ||j        |z
  dz  z            S |t          j        |j                  }|                    |          }|j        	                    |          |	                    |          z  }|j        |z
  }|                    |          }t          j        |dz            S |j        |j        
                                z
  }t          j	        ||          S )z<The total (weighted) sum of squares centered about the mean.r;   Nr.   r   r   )rq  getattrr$   averagerA   r   	ones_likerF   r9   rl   rX  )r@   rq  r;   r.   rX  iotar_  centered_endogs           r2   centered_tsszRegressionResults.centered_tss  s    
%D11w--:ek7;;;D6'U[4%7!$;;<<<<,,D<<%%D<##D))DHHTNN:D+$C,,s##C6#q&>>!"\EL,=,=,?,??N6..999r4   c                D    | j         j        }t          j        ||          S )z
        Uncentered sum of squares.

        The sum of the squared values of the (whitened) endogenous response
        variable.
        )rq  r9   r$   rl   )r@   r9   s     r2   uncentered_tssz RegressionResults.uncentered_tss  s      "vff%%%r4   c                L    | j         r| j        | j        z
  S | j        | j        z
  S )z
        The explained sum of squares.

        If a constant is present, the centered total sum of squares minus the
        sum of squared residuals. If there is no constant, the uncentered total
        sum of squares is used.
        )rO   r  r   r  rK   s    r2   esszRegressionResults.ess  s.     ? 	2$tx//&11r4   c                X    | j         rd| j        | j        z  z
  S d| j        | j        z  z
  S )z
        R-squared of the model.

        This is defined here as 1 - `ssr`/`centered_tss` if the constant is
        included in the model and 1 - `ssr`/`uncentered_tss` if the constant is
        omitted.
        r   )rO   r   r  r  rK   s    r2   rsquaredzRegressionResults.rsquared  s8     ? 	4tx 1111tx 3333r4   c                l    dt          j        | j        | j        z
  | j                  d| j        z
  z  z
  S )z
        Adjusted R-squared.

        This is defined here as 1 - (`nobs`-1)/`df_resid` * (1-`rsquared`)
        if a constant is included and 1 - `nobs`/`df_resid` * (1-`rsquared`) if
        no constant is included.
        r   )r$   divider/   rO   rW   r  rK   s    r2   rsquared_adjzRegressionResults.rsquared_adj  s9     BIdi$/94=II4=(* + 	+r4   c                    t          j        | j        dk              r$t          j        | j        t           j                  S | j        | j        z  S )z~
        Mean squared error the model.

        The explained sum of squares divided by the model degrees of freedom.
        r   )r$   allrP   	full_liker  r[  rK   s    r2   	mse_modelzRegressionResults.mse_model  sB     6$-3&'' 	2<"&111x%%r4   c                    t          j        | j        dk              r$t          j        | j        t           j                  S | j        | j        z  S )z
        Mean squared error of the residuals.

        The sum of squared residuals divided by the residual degrees of
        freedom.
        r   )r$   r  rW   r  r   r[  rK   s    r2   	mse_residzRegressionResults.mse_resid  sB     6$-3&'' 	2<"&111x%%r4   c                    t          j        | j        | j        z   dk              r$t          j        | j        t           j                  S | j        r| j        | j        | j        z   z  S | j        | j        | j        z   z  S )z
        Total mean squared error.

        The uncentered total sum of squares divided by the number of
        observations.
        r   )	r$   r  rW   rP   r  r  r[  rO   r  rK   s    r2   	mse_totalzRegressionResults.mse_total  st     6$-$-/3677 	;< 126:::? 	I$(EFF&$-$-*GHHr4   c                   t          | d          r| j        dk    r| j        j        d         }t	          j        |          }| j        j        j        }| j        j        j	        dk    rQ|t          j
        S t          |          }|                    |           ||         }|j        dk    rt          j
        S |                     |          }t          |j                  | j        d<   t          |j                  S | j        | j        z  S )aa  
        F-statistic of the fully specified model.

        Calculated as the mean squared error of the model divided by the mean
        squared error of the residuals if the nonrobust covariance is used.
        Otherwise computed using a Wald-like quadratic form that tests whether
        all coefficients (excluding the constant) are zero.
        ra   r^   r   r   Nf_pvalue)rk   ra   rf   r)   r$   eyerq  data	const_idxrO   r[  r   rn  r   f_testrG   pvaluerl  fvaluer  r  )r@   k_paramsmatr  idxfts         r2   r  zRegressionResults.fvalue,  s     4$$ 	1+)E)E17:H&""C
1I
 z)Q..$6MX&&	"""#h8q==6MS!!B&+BI&6&6DK
#### >$.00r4   c                    | j         dk    r$t          j        | j        t          j                  S t
          j                            | j        | j         | j                  S )zThe p-value of the F-statistic.r   )	rP   r$   r  r  r[  r
   fsfrW   rK   s    r2   r  zRegressionResults.f_pvalueQ  sE     =A<RV444wzz$+t}dmDDDr4   c                r    t          j        t          j        |                                                     S )z/The standard errors of the parameter estimates.)r$   r+   ro   
cov_paramsrK   s    r2   bsezRegressionResults.bseY  s(     wrwt0011222r4   c                ,    |                      d          S )z
        Akaike's information criteria.

        For a model with a constant :math:`-2llf + 2(df\_model + 1)`. For a
        model without a constant :math:`-2llf + 2(df\_model)`.
        aicinfo_criteriarK   s    r2   r  zRegressionResults.aic^       !!%(((r4   c                ,    |                      d          S )z
        Bayes' information criteria.

        For a model with a constant :math:`-2llf + \log(n)(df\_model+1)`.
        For a model without a constant :math:`-2llf + \log(n)(df\_model)`.
        bicr  rK   s    r2   r  zRegressionResults.bich  r  r4   r   c                h   |                                 }| j        | j        z   |z   }|dk    rd| j        z  d|z  z   S |dk    r)d| j        z  t	          j        | j                  |z  z   }|S |dk    rddlm}  || j        | j        |          S |dk    rdd	lm	}  || j        | j        |          S d
S )a  Return an information criterion for the model.

        Parameters
        ----------
        crit : string
            One of 'aic', 'bic', 'aicc' or 'hqic'.
        dk_params : int or float
            Correction to the number of parameters used in the information
            criterion. By default, only mean parameters are included, the
            scale parameter is not included in the parameter count.
            Use ``dk_params=1`` to include scale in the parameter count.

        Returns
        -------
        Value of information criterion.

        References
        ----------
        Burnham KP, Anderson KR (2002). Model Selection and Multimodel
        Inference; Springer New York.
        r  r   r   r  aiccr   )r  hqic)r  N)
r"   rP   rO   r   r$   r   r/   statsmodels.tools.eval_measuresr  r  )r@   crit	dk_paramsr  r  r  r  s          r2   r  zRegressionResults.info_criteriar  s    , zz||=4?2Y>5===1x<//U]]TX+ty 1 1H <<CJV^^<<<<<<4$)X666V^^<<<<<<4$)X666 ^r4   c                    | j         | j         dz  }n3| j        j        }t          j                            |j        |z            }t          j        |          ddd         S )z@
        Return eigenvalues sorted in decreasing order.
        Nr   r
  )rm  rq  r:   r$   r,   eigvalshrq   sort)r@   eigvalswxs      r2   	eigenvalszRegressionResults.eigenvals  s\    
 &21Q6GG!Bi((33Gww"%%r4   c                V    | j         }t          j        |d         |d         z            S )aC  
        Return condition number of exogenous matrix.

        Calculated as ratio of largest to smallest singular value of the
        exogenous variables. This value is the same as the square root of
        the ratio of the largest to smallest eigenvalue of the inner-product
        of the exogenous variables.
        r   r
  )r  r$   r+   )r@   r  s     r2   condition_numberz"RegressionResults.condition_number  s(     .wwqz'"+-...r4   c                |    t          j        | j        j        |d d d f         | j        j        j        z            }|S rR   )r$   rl   rq  r8   rq   )r@   r   Hs      r2   _HCCMzRegressionResults._HCCM  s;    F4:(D>DJ$9$;;= =r4   c                0    t          j        d|||          S )Nzij,ik,kj->i)r$   einsum)r@   abs      r2   _abat_diagonalz RegressionResults._abat_diagonal  s    y1a000r4   c                X    | j         dz  | _        |                     | j                  }|S )zJ
        Heteroscedasticity robust covariance matrix. See HC0_se.
        r   )r}  	het_scaler  )r@   cov_HC0s     r2   r  zRegressionResults.cov_HC0  s)    
 a**T^,,r4   c                x    | j         | j        z  | j        dz  z  | _        |                     | j                  }|S )zJ
        Heteroscedasticity robust covariance matrix. See HC1_se.
        r   )r/   rW   r}  r  r  )r@   cov_HC1s     r2   r  zRegressionResults.cov_HC1  s7    
 DM2DKNC**T^,,r4   c                    | j         j        }|                     || j                  }| j        dz  d|z
  z  | _        |                     | j                  }|S )zJ
        Heteroscedasticity robust covariance matrix. See HC2_se.
        r   r   rq  r:   r  rf   r}  r  r  )r@   r:   hcov_HC2s       r2   r  zRegressionResults.cov_HC2  sT    
 
 t'ABBa1-**T^,,r4   c                    | j         j        }|                     || j                  }| j        d|z
  z  dz  | _        |                     | j                  }|S )zJ
        Heteroscedasticity robust covariance matrix. See HC3_se.
        r   r   r  )r@   r:   r  cov_HC3s       r2   r  zRegressionResults.cov_HC3  sU    
 
 t'ABB+Q/!3**T^,,r4   c                X    t          j        t          j        | j                            S )a}  
        White's (1980) heteroskedasticity robust standard errors.

        Notes
        -----
        Defined as sqrt(diag(X.T X)^(-1)X.T diag(e_i^(2)) X(X.T X)^(-1)
        where e_i = resid[i].

        When HC0_se or cov_HC0 is called the RegressionResults instance will
        then have another attribute `het_scale`, which is in this case is just
        resid**2.
        )r$   r+   ro   r  rK   s    r2   HC0_sezRegressionResults.HC0_se        wrwt|,,---r4   c                X    t          j        t          j        | j                            S )aT  
        MacKinnon and White's (1985) heteroskedasticity robust standard errors.

        Notes
        -----
        Defined as sqrt(diag(n/(n-p)*HC_0).

        When HC1_se or cov_HC1 is called the RegressionResults instance will
        then have another attribute `het_scale`, which is in this case is
        n/(n-p)*resid**2.
        )r$   r+   ro   r  rK   s    r2   HC1_sezRegressionResults.HC1_se  s      wrwt|,,---r4   c                X    t          j        t          j        | j                            S )a  
        MacKinnon and White's (1985) heteroskedasticity robust standard errors.

        Notes
        -----
        Defined as (X.T X)^(-1)X.T diag(e_i^(2)/(1-h_ii)) X(X.T X)^(-1)
        where h_ii = x_i(X.T X)^(-1)x_i.T

        When HC2_se or cov_HC2 is called the RegressionResults instance will
        then have another attribute `het_scale`, which is in this case is
        resid^(2)/(1-h_ii).
        )r$   r+   ro   r  rK   s    r2   HC2_sezRegressionResults.HC2_se  r  r4   c                X    t          j        t          j        | j                            S )a  
        MacKinnon and White's (1985) heteroskedasticity robust standard errors.

        Notes
        -----
        Defined as (X.T X)^(-1)X.T diag(e_i^(2)/(1-h_ii)^(2)) X(X.T X)^(-1)
        where h_ii = x_i(X.T X)^(-1)x_i.T.

        When HC3_se or cov_HC3 is called the RegressionResults instance will
        then have another attribute `het_scale`, which is in this case is
        resid^(2)/(1-h_ii)^(2).
        )r$   r+   ro   r  rK   s    r2   HC3_sezRegressionResults.HC3_se  r  r4   c                   t          | d          st          d          t          j        | j        j                  j        }t          j        | j                  d|z  | j	        j
                                        z  k     r!t          j        dt                     | j        S | j        t          j        | j                  z  S )z
        Residuals, normalized to have unit variance.

        Returns
        -------
        array_like
            The array `wresid` normalized by the sqrt of the scale to have
            unit variance.
        r   zMethod requires residuals.
   z5All residuals are 0, cannot compute normed residuals.)rk   r*   r$   finfor}  rQ  epsr+   r   rq  rA   rX  r   r   RuntimeWarning)r@   r  s     r2   resid_pearsonzRegressionResults.resid_pearson!  s     tW%% 	;9:::ht{())-74:cDJ,<,A,A,C,C!CCCMG   ;;!4!444r4   c                `   | j         j        |j         j        k    rdS | j         j        }|j         j        }||k    rdS |j         j        }| j        }||dddf         z  }t          j        t          j        |                    d          dz                      }t          j        |d          S )a  
        Parameters
        ----------
        restricted : Result instance
            The restricted model is assumed to be nested in the current
            model. The result instance of the restricted model is required to
            have two attributes, residual sum of squares, `ssr`, residual
            degrees of freedom, `df_resid`.

        Returns
        -------
        nested : bool
            True if nested, otherwise false

        Notes
        -----
        A most nests another model if the regressors in the smaller
        model are spanned by the regressors in the larger model and
        the regressand is identical.
        FNr   r   )	rq  r/   rJ   r:   r}  r$   r+   rX  allclose)r@   
restricted	full_rankrestricted_rankrestricted_exogfull_wresidscoresscore_l2s           r2   
_is_nestedzRegressionResults._is_nested:  s    , :?j.3335JO	$*/''5$*0k ;qqq$w#777276;;q>>Q#67788 {8Q'''r4   TFc                   ddl m} ddlmc m} |                     |          st          d          |j        }| j        j	        }||dddf         z  }| j
        }	| j        }
|j        }||
z
  }|                    d          }|r|| j        dddf         z  }d}|r"||                    d          dddf         z
  }t          | dd          }|dk    rCt          j        |d	z            }t          j        |j        |          |	z  } |||z            }n|d
v r' |t          j        |j        |          |	z            }nx|dk    r0| j        d         } ||                    ||          |	z            }nB|dk    r-| j        d         } ||                    ||                    }nt          d          |	||z  |j        z  z  }t          j                            ||          }|||fS )a@  
        Use Lagrange Multiplier test to test a set of linear restrictions.

        Parameters
        ----------
        restricted : Result instance
            The restricted model is assumed to be nested in the
            current model. The result instance of the restricted model
            is required to have two attributes, residual sum of
            squares, `ssr`, residual degrees of freedom, `df_resid`.
        demean : bool
            Flag indicating whether the demean the scores based on the
            residuals from the restricted model.  If True, the covariance of
            the scores are used and the LM test is identical to the large
            sample version of the LR test.
        use_lr : bool
            A flag indicating whether to estimate the covariance of the model
            scores using the unrestricted model. Setting the to True improves
            the power of the test.

        Returns
        -------
        lm_value : float
            The test statistic which has a chi2 distributed.
        p_value : float
            The p-value of the test statistic.
        df_diff : int
            The degrees of freedom of the restriction, i.e. difference in df
            between models.

        Notes
        -----
        The LM test examines whether the scores from the restricted model are
        0. If the null is true, and the restrictions are valid, then the
        parameters of the restricted model should be close to the minimum of
        the sum of squared errors, and so the scores should be close to zero,
        on average.
        r   )rp   Nz-Restricted model is not nested by full model.r   Fra   r^   r   HC0HC1HC2HC3HACmaxlagsclustergroupsz;Only nonrobust, HC, HAC and cluster are currently connected)numpy.linalgrp   %statsmodels.stats.sandwich_covariancer
   sandwich_covariancer  r*   r}  rq  r:   r/   rW   rX  r  r$   rl   rq   rj   S_hac_simpleS_crosssectionchi2r  )r@   r  r\  use_lrrp   swr}  r:   r  r  df_fulldf_restrdf_diffr*  ra   sigma2xpxs_invr  r  lm_valuep_values                         r2   compare_lm_testz!RegressionResults.compare_lm_testa  sP   N 	%$$$$$:::::::::z** 	NLMMM"
 4(I-&g%KKQK 	T[D11FF 	6fkk!nnT111W55F 4[99{""WVQY''F&%((1,CC%%EE555Cvx001455EEmI.GC881<==EE""]8,FC))&&99::EE 3 4 4 4 E	AC(*--'22'))r4   c                <   t          | dd          dk    }t          |dd          dk    }|s|rt          j        dt                     | j        }|j        }| j        }|j        }||z
  }||z
  |z  |z  |z  }	t          j                            |	||          }
|	|
|fS )a  
        Use F test to test whether restricted model is correct.

        Parameters
        ----------
        restricted : Result instance
            The restricted model is assumed to be nested in the
            current model. The result instance of the restricted model
            is required to have two attributes, residual sum of
            squares, `ssr`, residual degrees of freedom, `df_resid`.

        Returns
        -------
        f_value : float
            The test statistic which has an F distribution.
        p_value : float
            The p-value of the test statistic.
        df_diff : int
            The degrees of freedom of the restriction, i.e. difference in
            df between models.

        Notes
        -----
        See mailing list discussion October 17,

        This test compares the residual sum of squares of the two
        models.  This is not a valid test, if there is unspecified
        heteroscedasticity or correlation. This method will issue a
        warning if this is detected but still return the results under
        the assumption of homoscedasticity and no autocorrelation
        (sphericity).
        ra   r^   zQF test for comparison is likely invalid with robust covariance, proceeding anyway)	r  r   r   r   r   rW   r
   r  r  )r@   r  has_robust1has_robust2ssr_full	ssr_restrr  r   r  f_valuer  s              r2   compare_f_testz RegressionResults.compare_f_test  s    D dJ<<Kz:{CC"#  	.+ 	.M A,. . . 8N	-&g%x'72X=G'**Wgw77((r4   c                `   |r|                      |d          S t          | dd          dk    }t          |dd          dk    }|s|rt          j        dt                     | j        }|j        }| j        }|j        }||z
  }	d||z
  z  }
t          j        	                    |
|	          }|
||	fS )a  
        Likelihood ratio test to test whether restricted model is correct.

        Parameters
        ----------
        restricted : Result instance
            The restricted model is assumed to be nested in the current model.
            The result instance of the restricted model is required to have two
            attributes, residual sum of squares, `ssr`, residual degrees of
            freedom, `df_resid`.

        large_sample : bool
            Flag indicating whether to use a heteroskedasticity robust version
            of the LR test, which is a modified LM test.

        Returns
        -------
        lr_stat : float
            The likelihood ratio which is chisquare distributed with df_diff
            degrees of freedom.
        p_value : float
            The p-value of the test statistic.
        df_diff : int
            The degrees of freedom of the restriction, i.e. difference in df
            between models.

        Notes
        -----
        The exact likelihood ratio is valid for homoskedastic data,
        and is defined as

        .. math:: D=-2\log\left(\frac{\mathcal{L}_{null}}
           {\mathcal{L}_{alternative}}\right)

        where :math:`\mathcal{L}` is the likelihood of the
        model. With :math:`D` distributed as chisquare with df equal
        to difference in number of parameters or equivalently
        difference in residual degrees of freedom.

        The large sample version of the likelihood ratio is defined as

        .. math:: D=n s^{\prime}S^{-1}s

        where :math:`s=n^{-1}\sum_{i=1}^{n} s_{i}`

        .. math:: s_{i} = x_{i,alternative} \epsilon_{i,null}

        is the average score of the model evaluated using the
        residuals from null model and the regressors from the
        alternative model and :math:`S` is the covariance of the
        scores, :math:`s_{i}`.  The covariance of the scores is
        estimated using the same estimator as in the alternative
        model.

        This test compares the loglikelihood of the two models.  This
        may not be a valid test, if there is unspecified
        heteroscedasticity or correlation. This method will issue a
        warning if this is detected but still return the results
        without taking unspecified heteroscedasticity or correlation
        into account.

        This test compares the loglikelihood of the two models.  This
        may not be a valid test, if there is unspecified
        heteroscedasticity or correlation. This method will issue a
        warning if this is detected but still return the results
        without taking unspecified heteroscedasticity or correlation
        into account.

        is the average score of the model evaluated using the
        residuals from null model and the regressors from the
        alternative model and :math:`S` is the covariance of the
        scores, :math:`s_{i}`.  The covariance of the scores is
        estimated using the same estimator as in the alternative
        model.
        T)r  ra   r^   zQLikelihood Ratio test is likely invalid with robust covariance, proceeding anywayr   )
r  r  r   r   r   r   rW   r
   r  r  )r@   r  large_sampler	  r
  llf_full	llf_restrr  r   lrdflrstat	lr_pvalues               r2   compare_lr_testz!RegressionResults.compare_lr_test  s    `  	A''
4'@@@tZ==LJ
K88KG 	  	.+ 	.M A,. . . 8N	-&7"Y)*JMM&$//	y$&&r4   r  c                   ddl m}m} ddlmc m}  ||          }d|v r|                    d          |d<   d|v r+t          |d                   s|j        |d                  |d<   |                    dd          }|r| }n-| 	                    | j
        | j        | j        | j                  }||_        || j        }d	|i|_        ||_        d}	|d
v r|                    dd          }
|
durd}	|	|j        d<   |dv rA|d         |j        d<   |                    dd          x|j        d<   }||j        z  |_        n|                                dv r_|rt)          d          ||                                         |j        d<   t+          | d|                                z             |_        n|                                dk    r|d         }||j        d<   |                    d|j                  }||j        d<   |                    dd          }||j        d<   |d                             |ddg|                   |j        d<   |                    | |||          |_        n|                                dk    r|d         }t5          |d           s%d! |D             }t7          j        |          j        }|j        d"k    r|                                }||j        d<   |                    dd          }||j        d<   |j        d#k    rH|	r(tA          t7          j!        |                    x| _"        }|#                    | ||$          |_        n|j        d"k    rt5          |d%          r|j$        }|	rotA          t7          j!        |dddf                             }tA          t7          j!        |ddd#f                             }||f| _"        tK          ||          }|&                    | ||$          d         |_        nt)          d&          |d         |j        d<   n|                                d'k    r|                    d(d          x|j        d(<   }|                    dd          x|j        d<   }|d         x|j        d<   }|                    dd          }||j        d<   |                    d|j                  }||j        d<   |gt7          j        |          }t7          j'        |dd)         |d#d         k              d         d#z   (                                }tA          |          }nx|gt7          j        |          }t7          j'        |d#d         |dd)         k               d         d#z   (                                }tA          |          }nt)          d*          tS          dg|z   ||gz             }tA          |          x| _"        }|*                    | ||||+          |_        |d,         |j        d<   n|                                d-k    r|d(         x|j        d(<   }|d         x|j        d<   }|                    dd          }||j        d<   |                    d|j                  }||j        d<   |	rJt7          j'        |d#d         |dd)         k               d         d#z   }tA          |          d#z   x| _"        }|+                    | ||||+          |_        |d.         |j        d<   nt)          d/          |	r
|d#z
  |_,        |S )0a  
        Create new results instance with robust covariance as default.

        Parameters
        ----------
        cov_type : str
            The type of robust sandwich estimator to use. See Notes below.
        use_t : bool
            If true, then the t distribution is used for inference.
            If false, then the normal distribution is used.
            If `use_t` is None, then an appropriate default is used, which is
            `True` if the cov_type is nonrobust, and `False` in all other
            cases.
        **kwargs
            Required or optional arguments for robust covariance calculation.
            See Notes below.

        Returns
        -------
        RegressionResults
            This method creates a new results instance with the
            requested robust covariance as the default covariance of
            the parameters.  Inferential statistics like p-values and
            hypothesis tests will be based on this covariance matrix.

        Notes
        -----
        The following covariance types and required or optional arguments are
        currently available:

        - 'fixed scale' uses a predefined scale

          ``scale``: float, optional
            Argument to set the scale. Default is 1.

        - 'HC0', 'HC1', 'HC2', 'HC3': heteroscedasticity robust covariance

          - no keyword arguments

        - 'HAC': heteroskedasticity-autocorrelation robust covariance

          ``maxlags`` :  integer, required
            number of lags to use

          ``kernel`` : {callable, str}, optional
            kernels currently available kernels are ['bartlett', 'uniform'],
            default is Bartlett

          ``use_correction``: bool, optional
            If true, use small sample correction

        - 'cluster': clustered covariance estimator

          ``groups`` : array_like[int], required :
            Integer-valued index of clusters or groups.

          ``use_correction``: bool, optional
            If True the sandwich covariance is calculated with a small
            sample correction.
            If False the sandwich covariance is calculated without
            small sample correction.

          ``df_correction``: bool, optional
            If True (default), then the degrees of freedom for the
            inferential statistics and hypothesis tests, such as
            pvalues, f_pvalue, conf_int, and t_test and f_test, are
            based on the number of groups minus one instead of the
            total number of observations minus the number of explanatory
            variables. `df_resid` of the results instance is also
            adjusted. When `use_t` is also True, then pvalues are
            computed using the Student's t distribution using the
            corrected values. These may differ substantially from
            p-values based on the normal is the number of groups is
            small.
            If False, then `df_resid` of the results instance is not
            adjusted.

        - 'hac-groupsum': Driscoll and Kraay, heteroscedasticity and
          autocorrelation robust covariance for panel data
          # TODO: more options needed here

          ``time`` : array_like, required
            index of time periods
          ``maxlags`` : integer, required
            number of lags to use
          ``kernel`` : {callable, str}, optional
            The available kernels are ['bartlett', 'uniform']. The default is
            Bartlett.
          ``use_correction`` : {False, 'hac', 'cluster'}, optional
            If False the the sandwich covariance is calculated without small
            sample correction. If `use_correction = 'cluster'` (default),
            then the same small sample correction as in the case of
            `covtype='cluster'` is used.
          ``df_correction`` : bool, optional
            The adjustment to df_resid, see cov_type 'cluster' above

        - 'hac-panel': heteroscedasticity and autocorrelation robust standard
          errors in panel data. The data needs to be sorted in this case, the
          time series for each panel unit or cluster need to be stacked. The
          membership to a time series of an individual or group can be either
          specified by group indicators or by increasing time periods. One of
          ``groups`` or ``time`` is required. # TODO: we need more options here

          ``groups`` : array_like[int]
            indicator for groups
          ``time`` : array_like[int]
            index of time periods
          ``maxlags`` : int, required
            number of lags to use
          ``kernel`` : {callable, str}, optional
            Available kernels are ['bartlett', 'uniform'], default
            is Bartlett
          ``use_correction`` : {False, 'hac', 'cluster'}, optional
            If False the sandwich covariance is calculated without
            small sample correction.
          ``df_correction`` : bool, optional
            Adjustment to df_resid, see cov_type 'cluster' above

        **Reminder**: ``use_correction`` in "hac-groupsum" and "hac-panel" is
        not bool, needs to be in {False, 'hac', 'cluster'}.

        .. todo:: Currently there is no check for extra or misspelled keywords,
             except in the case of cov_type `HCx`
        r   )descriptionsnormalize_cov_typeNkernelweights_funcrk  F)rf   r   rc   )r  	hac-panelhac-groupsumdf_correctionT	adjust_df)zfixed scalefixed_scaler   rj  r   r   r  z:heteroscedasticity robust covariance does not use keywordscov_hacr  use_correctionr  withoutwith)r  
correction)nlagsr  r#  r  r  r)   c                Z    g | ](}t          j        t          j        |                    )S r   )r$   r&   r%   ).0groups     r2   
<listcomp>z;RegressionResults.get_robustcov_results.<locals>.<listcomp>
  s,    LLLE"*RZ%6%677LLLr4   r   r   )r#  valueszonly two groups are supportedr  timer
  z'either time or groups needs to be given)r  r#  z	HAC-Panelr  zHAC-GroupsumzIcov_type not recognized. See docstring for available options and spelling)-statsmodels.base.covtyper  r  r  r
   r  rn  callablekernel_dictrD   rq  r   rf   r   ra   rc   rj   getcov_params_defaultupperr*   r  r"   weights_bartlettr   cov_hac_simplerk   r$   r%   rq   r'   r&   r   uniquen_groupscov_clusterr,  mincov_cluster_2groupsnonzerotolistr   cov_nw_panelcov_nw_groupsumdf_resid_inference)r@   ra   rc   rC   r  r  r  rk  resr  r  r   r  r  r#  r  r7  	n_groups0	n_groups1r-  ttnobs_groupidxs                          r2   ro  z'RegressionResults.get_robustcov_resultsW	  s   z 	NMMMMMMM:::::::::%%h//v%+ZZ%9%9F>"V##HVN5K,L,L#%'^F>4J%KF>" ::j%00 	"CC..
DK&*&@j ! " "C
  =JE'		???"JJ==ME)) 	$-[! 555*6}*ECL',2JJw,C,CCCL!E%*S-F%FC""^^!=== :  "9 : : :*6x~~7G7G*HCL'%,T6HNN<L<L3L%M%MC""^^&&Y'G&-CL#!::nb6IJJL+7CL(#ZZ(8%@@N-;CL)**6u*=*D*D%v.~> +E +@ +@CL' &(%6%6G,- &7 &/ &/C"" ^^**H%F67++ .LLVLLLF++-{a))%+CL"#ZZ(8$??N-;CL)*{a F 0329V3D3D/E/EEDMH)+& *8 *A *A&& !!68,, +#]F 9 !$BIfQQQTl$;$; < <I #BIfQQQTl$;$; < <I%.	$:DM"9i88H *,)?)?& *@ *A *AAB*D&& !!@AAA*6y*ACL''^^,,*0**VT*B*BBCL 4.4jj4.H.HHCL"V
 17y0AACL#g#ZZ(8%@@N-;CL)*!::nb6IJJL+7CL(!F++jqrr
!:;;A>BJJLLF!z$''jabbD"I!566q9A=EEGGD		 !JKKKQC"HbE7l33H'*8}}4DMH%'__)- &5 & &C" +7{*CCL''^^//*0.8CL 4
 17y0AACL#g#ZZ(8)DDN-;CL)*!::nb6IJJL+7CL( 7jabbD"I!566q9A=+.r77Q;6%'%7%7gt,- &8 &/ &/C" +7~*FCL'' > ? ? ?  	2%-\C"
r4   c                0    t          j        | f||||d|S )N)rB   	transformr;   
row_labels)predget_prediction)r@   rB   rG  r;   rH  rC   s         r2   rJ  z RegressionResults.get_prediction
  s8     "-y'!- -%+- - 	-r4   yname
str | NonexnameSequence[str] | Nonetitler   rG   slimboolc                   ddl m}m}m} t	          |dd          }t          |ddd          } || j                  \  }	}
}} || j                  \  }}| j        }| j        }t          |	|
||||||d	         
          | _
        ddddgfdddddg}t          | d          r|                    d| j        gf           | j        rdnd}d|z   dz   d| j        z  gfd|z   dz   d| j        z  gfdd| j        z  gfdd| j        z  gfd d!d| j        z  gfd"d| j        z  gfg}|rMg d#g x}}fd$|D             }fd%|D             }|dg fgt+          |          t+          |          z
  z  z   }nJd&d'|z  gfd(d'|z  gfd)d'|z  gfd*d'|z  gfg}d+d || j                  z  gfd,d|	z  gfd-d.|
z  gfd/d.|z  gfg}|| j        j        j        d1z   d2z   }dd3lm}  |            }|                    | |||||4           |                    | |||| j        5           |s|                    | ||||d4           g }| j        s|                    d6           t          | d          r |                    | j        d7                    | j        j        j         d         | j        j        j         d8         k     rd9}|                    |           |d	         d:k     r2d;}|d<z  }|d=z  }|d>z  }||d	         z  }|                    |           n1|d?k    r+d@}|dAz  }|dBz  }|dCz  }||z  }|                    |           |rDdD tC          |          D             }|"                    ddE           |#                    |           |S )Fa)  
        Summarize the Regression Results.

        Parameters
        ----------
        yname : str, optional
            Name of endogenous (response) variable. The Default is `y`.
        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, optional
            The significance level for the confidence intervals.
        slim : bool, optional
            Flag indicating to produce reduced set or diagnostic information.
            Default is False.

        Returns
        -------
        Summary
            Instance holding the summary tables and text, which can be printed
            or converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary : A class that holds summary results.
        r   durbin_watsonjarque_beraomni_normtestr   F)optionalrP  T)rW  strictr
  )jbjbpvskewkurtosisomniomnipvcondno	mineigval)Dep. Variable:N)Model:NzMethod:zLeast Squares)zDate:N)zTime:N)No. Observations:N)zDf Residuals:N)z	Df Model:Nra   Covariance Type: z (uncentered)z	R-squared:z%#8.3fzAdj. R-squaredF-statistic:z%#8.4gProb (F-statistic):z%#6.3g)zLog-Likelihood:NzAIC:zBIC:)ra  rb  rc  rd  z
R-squared:zAdj. R-squared:rg  rh  c                (    g | ]}|d          v |S r   r   r)  elemslimlists     r2   r+  z-RegressionResults.summary.<locals>.<listcomp>
  s'    IIIT!W5H5H5H5H5Hr4   c                (    g | ]}|d          v |S rj  r   rk  s     r2   r+  z-RegressionResults.summary.<locals>.<listcomp>
  s'    KKK$tAw(7J7J7J7J7Jr4   Omnibus:z%#6.3fProb(Omnibus):Skew:	Kurtosis:Durbin-Watson:Jarque-Bera (JB):	Prob(JB):z%#8.3gz	Cond. No.N zRegression Results)Summary)gleftgrightrK  rM  rO  )rK  rM  r   rc   u[   R² is computed without centering (uncentered) since the model does not contain a constant.rj  r   9The input rank is higher than the number of observations.r   z6The smallest eigenvalue is %6.3g. This might indicate zthat there are
z5strong multicollinearity problems or that the design zmatrix is singular.  z1The condition number is large, %6.3g. This might zindicate that there are
z,strong multicollinearity or other numerical z	problems.c                *    g | ]\  }}d |dz    d| S [r   z] r   r)  r   texts      r2   r+  z-RegressionResults.summary.<locals>.<listcomp>%  @     6 6 6 D )Q(($(( 6 6 6r4   Notes:)$statsmodels.stats.stattoolsrT  rU  rV  r   r   r}  r  r  dictdiagnrk   r@  ra   rO   r  r  r  r  r  r  r   rq  rD   r   statsmodels.iolib.summaryrw  add_table_2colsadd_table_paramsrc   rj   rB   r)   	enumerateinsertadd_extra_txt)r@   rK  rM  rO  r   rP  rT  rU  rV  rY  rZ  r[  r\  r]  r^  r  r_  top_leftrsquared_type	top_right
diagn_leftdiagn_rightrw  smryetextwstrrm  s                             @r2   summaryzRegressionResults.summary
  sB   L	
 	
 	
 	
 	
 	
 	
 	
 	
 	

 5'E:::vdCCC#.;t{#;#; D$$}T[11f.& Rd#F6$+BK1 1 1
 -$ 12##/+' 4$$ 	COO/$-ABBB"oB?!M1C7$-/02&6<$"3346$x$+'=&>?+h.F-GH.x$(234x$(234		  	? ? ?H (*)JIIIIIIIHKKKK)KKKI!b
c(mmc)nn<=>II &4'89+h.?-@A"X_$56&H)<(=>J -%dk(B(BBC 0(R-A'(T/):;'(V*;)<=K =J(1C7:NNE 	655555wyyT)#(U 	 	D 	D 	Dd%uE$(J 	 	0 	0 	0 	+  Z',E') ! + + +
  	LL5   4$$ 	7LL}5666:? #djo&;A&>>>NDLL2;KD&&DKKD))D'"+%DLLd]]FD//DBBDKD&=DLL 	&6 6$-e$4$46 6 6ELLH%%%u%%%r4   %.4ffloat_formatrY  c                   ddl m}m}m}  || j                  \  }	}
}} || j                  \  }} || j                  }| j        }| j        }t          dd|z  fdd|z  fdd|z  fdd|z  fdd|z  fd	d|	z  fd
d|
z  fdd|z  fg          }ddlm	} |
                                }|                    | |||||           |                    |           g }| j        s|                    d           t          | d          r |                    | j        d                    | j        j        j        d         | j        j        j        d         k     rd}|                    |           |d         dk     r!d|d         z  }|                    |           n |dk    rd|z  }|                    |           |r/d t)          |          D             }|                    dd           |D ]}|                    |           |S )a  
        Experimental summary function to summarize the regression results.

        Parameters
        ----------
        yname : str
            The 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
            The significance level for the confidence intervals.
        float_format : str
            The format for floats in parameters summary.

        Returns
        -------
        Summary
            Instance holding the summary tables and text, which can be printed
            or converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary2.Summary
            A class that holds summary results.
        r   rS  ro  z%.3frp  rq  rr  rs  rt  ru  zCondition No.:z%.0f)summary2)r  r   r  rM  rK  rO  uk   R² is computed without centering (uncentered) since the                 model does not contain a constant.ra   rj  r   rz  r
  r   zThe smallest eigenvalue is %6.3g. This might indicate that                there are strong multicollinearity problems or that the design                matrix is singular.r{  zThe condition number is large, %6.3g. This might indicate                that there are strong multicollinearity or other numerical                problems.c                *    g | ]\  }}d |dz    d| S r}  r   r  s      r2   r+  z.RegressionResults.summary2.<locals>.<listcomp>  r  r4   r  )r  rT  rU  rV  r}  r  r  r  statsmodels.iolibr  rw  add_baseadd_dictrO   r@  rk   rj   rq  rB   r)   r  r  add_text)r@   rK  rM  rO  r   r  rT  rU  rV  rY  rZ  r[  r\  r]  r^  dwr  r_  
diagnosticr  r  r  r  r   lines                            r2   r  zRegressionResults.summary2,  s   N	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 $/;t{#;#; D$$}T[11f]4;''.&&4-(v/ftm$&8+,v{+ &2+.&4-(v/	 	 	
 	/.....!!d%l!e 	 	= 	= 	=j!!! 	LL4   4$$ 	7LL}5666:? #djo&;A&>>>NDLL 2;%'.r{3D LLd]]#$D LL 	&6 6$-e$4$46 6 6ELLH%%% 	  	 DMM$r4   )Nr   r^   NN)rt  Nrj  )TF)F)r  N)NTNN)NNNrt  F)
rK  rL  rM  rN  rO  rL  r   rG   rP  rQ  )NNNrt  r  )
rK  rL  rM  rN  rO  rL  r   rG   r  rY  )5r   r   r   r   rl  r=   rw  r   r/   r{  r}  r   r   r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  ro  r   rI  rJ  r  r  r   r   s   @r2   rw   rw      s       0 0d FHJ<@#, #, #, #, #, #,J     2 0 0 ^0 @ @ ^@ + + ^+ * * ^* ^6 6 6 & & ^&
 : : ^:( & & ^& 2 2 ^2 4 4 ^4 	+ 	+ ^	+ & & ^& 	& 	& ^	& I I ^I "1 "1 ^"1H E E ^E 3 3 ^3 ) ) ^) ) ) ^)#7 #7 #7 #7J 	& 	& ^	& 
/ 
/ ^
/  
1 1 1   ^   ^   ^   ^ . . ^. . . ^. . . ^. . . ^. 5 5 ^50%( %( %(NX* X* X* X*t3) 3) 3)je' e' e' e'Ng g g gR	 Xd!)**@D"&- - - +*- !%*. $b b b b bL !%*. $ &e e e e e e e e er4   rw   c                  <    e Zd ZdZd Z	 	 ddZ	 	 ddZ	 	 ddZdS )rv   a  
    Results class for for an OLS model.

    Parameters
    ----------
    model : RegressionModel
        The regression model instance.
    params : ndarray
        The estimated parameters.
    normalized_cov_params : ndarray
        The normalized covariance parameters.
    scale : float
        The estimated scale of the residuals.
    cov_type : str
        The covariance estimator used in the results.
    cov_kwds : dict
        Additional keywords used in the covariance specification.
    use_t : bool
        Flag indicating to use the Student's t in inference.
    **kwargs
        Additional keyword arguments used to initialize the results.

    See Also
    --------
    RegressionResults
        Results store for WLS and GLW models.

    Notes
    -----
    Most of the methods and attributes are inherited from RegressionResults.
    The special methods that are only available for OLS are:

    - get_influence
    - outlier_test
    - el_test
    - conf_int_el
    c                $    ddl m}  ||           S )a  
        Calculate influence and outlier measures.

        Returns
        -------
        OLSInfluence
            The instance containing methods to calculate the main influence and
            outlier measures for the OLS regression.

        See Also
        --------
        statsmodels.stats.outliers_influence.OLSInfluence
            A class that exposes methods to examine observation influence.
        r   )OLSInfluence)$statsmodels.stats.outliers_influencer  )r@   r  s     r2   get_influencezOLSResults.get_influence  s'     	FEEEEE|D!!!r4   bonfrt  NFc                0    ddl m}  || |||||          S )a  
        Test observations for outliers according to method.

        Parameters
        ----------
        method : str
            The method to use in the outlier test.  Must be one of:

            - `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
            The familywise error rate (FWER).
        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 t.

        Returns
        -------
        array_like
            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.
        r   )outlier_test)labelsr7  cutoff)r  r  )r@   r_   r   r  r7  r  r  s          r2   r  zOLSResults.outlier_test  s>    ^ 	FEEEEE|D&%"'8 8 8 	8r4   r   nmr   c                   t          j        | j                  }t                      }t	          |          t	          |          k    r|                    g || j        j        | j        j        | j        j	        | j        j        j
        d         |||	  	        }	dt          j                            |	t	          |                    z
  }
|r
|	|
|j        fS |	|
fS t          j        ||          }|| j        j        | j        j        | j        j	        | j        j        j
        d         |||f}|dk    r&t!          j        |j        |dddd|          d         }	|dk    r$t!          j        |j        |dd|          d         }	dt          j                            |	t	          |                    z
  }
|r|	|
|j        |j        fS |r
|	|
|j        fS |	|
fS )	a  
        Test single or joint hypotheses using Empirical Likelihood.

        Parameters
        ----------
        b0_vals : 1darray
            The hypothesized value of the parameter to be tested.
        param_nums : 1darray
            The parameter number to be tested.
        return_weights : bool
            If true, returns the weights that optimize the likelihood
            ratio at b0_vals. The default is False.
        ret_params : bool
            If true, returns the parameter vector that maximizes the likelihood
            ratio at b0_vals.  Also returns the weights.  The default is False.
        method : str
            Can either be 'nm' for Nelder-Mead or 'powell' for Powell.  The
            optimization method that optimizes over nuisance parameters.
            The default is 'nm'.
        stochastic_exog : bool
            When True, the exogenous variables are assumed to be stochastic.
            When the regressors are nonstochastic, moment conditions are
            placed on the exogenous variables.  Confidence intervals for
            stochastic regressors are at least as large as non-stochastic
            regressors. The default is True.

        Returns
        -------
        tuple
            The p-value and -2 times the log-likelihood ratio for the
            hypothesized values.

        Examples
        --------
        >>> import statsmodels.api as sm
        >>> data = sm.datasets.stackloss.load()
        >>> endog = data.endog
        >>> exog = sm.add_constant(data.exog)
        >>> model = sm.OLS(endog, exog)
        >>> fitted = model.fit()
        >>> fitted.params
        >>> array([-39.91967442,   0.7156402 ,   1.29528612,  -0.15212252])
        >>> fitted.rsquared
        >>> 0.91357690446068196
        >>> # Test that the slope on the first variable is 0
        >>> fitted.el_test([0], [1])
        >>> (27.248146353888796, 1.7894660442330235e-07)
        r   )
param_numsrA   rB   r/   nvarr   b0_valsstochastic_exogr  i'  r   )maxfunr   full_outputdispargspowell)r  r  r  )r$   rK  r   r   r   _opt_nuis_regressrq  rA   rB   r/   r)   r
   r  cdfnew_weightsdeleter	   fminfmin_powell
new_params)r@   r  r  return_weights
ret_paramsr_   r  r   opt_fun_instllrpvalx0r  s                r2   el_testzOLSResults.el_test   s   d %%!||z??c&kk))00%j&Z_Z_Z_*1- / 1 	1 	1C uz~~c3z??;;;D !D,":::Dy Yvz**DJ,djo
!6q!96* T>>- >',e%&T3 3 3346C X&|'Er341,02 2 2235C 5:>>#s:777 	l68OOO 	l6669r4   Tc                |   
 t           j                            d|z
  d          
|!                     d                   d         }|!                     d                   d         }
 fd}t	          j        || j                           }t	          j        | j                 |          }	||	fS )a	  
        Compute the confidence interval using Empirical Likelihood.

        Parameters
        ----------
        param_num : float
            The parameter for which the confidence interval is desired.
        sig : float
            The significance level.  Default is 0.05.
        upper_bound : float
            The maximum value the upper limit can be.  Default is the
            99.9% confidence value under OLS assumptions.
        lower_bound : float
            The minimum value the lower limit can be.  Default is the 99.9%
            confidence value under OLS assumptions.
        method : str
            Can either be 'nm' for Nelder-Mead or 'powell' for Powell.  The
            optimization method that optimizes over nuisance parameters.
            The default is 'nm'.
        stochastic_exog : bool
            When True, the exogenous variables are assumed to be stochastic.
            When the regressors are nonstochastic, moment conditions are
            placed on the exogenous variables.  Confidence intervals for
            stochastic regressors are at least as large as non-stochastic
            regressors.  The default is True.

        Returns
        -------
        lowerl : float
            The lower bound of the confidence interval.
        upperl : float
            The upper bound of the confidence interval.

        See Also
        --------
        el_test : Test parameters using Empirical Likelihood.

        Notes
        -----
        This function uses brentq to find the value of beta where
        test_beta([beta], param_num)[1] is equal to the critical value.

        The function returns the results of each iteration of brentq at each
        value of beta.

        The current function value of the last printed optimization should be
        the critical value at the desired significance level. For alpha=.05,
        the value is 3.841459.

        To ensure optimization terminated successfully, it is suggested to do
        el_test([lower_limit], [param_num]).

        If the optimization does not terminate successfully, consider switching
        optimization algorithms.

        If optimization is still not successful, try changing the values of
        start_int_params.  If the current function value repeatedly jumps
        from a number between 0 and the critical value and a very large number
        (>50), the starting parameters of the interior minimization need
        to be changed.
        r   Ng{Gz?r   c                                         t          j        | g          t          j        g                    d         z
  S )N)r_   r  r   )r  r$   r   )b0r_   	param_numr0r@   r  s    r2   r  z!OLSResults.conf_int_el.<locals>.f  sS    <<")0E0E'-0?   A AABDFHI Ir4   )r
   r  ppfrw  r	   brenthr   )r@   r  sigupper_boundlower_boundr_   r  r  lowerlupperlr  s   ``   ``   @r2   conf_int_elzOLSResults.conf_int_elY  s    ~ Z^^AGQ''--,,Y7:K--,,Y7:K	I 	I 	I 	I 	I 	I 	I 	I 	I
 K!%Y!79 9DK	$:!,. . r4   )r  rt  NFN)r   r   r  r   )rt  NNr  T)r   r   r   r   r  r  r  r  r   r4   r2   rv   rv     s        $ $L" " "$ =A)-18 18 18 18f IJ-.W W W Wr ;?CGO  O  O  O  O  O r4   rv   c                      e Zd ZddddddddddddZ ej        ej        j        e          Zi Z	 ej        ej        j
        e	          Z
dS )r   columnsrowscov)chisqsresidr;   r}  bcov_unscaledbcov_scaledr  r  r  r  
norm_residN)r   r   r   _attrswrapunion_dictsr   LikelihoodResultsWrapper_wrap_attrs_methods_wrap_methodsr   r4   r2   r   r     s          F #$"4#@#G#)+ +K H$D$5C " "MMMr4   r   )r   rM  NFT)r   T)Dr   
__future__r   statsmodels.compat.pandasr   statsmodels.compat.pythonr   r   typingr   collections.abcr   r   numpyr$   scipyr	   r
   scipy.linalgr   r   scipy.linalg.lapackr   statsmodels.base.modelr   rq  statsmodels.base.wrapperwrapperr  statsmodels.emplike.elregressr   "statsmodels.regression._predictionr   statsmodels.tools.decoratorsr   r   statsmodels.tools.sm_exceptionsr   r   statsmodels.tools.toolsr   statsmodels.tools.typingr   statsmodels.tools.validationr   r   r   re  r   rI  __docformat____all__r   r3   LikelihoodModelr6   r   r   r   r   rB  rg  LikelihoodModelResultsrw   rv   ResultsWrapperr   populate_wrapperr   r4   r2   <module>r     s   6 # " " " " " . . . . . . 2 2 2 2 2 2 2 2       $ $ $ $ $ $      ! ! ! ! ! ! ! ! + + + + + + + + & & & & & & % % % % % % % % % ' ' ' ' ' ' ' ' ' 4 4 4 4 4 4 @ @ @ @ @ @ G G G G G G G G L L L L L L L L 1 1 1 1 1 1 1 1 1 1 1 1 K K K K K K K K K K ! ! ! ! ! !%' ' '
\	 @  >    d*   D`0 `0 `0 `0 `0/ `0 `0 `0Fs0 s0 s0 s0 s0/ s0 s0 s0lf0 f0 f0 f0 f0# f0 f0 f0Rh h h h hC h h hV =Bo o o od; ; ; ;|q q q q q3 q q qh+T  T  T  T  T " T  T  T n" " " " "t2 " " "4  .') ) ) ) )r4   