
    M/Ph2                         d dl Zd dlmZ d dlmc mZ d dlm	Z	 	 d Z
	 	 	 	 ddZ	 ddZ G d de          Z G d dej                  Z ej        ee           dS )    N)Results)cache_readonlyc                 H      fd} fd} f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                     |j         }         dz
  z  t          j        | dz            z  dz  } |j        t          j        |          fi }| |z  |z   S )N      )nobsnpsumlogliker_)	paramsmodelr	   pen_llfllfL1_wtalphakloglike_kwdss	        \/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/base/elastic_net.py	nploglikez_gen_npfuncs.<locals>.nploglike)   sd    z(a%i(26&!)+<+<<q@emBE&M::\::ut|g%%    c                     |j         }         dz
  z  | z  } |j        t          j        |          fi d          |z  }||z   S )Nr   r   )r	   scorer
   r   )	r   r   r	   pen_gradgrr   r   r   
score_kwdss	        r   npscorez_gen_npfuncs.<locals>.npscore/   sW    z8q5y)F2ek"%-66:66q99D@H}r   c                     |j         }         dz
  z  } |j        t          j        |          fi d          |z  |z   }|S )Nr   )r   r   )r	   hessianr
   r   )	r   r   r	   pen_hesshr   r   	hess_kwdsr   s	        r   nphessz_gen_npfuncs.<locals>.nphess5   sR    z8q5y)U]25=66I66t<<tChNr    )	r   r   r   r   r   r#   r   r   r$   s	   ``````   r   _gen_npfuncsr&      s    & & & & & & & &               gv%%r   coord_descentd                 ?Hz>:0yE>FTc                 	   
  j         j        d         }
i n

i ni nt          j                  rt          j        |          z  |t          j        |          }n|                                }d}t          j        t          |          t                    } 	                                }d|d<   |
                    dd          }d|v r\|d         T|(t          j        |
                    d                    }n*|t          j        |
                    d                    z  }
fd	t          |          D             }d}t          |          D ]'}|                                }t          |          D ]}||         r|                                }d
||<   t          j         j         |          }|||z  }  j         j         j         dd|f         fd|i|}||         \  }}}t!          ||||||         |         z  ||	          ||<   |d
k    r(t          j        ||                   |k     r
d||<   d||<   t          j        t          j        ||z
                      }||k     rd} n)d
|t          j        |          |k     <   |s&t'           |          }||_        t+          |          S t          j        |          } t          j        ||f          }! fd j        D             }t          |           d
k    r_  j         j         j         dd| f         fi |}"|"                                }#|#j        || <   |#j        |!t          j        | |           <   n9  j         j         j         ddd
f         fi |}"|"                    d
          }#t9          |#j        t:          j                  r|#j        j        }$n|#j        }$tA          |#d          r|#j!        }%nd}% j"         j#        }'}&t          |            _"         j$         j"        z
   _#         |$ ||!|%          }d|_%        ||_        ||_&        d|dz   i|_'        |&|'c _"         _#        |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?)dtypeFhasconstoffsetexposurec           
      8    g | ]}t          |          S r%   )r&   ).0r   r   r   r#   r   r   s     r   
<listcomp>z"fit_elasticnet.<locals>.<listcomp>   s;           	QulJ	JJ     r   r   )tol
check_stepTr)   c                 4    i | ]}|t          |d           S N)getattr)r3   r   r   s     r   
<dictcomp>z"fit_elasticnet.<locals>.<dictcomp>   s'    FFFGE1d++FFFr   )maxiterscaler*   )r<   	iteration)(exogshaper
   isscalaroneszeroscopylenbool_get_init_kwdspoplograngedot	__class__endog_opt_1dabsmaxRegularizedResults	convergedRegularizedResultsWrapperflatnonzero
_init_keysfitr   normalized_cov_paramsix_
issubclasswrapResultsWrapper_resultshasattrr<   df_modeldf_residr	   regularizedmethodfit_history)(r   r`   r;   r   r   start_params	cnvrg_tolzero_tolrefitr6   r   r   r#   k_exogr   btolparams_zero	init_argsmodel_offsetfgh_listrQ   itrparams_saver   params0r0   
model_1varfuncgradhesspchangeresultsiicovmodel1rsltklassr<   pqs(   `  ``     ```                           r   fit_elasticnetr|   >   s   T Za F%-22<L!)zJ'YI	{5 (' &!!""$$D(3v;;d333K$$&&I!Ij==400LY9Z#8#D6)--
";";<<LLBF9==#<#<===L               v     H IW~~ ( ( kkmmv 	 	A
 1~ 
 kkmmGGAJVEJ00F',& )UZ1-K K6<K@IK KJ  ({D$dD*fQiq%Z1 1 1F1I
 Qww26&),,x77!%Aq	 & 45566YIE 
 )*F26&>>H$% 2$UF33%(111 
		B
(FF#
$
$CFFFFU5EFFFI
2ww{{ KAAArE*9 9.79 9zz||[r
"8BF2rNN
 !ejA.>LL)LLzz!z$$ $.$"566 ' tW 
 >5>qAWWENZ%.0EN E%E222EEEOEL$cAg.E &'"ENENLr   c                    |} | ||          }	 |||          }
 |||          }|
||z  z
  }|t          j        |          k    rdS |dk    r	||
z
  |z  }n|dk     r
||
z    |z  }nt           j        S |s||z   S  | ||z   |          |t          j        ||z             z  z   }||	|t          j        |          z  z   dz   k    r||z   S ddlm}  || |f|dz
  |dz   f|          }|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   )argsbrackr5   )r
   rN   nanscipy.optimizer~   )rp   rq   rr   r   startr   r5   r6   xfbcdr"   f1r~   x_opts                    r   rM   rM     sA   j 	AQAQAQA	AaCA rvayyr 	AvvQY!O	
QaiL1v
  1u	a!eU		eBF1q5MM1	1B	Qrvayy 5(((1u %$$$$$E$eXac1Q3ZSAAAELr   c                   8     e Zd ZdZ fdZed             Z xZS )rP   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                 L    t                                          ||           d S r8   )super__init__)selfr   r   rK   s      r   r   zRegularizedResults.__init__q  s#    '''''r   c                 @    | j                             | j                  S )zR
        The predicted values from the model at the estimated parameters.
        )r   predictr   )r   s    r   fittedvalueszRegularizedResults.fittedvaluest  s    
 z!!$+...r   )__name__
__module____qualname____doc__r   r   r   __classcell__)rK   s   @r   rP   rP   f  s]        	 	( ( ( ( ( / / ^/ / / / /r   rP   c                       e Zd ZddddZeZdS )rR   columnsrows)r   residr   N)r   r   r   _attrs_wrap_attrsr%   r   r   rR   rR   |  s*         F
 KKKr   rR   )r'   r(   r)   r*   Nr+   r,   FTNNN)T)numpyr
   statsmodels.base.modelr   statsmodels.base.wrapperbasewrapperrY   statsmodels.tools.decoratorsr   r&   r|   rM   rP   rZ   rR   populate_wrapperr%   r   r   <module>r      s*       * * * * * * ' ' ' ' ' ' ' ' ' 7 7 7 7 7 7.& & &B ;>DH:>AEO O O Of S S S Sl/ / / / / / / /,     3     /(* * * * *r   