
    M/Ph"                     |    d Z ddlZddlmZ ddlmZ ddlmZm	Z	 ddl
mZ  G d d          Z G d	 d
e	          ZdS )ay  
This module implements empirical likelihood regression that is forced through
the origin.

This is different than regression not forced through the origin because the
maximum empirical likelihood estimate is calculated with a vector of ones in
the exogenous matrix but restricts the intercept parameter to be 0.  This
results in significantly more narrow confidence intervals and different
parameter estimates.

For notes on regression not forced through the origin, see empirical likelihood
methods in the OLSResults class.

General References
------------------
Owen, A.B. (2001). Empirical Likelihood.  Chapman and Hall. p. 82.

    N)optimize)chi2)OLSRegressionResults)add_constantc                   &    e Zd ZdZd Zd ZddZdS )ELOriginRegressa/  
    Empirical Likelihood inference and estimation for linear regression
    through the origin.

    Parameters
    ----------
    endog: nx1 array
        Array of response variables.

    exog: nxk array
        Array of exogenous variables.  Assumes no array of ones

    Attributes
    ----------
    endog : nx1 array
        Array of response variables

    exog : nxk array
        Array of exogenous variables.  Assumes no array of ones.

    nobs : float
        Number of observations.

    nvar : float
        Number of exogenous regressors.
    c                     || _         || _        | j        j        d         | _        	 t	          |j        d                   | _        d S # t          $ r d| _        Y d S w xY w)Nr      g      ?)endogexogshapenobsfloatnvar
IndexError)selfr   r   s      a/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/emplike/originregress.py__init__zELOriginRegress.__init__7   sf    
	IOA&		djm,,DIII 	 	 	DIIII	s   A AAc                    t          | j        d          }t          | j        |          }|                                }|                    t          j        dg          t          j        dg          d          }t          j        |d                   }|d         }t          j	        t          j
        |d                             }t          ||||          S )z
        Fits the model and provides regression results.

        Returns
        -------
        Results : class
            Empirical likelihood regression class.
        Tprependr   r   )
ret_params      )r   r   r   r   fitel_testnparraysqueezesumlogOriginResults)r   	exog_withrestricted_modelrestricted_fitrestricted_elparamsbeta_hat_llrllfs           r   r   zELOriginRegress.fit@   s     !D999	tz955)--//&..
!rx}} / 4 4M!,--$Q'fRVM!,--..-v|SIII    Nc                 \    || j         }t          j        t          |d          |          S )NTr   )r   r   dotr   )r   r(   r   s      r   predictzELOriginRegress.predictS   s-    <9Dvl4666???r+   N)__name__
__module____qualname____doc__r   r   r.    r+   r   r	   r	      sY         4  J J J&@ @ @ @ @ @r+   r	   c                   2    e Zd ZdZd Z	 	 ddZ	 	 	 dd
ZdS )r#   a   
    A Results class for empirical likelihood regression through the origin.

    Parameters
    ----------
    model : class
        An OLS model with an intercept.

    params : 1darray
        Fitted parameters.

    est_llr : float
        The log likelihood ratio of the model with the intercept restricted to
        0 at the maximum likelihood estimates of the parameters.
        llr_restricted/llr_unrestricted

    llf_el : float
        The log likelihood of the fitted model with the intercept restricted to 0.

    Attributes
    ----------
    model : class
        An OLS model with an intercept.

    params : 1darray
        Fitted parameter.

    llr : float
        The log likelihood ratio of the maximum empirical likelihood estimate.

    llf_el : float
        The log likelihood of the fitted model with the intercept restricted to 0.

    Notes
    -----
    IMPORTANT.  Since EL estimation does not drop the intercept parameter but
    instead estimates the slope parameters conditional on the slope parameter
    being 0, the first element for params will be the intercept, which is
    restricted to 0.

    IMPORTANT.  This class inherits from RegressionResults but inference is
    conducted via empirical likelihood.  Therefore, any methods that
    require an estimate of the covariance matrix will not function.  Instead
    use el_test and conf_int_el to conduct inference.

    Examples
    --------
    >>> import statsmodels.api as sm
    >>> data = sm.datasets.bc.load()
    >>> model = sm.emplike.ELOriginRegress(data.endog, data.exog)
    >>> fitted = model.fit()
    >>> fitted.params #  0 is the intercept term.
    array([ 0.        ,  0.00351813])

    >>> fitted.el_test(np.array([.0034]), np.array([1]))
    (3.6696503297979302, 0.055411808127497755)
    >>> fitted.conf_int_el(1)
    (0.0033971871114706867, 0.0036373150174892847)

    # No covariance matrix so normal inference is not valid
    >>> fitted.conf_int()
    TypeError: unsupported operand type(s) for *: 'instancemethod' and 'float'
    c                 b    || _         t          j        |          | _        || _        || _        d S r/   )modelr   r    r(   llrllf_el)r   r7   r(   est_llrr9   s        r   r   zOriginResults.__init__   s,    
j((r+   nmr   r   c                 \   t          j        d|f          }t          j        d|f          }| j                                                            |||||          }|d         }|| j        z
  }t          j        || j        j        j	        d         dz
            }	|r||	|d         fS ||	fS )a  
        Returns the llr and p-value for a hypothesized parameter value
        for a regression that goes through the origin.

        Parameters
        ----------
        b0_vals : 1darray
            The hypothesized value to be tested.

        param_num : 1darray
            Which parameters to test.  Note this uses python
            indexing but the '0' parameter refers to the intercept term,
            which is assumed 0.  Therefore, param_num should be > 0.

        return_weights : bool
            If true, returns the weights that optimize the likelihood
            ratio at b0_vals.  Default is False.

        method : str
            Can either be 'nm' for Nelder-Mead or 'powell' for Powell.  The
            optimization method that optimizes over nuisance parameters.
            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.  Default is TRUE.

        Returns
        -------
        res : tuple
            pvalue and likelihood ratio.
        r   )methodstochastic_exogreturn_weightsr   r   )
r   hstackr7   r   r   r8   r   sfr   r   )
r   b0_vals
param_numsr=   r>   r?   test_resllr_testllr_respvals
             r   r   zOriginResults.el_test   s    J )QL))Y://
:>>##++GZ2A1? , A A A;TX%ww
 5a 81 <== 	!D(1+--D= r+   N皙?Tc                     t          j        d|z
  d          t          j        g          |^t          j         j                                                            d                    }t          j        |                   d         }|^t          j         j                                                            d                    }t          j        |                   d         } fd}t          j         j	                           }	t          j        |t          j        |          |	          }
t          j        ||	t          j        |                    }|
|fS )au  
        Returns the confidence interval for a regression parameter when the
        regression is forced through the origin.

        Parameters
        ----------
        param_num : int
            The parameter number to be tested.  Note this uses python
            indexing but the '0' parameter refers to the intercept term.
        upper_bound : float
            The maximum value the upper confidence limit can be.  The
            closer this is to the confidence limit, the quicker the
            computation.  Default is .00001 confidence limit under normality.
        lower_bound : float
            The minimum value the lower confidence limit can be.
            Default is .00001 confidence limit under normality.
        sig : float, optional
            The significance level.  Default .05.
        method : str, optional
             Algorithm to optimize of nuisance params.  Can be 'nm' or
            'powell'.  Default is 'nm'.
        stochastic_exog : bool
            Default is True.

        Returns
        -------
        ci: tuple
            The confidence interval for the parameter 'param_num'.
        r   Ng-C6?r   c                 v    t          j        | g          }                     |           }|d         z
  S )N)r=   r>   r   )r   r   r   )b0valr=   	param_numr0r   r>   s     r   fz$OriginResults.conf_int_el.<locals>.f   sC    2$B,,Ifo   C q6B;r+   )r   ppfr   r   asarrayr7   r   conf_intr    r(   r   brentq)r   rM   upper_boundlower_boundsigr=   r>   cirO   _paramlowerlupperlrN   s   ``   ``     @r   conf_int_elzOriginResults.conf_int_el   sH   @ Xa#gq!!Hi[))	DJNN,,55e<<==B:bm44Q7KDJNN,,55e<<==B:bm44Q7K	 	 	 	 	 	 	 	 	 DK	233BJ{$;$;VDDFBJ{,C,CDDr+   )r;   r   r   )NNrH   r;   T)r0   r1   r2   r3   r   r   r[   r4   r+   r   r#   r#   Y   sj        > >~  
 37>?0! 0! 0! 0!d 269='+3  3  3  3  3  3 r+   r#   )r3   numpyr   scipyr   scipy.statsr   #statsmodels.regression.linear_modelr   r   statsmodels.tools.toolsr   r	   r#   r4   r+   r   <module>ra      s    $                 F F F F F F F F 0 0 0 0 0 0:@ :@ :@ :@ :@ :@ :@ :@zj  j  j  j  j % j  j  j  j  j r+   