B
    lZ1                 @   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 ;lib/python3.7/site-packages/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 }xt|D ]}| }xt|D ]}|| r8q&| }d||< tj |}|dk	rh||7 }jjj dd|f fd|i|}|| \}}}t|||||| |   ||	d||< |dkr&t|| |k r&d||< d||< q&W tt|| }||k rP qW d|t||k < |sJt|}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r.|"j!}$nd}$j"j# }%}&t|_"j$j" _#|#|| |$d}d|_%||_&d|d i|_'|%|& _"_#|S )ay	  
    Return an elastic net regularized fit to a regression model.

    Parameters
    ----------
    model : model object
        A statsmodels object implementing ``loglike``, ``score``, and
        ``hessian``.
    method :
        Only the coordinate descent algorithm is implemented.
    maxiter : integer
        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
    -------
    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_stepTg        c                s   g | ]}|t  |d fqS )N)getattr)r    r   )r   r   r   r!      s    )maxiterscaleg      ?)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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_listZitrZparams_saver   Zparams0r   Z
model_1varfuncgradhessZpchangeZresultsZiiZcovZmodel1Zrsltklassr&   pqr   )r   r   r   r   r   r   r   fit_elasticnet>   s    I


$



 

rA   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.
    g        r   g|=)brentr   )argsZbrackr"   )r   r1   nanZscipy.optimizerB   )r;   r<   r=   r   startr   r"   r#   xfbcdr   f1rB   Zx_optr   r   r   r0   
  s(    5


 r0   c                   s(   e Zd Z fddZedd Z  ZS )r3   c                s   t t| || d S )N)superr3   __init__)selfr   r
   )r/   r   r   rM   b  s    zRegularizedResults.__init__c             C   s   | j | jS )N)r   Zpredictr
   )rN   r   r   r   fittedvaluese  s    zRegularizedResults.fittedvalues)__name__
__module____qualname__rM   r   rO   __classcell__r   r   )r/   r   r3   `  s   r3   c               @   s   e Zd ZddddZeZdS )r4   columnsZrows)r
   ZresidrO   N)rP   rQ   rR   Z_attrsZ_wrap_attrsr   r   r   r   r4   j  s   r4   )r   r   r   r   Nr   r   FTNNN)T)Znumpyr   Zstatsmodels.base.modelr   Zstatsmodels.base.wrapperbasewrapperr7   Zstatsmodels.tools.decoratorsr   r   rA   r0   r3   r8   r4   Zpopulate_wrapperr   r   r   r   <module>   s   !   
 K
U
	