U
    Ãmœd!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© úU/home/sam/Atlas/atlas_env/lib/python3.8/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_gradÚ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_descentéd   ç        ç      ð?çH¯¼šò×z>ç:Œ0âŽyE>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rÐt | 
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onesZzerosÚcopyÚlenÚboolZ_get_init_kwdsÚpopÚlogÚrangeÚdotÚ	__class__ZendogÚ_opt_1dÚabsÚmaxÚRegularizedResultsÚ	convergedÚRegularizedResultsWrapperZflatnonzeroÚdictZ
_init_keysÚfitr
   Znormalized_cov_paramsZix_Ú
issubclassÚwrapÚResultsWrapperZ_resultsÚhasattrr*   Zdf_modelZdf_residr   ZregularizedÚmethodZfit_history)(r   rA   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
þ

 ÿÿÿ     
 þ




 ÿÿ
 

rK   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.optimizerL   )rC   rD   rE   r   Ústartr   r%   r&   ÚxÚfÚbÚcÚdr   Úf1rL   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   rW   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
   )rX   r   r   r   Úfittedvaluest  s    zRegularizedResults.fittedvalues)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rW   r   rZ   Ú__classcell__r   r   rY   r   r8   f  s   
r8   c                   @   s   e Zd ZddddœZeZdS )r:   ÚcolumnsÚrows)r
   ZresidrZ   N)r[   r\   r]   Z_attrsZ_wrap_attrsr   r   r   r   r:   |  s
   ýr:   )r   r   r   r   Nr   r   FTNNN)T)Únumpyr   Zstatsmodels.base.modelr   Zstatsmodels.base.wrapperÚbaseÚwrapperr>   Zstatsmodels.tools.decoratorsr   r   rK   r5   r8   r?   r:   Zpopulate_wrapperr   r   r   r   Ú<module>   s0   !                  ý
 T ÿ
Vÿ