o
    0Gf2                     @   s   d dl Zd dlmZ d dlm  mZ d dlm	Z	 	 dd Z
		
		dddZ	dddZG dd deZG dd dejZeee dS )    N)Results)cache_readonlyc           	         s@    fdd} fdd} fdd}|||fS )ao  
    Negative penalized log-likelihood functions.

    Returns the negative penalized log-likelihood, its derivative, and
    its Hessian.  The penalty only includes the smooth (L2) term.

    All three functions have argument signature (x, model), where
    ``x`` is a point in the parameter space and ``model`` is an
    arbitrary statsmodels regression model.
    c                    sN   |j } d   t| d  d }|jtj|  fi }| | | S )N      )nobsnpsumZlogliker_)paramsmodelr   Zpen_llfZllf)L1_wtalphakloglike_kwds <lib/python3.10/site-packages/statsmodels/base/elastic_net.py	nploglike)   s   "z_gen_npfuncs.<locals>.nploglikec                    sD   |j } d   |  }|jtj|  fi d  | }|| S )Nr   r   )r   Zscorer   r	   )r
   r   r   Zpen_gradZgr)r   r   r   
score_kwdsr   r   npscore/   s   "z_gen_npfuncs.<locals>.npscorec                    s@   |j } d   }|jtj|  fi d  | | }|S )Nr   )r   r   )r   Zhessianr   r	   )r
   r   r   Zpen_hessh)r   r   	hess_kwdsr   r   r   nphess5   s   &z_gen_npfuncs.<locals>.nphessr   )	r   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   _gen_npfuncs   s   
r   coord_descentd                 ?Hz>:0yE>FTc           (         s  j jd }du ri ndu ri ndu ri ntr*t| |du r4t|}n| }d}tjt|td}	 }d|d< |
dd}d|v rr|d durr|du rht|
d}n
|t|
d7 } fd	d
t|D }d}t|D ]}| }t|D ]b}|| rq| }d||< tj |}|dur||7 }jjj dd|f fd|i|}|| \}}}t|||||| |   ||	d||< |dkrt|| |k rd||< d||< qtt|| }||k rd} nqd|t||k < |s t|}||_t|S t|} t||f}!fddjD }t| dkrbjjj dd| f fi |}"|" }#|#j|| < |#j|!t| | < njjj dddf fi |}"|"jdd}#t|#jtjr|#jj}$n|#j}$t |#dr|#j!}%nd}%j"j#}&}'t| _"j$j" _#|$||!|%d}d|_%||_||_&d|d i|_'|&|'_"_#|S )a	  
    Return an elastic net regularized fit to a regression model.

    Parameters
    ----------
    model : model object
        A statsmodels object implementing ``loglike``, ``score``, and
        ``hessian``.
    method : {'coord_descent'}
        Only the coordinate descent algorithm is implemented.
    maxiter : int
        The maximum number of iteration cycles (an iteration cycle
        involves running coordinate descent on all variables).
    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`.
    cnvrg_tol : scalar
        If `params` changes by less than this amount (in sup-norm)
        in one iteration cycle, the algorithm terminates with
        convergence.
    zero_tol : scalar
        Any estimated coefficient smaller than this value is
        replaced with zero.
    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.
    check_step : bool
        If True, confirm that the first step is an improvement and search
        further if it is not.
    loglike_kwds : dict-like or None
        Keyword arguments for the log-likelihood function.
    score_kwds : dict-like or None
        Keyword arguments for the score function.
    hess_kwds : dict-like or None
        Keyword arguments for the Hessian function.

    Returns
    -------
    Results
        A results object.

    Notes
    -----
    The ``elastic net`` penalty is a combination of L1 and L2
    penalties.

    The function that is minimized is:

    -loglike/n + alpha*((1-L1_wt)*|params|_2^2/2 + L1_wt*|params|_1)

    where |*|_1 and |*|_2 are the L1 and L2 norms.

    The computational approach used here is to obtain a quadratic
    approximation to the smooth part of the target function:

    -loglike/n + alpha*(1-L1_wt)*|params|_2^2/2

    then repeatedly optimize the L1 penalized version of this function
    along coordinate axes.
    r   Ng-C6?)ZdtypeFZhasconstoffsetZexposurec              	      s   g | ]}t | qS r   )r   .0r   )r   r   r   r   r   r   r   
<listcomp>   s    z"fit_elasticnet.<locals>.<listcomp>r   )tol
check_stepTr   c                    s   i | ]	}|t  |d qS N)getattrr    )r   r   r   
<dictcomp>   s    z"fit_elasticnet.<locals>.<dictcomp>)maxiterscaler   )r)   Z	iteration)(Zexogshaper   ZisscalarZonesZzeroscopylenboolZ_get_init_kwdspoplograngedot	__class__Zendog_opt_1dabsmaxRegularizedResults	convergedRegularizedResultsWrapperZflatnonzeroZ
_init_keysZfitr
   Znormalized_cov_paramsZix_
issubclasswrapResultsWrapperZ_resultshasattrr)   Zdf_modelZdf_residr   ZregularizedmethodZfit_history)(r   r=   r(   r   r   Zstart_paramsZ	cnvrg_tolZzero_tolZrefitr$   r   r   r   Zk_exogr
   ZbtolZparams_zeroZ	init_argsZmodel_offsetZfgh_listr7   itrZparams_saver   Zparams0r   Z
model_1varfuncgradhessZpchangeresultsiiZcovZmodel1Zrsltklassr)   pqr   )r   r   r   r   r   r   r   fit_elasticnet>   s   J





$

rG   c                 C   s   |}| ||}	|||}
|||}|
||  }|t |kr dS |dkr+||
 | }n|dk r7||
  | }nt jS |s@|| S | || ||t ||   }||	|t |  d kra|| S ddlm} || |f|d |d f|d}|S )az  
    One-dimensional helper for elastic net.

    Parameters
    ----------
    func : function
        A smooth function of a single variable to be optimized
        with L1 penaty.
    grad : function
        The gradient of `func`.
    hess : function
        The Hessian of `func`.
    model : statsmodels model
        The model being fit.
    start : real
        A starting value for the function argument
    L1_wt : non-negative real
        The weight for the L1 penalty function.
    tol : non-negative real
        A convergence threshold.
    check_step : bool
        If True, check that the first step is an improvement and
        use bisection if it is not.  If False, return after the
        first step regardless.

    Notes
    -----
    ``func``, ``grad``, and ``hess`` have argument signature (x,
    model), where ``x`` is a point in the parameter space and
    ``model`` is the model being fit.

    If the log-likelihood for the model is exactly quadratic, the
    global minimum is returned in one step.  Otherwise numerical
    bisection is used.

    Returns
    -------
    The argmin of the objective function.
    r   r   g|=)brentr   )argsZbrackr#   )r   r4   nanZscipy.optimizerH   )r?   r@   rA   r   startr   r#   r$   xfbcdr   f1rH   Zx_optr   r   r   r3     s(   5


 r3   c                       s,   e Zd ZdZ fddZedd Z  ZS )r6   z
    Results for models estimated using regularization

    Parameters
    ----------
    model : Model
        The model instance used to estimate the parameters.
    params : ndarray
        The estimated (regularized) parameters.
    c                    s   t  || d S r%   )super__init__)selfr   r
   r2   r   r   rS   q  s   zRegularizedResults.__init__c                 C   s   | j | jS )zR
        The predicted values from the model at the estimated parameters.
        )r   Zpredictr
   )rT   r   r   r   fittedvaluest  s   zRegularizedResults.fittedvalues)__name__
__module____qualname____doc__rS   r   rV   __classcell__r   r   rU   r   r6   f  s
    
r6   c                   @   s   e Zd ZddddZeZdS )r8   columnsZrows)r
   ZresidrV   N)rW   rX   rY   _attrsZ_wrap_attrsr   r   r   r   r8   |  s    r8   )r   r   r   r   Nr   r   FTNNN)T)Znumpyr   Zstatsmodels.base.modelr   Zstatsmodels.base.wrapperbasewrapperr:   Zstatsmodels.tools.decoratorsr   r   rG   r3   r6   r;   r8   Zpopulate_wrapperr   r   r   r   <module>   s&    !
 T
V