U
    Kvf!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                    sJ   |j } d   t| d  d }|jtj|  f}| | | S )N      )nobsnpsumZlogliker_)paramsmodelr   Zpen_llfZllf)L1_wtalphakloglike_kwds @/tmp/pip-unpacked-wheel-2v6byqio/statsmodels/base/elastic_net.py	nploglike)   s    "z_gen_npfuncs.<locals>.nploglikec                    s@   |j } d   |  }|jtj|  f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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kri ndkr(i ndkr8i ntrTt| |dkrht|}n| }d}tjt|td}	 }d|d< |
dd}d|kr|d dk	r|dkrt|
d}n|t|
d7 } fd	d
t|D }d}t|D ]}| }t|D ]}|| r6q$| }d||< tj |}|dk	rf||7 }jjj dd|f fd|i|}|| \}}}t|||||| |   ||	d||< |dkr$t|| |k r$d||< d||< q$tt|| }||k rd} q"qd|t||k < |sRt|}||_t|S t|} t||f}!tfdd
jD }t| dkrֈjjj dd| f f|}"|" }#|#j|| < |#j|!t| | < n,jjj dddf f|}"|"jdd}#t|#jtjr|#j j}$n|#j}$t!|#dr6|#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dtypeF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   g | ]}|t  |d fqS N)getattrr!   )r   r   r   r#      s     )maxiterscaler   )r)   	iteration))Zexogshaper   ZisscalarZoneszeroscopylenboolZ_get_init_kwdspoplograngedot	__class__Zendog_opt_1dabsmaxRegularizedResults	convergedRegularizedResultsWrapperZflatnonzerodictZ
_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_listr9   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


      
 




 
 

rJ   c                 C   s   |}| ||}	|||}
|||}|
||  }|t |kr@dS |dkrV||
 | }n|dk rn||
  | }nt jS |s|| S | || ||t ||   }||	|t |  d kr|| 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   r6   nanZscipy.optimizerK   )rB   rC   rD   r   startr   r$   r%   xfbcdr   f1rK   Zx_optr   r   r   r5     s(    5


 r5   c                       s,   e Zd ZdZ fddZedd Z  ZS )r8   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 t| || d S r&   )superr8   __init__)selfr   r
   r4   r   r   rV   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
   )rW   r   r   r   fittedvaluest  s    zRegularizedResults.fittedvalues)__name__
__module____qualname____doc__rV   r   rY   __classcell__r   r   rX   r   r8   f  s   
r8   c                   @   s   e Zd ZddddZeZdS )r:   columnsZrows)r
   ZresidrY   N)rZ   r[   r\   _attrsZ_wrap_attrsr   r   r   r   r:   |  s
   r:   )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   rJ   r5   r8   r>   r:   Zpopulate_wrapperr   r   r   r   <module>   s0   !                  
 T 
V