Ë
    ¢�Dj/Y  ã                   ó²   — d dl mZ d dlmZmZmZ d dlmZ d dlm	Z	 d dl
Z	 dd„Zdd„Zdd„Zd	„ Zd
„ Z	 	 dd„Zdd„Zi fd„Z G d„ d«      Z G d„ de«      Zy)é    )ÚRegularizedResults)Ú_calc_nodewise_rowÚ_calc_nodewise_weightÚ_calc_approx_inv_cov)ÚLikelihoodModelResults)ÚOLSNc                 óT   — |€t        d«      ‚ | j                  di |¤Žj                  S )aÂ  estimates the regularized fitted parameters.

    Parameters
    ----------
    mod : statsmodels model class instance
        The model for the current partition.
    pnum : scalar
        Index of current partition
    partitions : scalar
        Total number of partitions
    fit_kwds : dict-like or None
        Keyword arguments to be given to fit_regularized

    Returns
    -------
    An array of the parameters for the regularized fit
    zD_est_regularized_naive currently requires that fit_kwds not be None.© )Ú
ValueErrorÚfit_regularizedÚparams©ÚmodÚpnumÚ
partitionsÚfit_kwdss       úkC:\Crop_Prediction\Backend\crop-ai-system\venv\Lib\site-packages\statsmodels/base/distributed_estimation.pyÚ_est_regularized_naiver   K   s<   € ð& ÐÜð ?ó @ð 	@ð ˆ3×ÑÑ* Ñ*×1Ñ1Ð1ó    c                 óT   — |€t        d«      ‚ | j                  di |¤Žj                  S )a¬  estimates the unregularized fitted parameters.

    Parameters
    ----------
    mod : statsmodels model class instance
        The model for the current partition.
    pnum : scalar
        Index of current partition
    partitions : scalar
        Total number of partitions
    fit_kwds : dict-like or None
        Keyword arguments to be given to fit

    Returns
    -------
    An array of the parameters for the fit
    zF_est_unregularized_naive currently requires that fit_kwds not be None.r
   )r   Úfitr   r   s       r   Ú_est_unregularized_naiver   e   s:   € ð& ÐÜð ?ó @ð 	@ð ˆ3�7‰7Ñ�XÑ×%Ñ%Ð%r   c                 óº   — t        | d   «      }t        | «      }t        j                  |«      }| D ]  }||z  }Œ	 ||z  }d|t        j                  |«      |k  <   |S )a   joins the results from each run of _est_<type>_naive
    and returns the mean estimate of the coefficients

    Parameters
    ----------
    params_l : list
        A list of arrays of coefficients.
    threshold : scalar
        The threshold at which the coefficients will be cut.
    r   )ÚlenÚnpÚzerosÚabs)Úparams_lÚ	thresholdÚpr   Ú	params_mnr   s         r   Ú_join_naiver"      si   € ô 	ˆH�Q‰KÓ€AÜ�X“€Jä—‘˜“€IØò ˆØ�VÑ‰	ðà�Ñ€Ià/0€IŒb�f‰f�YÓ )Ñ+Ñ,àÐr   c                 ój   —  | j                   t        j                  |«      fi |¤Ž }||d|z
  z  z  }|S )a  calculates the log-likelihood gradient for the debiasing

    Parameters
    ----------
    mod : statsmodels model class instance
        The model for the current partition.
    params : array_like
        The estimated coefficients for the current partition.
    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.
    score_kwds : dict-like or None
        Keyword arguments for the score function.

    Returns
    -------
    An array-like object of the same dimension as params

    Notes
    -----
    In general:

    gradient l_k(params)

    where k corresponds to the index of the partition

    For OLS:

    X^T(y - X^T params)
    é   )Úscorer   Úasarray)r   r   ÚalphaÚL1_wtÚ
score_kwdsÚgrads         r   Ú
_calc_gradr+   ˜   s>   € ðL ˆC�I‰I”b—j‘j Ó(Ñ7¨JÑ7Ð7€DØˆE�Q˜‘YÑÑ€DØ€Kr   c                 ó    — t        j                   | j                  t        j                  |«      fi |¤Ž«      }|dd…df   | j                  z  S )aú  calculates the weighted design matrix necessary to generate
    the approximate inverse covariance matrix

    Parameters
    ----------
    mod : statsmodels model class instance
        The model for the current partition.
    params : array_like
        The estimated coefficients for the current partition.
    hess_kwds : dict-like or None
        Keyword arguments for the hessian function.

    Returns
    -------
    An array-like object, updated design matrix, same dimension
    as mod.exog
    N)r   ÚsqrtÚhessian_factorr&   Úexog)r   r   Ú	hess_kwdsÚrhesss       r   Ú_calc_wdesign_matr2   Ã   sE   € ô& �G‰GÐ&�C×&Ñ&¤r§z¡z°&Ó'9ÑG¸YÑGÓH€EØ’�D�‰>˜CŸH™HÑ$Ð$r   c                 ó  — |€i n|}|€i n|}|€t        d«      ‚|d   }d|v r|d   }nd}| j                  j                  \  }}	t        t	        j
                  d|	z  |z  «      «      }
 | j                  di |¤Žj                  }t        | ||||«      |z  }t        | ||«      }g }g }t        ||
z  t        |dz   |
z  |	«      «      D ]?  }t        |||«      }|j                  |«       t        ||||«      }|j                  |«       ŒA ||||fS )a‚  estimates the regularized fitted parameters, is the default
    estimation_method for class DistributedModel.

    Parameters
    ----------
    mod : statsmodels model class instance
        The model for the current partition.
    mnum : scalar
        Index of current partition.
    partitions : scalar
        Total number of partitions.
    fit_kwds : dict-like or None
        Keyword arguments to be given to fit_regularized
    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 tuple of parameters for regularized fit
        An array-like object of the fitted parameters, params
        An array-like object for the gradient
        A list of array like objects for nodewise_row
        A list of array like objects for nodewise_weight
    zG_est_regularized_debiased currently requires that fit_kwds not be None.r'   r(   r$   g      ð?r
   )r   r/   ÚshapeÚintr   Úceilr   r   r+   r2   ÚrangeÚminr   Úappendr   )r   Úmnumr   r   r)   r0   r'   r(   Únobsr    Úp_partr   r*   ÚwexogÚnodewise_row_lÚnodewise_weight_lÚidxÚnodewise_rowÚnodewise_weights                      r   Ú_est_regularized_debiasedrC   Ú   sJ  € ð: "Ð)‘¨z€JØÐ'‘¨Y€IàÐÜð ?ó @ð 	@ð ˜Ñ!ˆà�(ÑØ˜Ñ!‰àˆà�h‰h�n‰n�G€Dˆ!Ü”—‘˜"˜q™& JÑ.Ó/Ó0€Fà ˆS× Ñ Ñ, 8Ñ,×3Ñ3€FÜ�c˜6 5¨%°Ó<¸tÑC€Dä˜c 6¨9Ó5€Eà€NØÐÜ�T˜F‘]¤C¨°©°VÑ(;¸QÓ$?Ó@ò 2ˆä)¨%°°eÓ<ˆØ×Ñ˜lÔ+ä/°°|ÀSØ05ó7ˆà× Ñ  Õ1ð2ð �4˜Ð):Ð:Ð:r   c                 óü  — t        | d   d   «      }t        | «      }t        j                  |«      }t        j                  |«      }g }g }| D ]:  }||d   z  }||d   z  }|j                  |d   «       |j                  |d   «       Œ< t        j                  |«      }t        j                  |«      }||z  }|d|z  z  }t        ||«      }	||	j                  |«      z   }
d|
t        j                  |
«      |k  <   |
S )a†  joins the results from each run of _est_regularized_debiased
    and returns the debiased estimate of the coefficients

    Parameters
    ----------
    results_l : list
        A list of tuples each one containing the params, grad,
        nodewise_row and nodewise_weight values for each partition.
    threshold : scalar
        The threshold at which the coefficients will be cut.
    r   r$   é   é   g      ð¿)r   r   r   ÚextendÚarrayr   Údotr   )Ú	results_lr   r    r   r!   Úgrad_mnr>   r?   ÚrÚapprox_inv_covÚdebiased_paramss              r   Ú_join_debiasedrO     s  € ô 	ˆI�a‰L˜‰OÓ€AÜ�Y“€Jä—‘˜“€IÜ�h‰h�q‹k€Gà€NØÐàò 'ˆà�Q�q‘TÑˆ	Ø�1�Q‘4‰ˆà×Ñ˜a ™dÔ#Ø× Ñ   1¡Õ&ð'ô —X‘X˜nÓ-€NÜŸ™Ð!2Ó3Ðà�Ñ€IØˆs�ZÑÑ€Gä)¨.Ð:KÓL€Nà .×"4Ñ"4°WÓ"=Ñ=€Oà;<€O”B—F‘F˜?Ó+¨iÑ7Ñ8àÐr   c                 óÚ   — | j                   j                  «       }|j                  |«        | j                  ||fi |¤Ž} | j                  ||| j
                  fd|i| j                  ¤Ž}|S )aà  handles the model fitting for each machine. NOTE: this
    is primarily handled outside of DistributedModel because
    joblib cannot handle class methods.

    Parameters
    ----------
    self : DistributedModel class instance
        An instance of DistributedModel.
    pnum : scalar
        index of current partition.
    endog : array_like
        endogenous data for current partition.
    exog : array_like
        exogenous data for current partition.
    fit_kwds : dict-like
        Keywords needed for the model fitting.
    init_kwds_e : dict-like
        Additional init_kwds to add for each partition.

    Returns
    -------
    estimation_method result.  For the default,
    _est_regularized_debiased, a tuple.
    r   )Ú	init_kwdsÚcopyÚupdateÚmodel_classÚestimation_methodr   Úestimation_kwds)	Úselfr   Úendogr/   r   Úinit_kwds_eÚtemp_init_kwdsÚmodelÚresultss	            r   Ú_helper_fit_partitionr]   H  sv   € ð6 —^‘^×(Ñ(Ó*€NØ×Ñ˜+Ô&àˆD×Ñ˜U DÑ;¨NÑ;€EØ$ˆd×$Ñ$ U¨D°$·/±/ñ =Ø.6ð=à'+×';Ñ';ñ=€Gð €Nr   c                   ó@   — e Zd ZdZ	 	 	 	 dd„Z	 	 dd„Z	 d	d„Z	 d	d„Zy)
ÚDistributedModelaÇ  
    Distributed model class

    Parameters
    ----------
    partitions : scalar
        The number of partitions that the data will be split into.
    model_class : statsmodels model class
        The model class which will be used for estimation. If None
        this defaults to OLS.
    init_kwds : dict-like or None
        Keywords needed for initializing the model, in addition to
        endog and exog.
    init_kwds_generator : generator or None
        Additional keyword generator that produces model init_kwds
        that may vary based on data partition.  The current usecase
        is for WLS and GLS
    estimation_method : function or None
        The method that performs the estimation for each partition.
        If None this defaults to _est_regularized_debiased.
    estimation_kwds : dict-like or None
        Keywords to be passed to estimation_method.
    join_method : function or None
        The method used to recombine the results from each partition.
        If None this defaults to _join_debiased.
    join_kwds : dict-like or None
        Keywords to be passed to join_method.
    results_class : results class or None
        The class of results that should be returned.  If None this
        defaults to RegularizedResults.
    results_kwds : dict-like or None
        Keywords to be passed to results class.

    Attributes
    ----------
    partitions : scalar
        See Parameters.
    model_class : statsmodels model class
        See Parameters.
    init_kwds : dict-like
        See Parameters.
    init_kwds_generator : generator or None
        See Parameters.
    estimation_method : function
        See Parameters.
    estimation_kwds : dict-like
        See Parameters.
    join_method : function
        See Parameters.
    join_kwds : dict-like
        See Parameters.
    results_class : results class
        See Parameters.
    results_kwds : dict-like
        See Parameters.

    Notes
    -----

    Examples
    --------
    Nc
                 óB  — || _         |€t        | _        n|| _        |€i | _        n|| _        |€t        | _        n|| _        |€i | _        n|| _        |€t        | _        n|| _        |€i | _	        n|| _	        |€t        | _        n|| _        |	€i | _        y |	| _        y ©N)r   r   rT   rQ   rC   rU   rV   rO   Újoin_methodÚ	join_kwdsr   Úresults_classÚresults_kwds)
rW   r   rT   rQ   rU   rV   rb   rc   rd   re   s
             r   Ú__init__zDistributedModel.__init__­  s·   € ð
 %ˆŒàÐÜ"ˆDÕà*ˆDÔàÐØˆD�Nà&ˆDŒNàÐ$Ü%>ˆDÕ"à%6ˆDÔ"àÐ"Ø#%ˆDÕ à#2ˆDÔ àÐÜ-ˆDÕà*ˆDÔàÐØˆD�Nà&ˆDŒNàÐ Ü!3ˆDÕà!.ˆDÔàÐØ "ˆDÕà ,ˆDÕr   c                 óB  — |€i }|dk(  r| j                  |||«      }n(|dk(  r| j                  ||||«      }nt        d|z  «      ‚ | j                  |fi | j                  ¤Ž} | j
                  dgdgfi | j                  ¤Ž} | j                  ||fi | j                  ¤ŽS )ae  Performs the distributed estimation using the corresponding
        DistributedModel

        Parameters
        ----------
        data_generator : generator
            A generator that produces a sequence of tuples where the first
            element in the tuple corresponds to an endog array and the
            element corresponds to an exog array.
        fit_kwds : dict-like or None
            Keywords needed for the model fitting.
        parallel_method : str
            type of distributed estimation to be used, currently
            "sequential", "joblib" and "dask" are supported.
        parallel_backend : None or joblib parallel_backend object
            used to allow support for more complicated backends,
            ex: dask.distributed
        init_kwds_generator : generator or None
            Additional keyword generator that produces model init_kwds
            that may vary based on data partition.  The current usecase
            is for WLS and GLS

        Returns
        -------
        join_method result.  For the default, _join_debiased, it returns a
        p length array.
        Ú
sequentialÚjoblibz.parallel_method: %s is currently not supportedr   )	Úfit_sequentialÚ
fit_joblibr   rb   rc   rT   rQ   rd   re   )	rW   Údata_generatorr   Úparallel_methodÚparallel_backendÚinit_kwds_generatorrJ   r   Úres_mods	            r   r   zDistributedModel.fitÜ  sË   € ð< ÐØˆHà˜lÒ*Ø×+Ñ+¨N¸HØ,?óA‰Ið  Ò(ØŸ™¨¸Ø(8Ø(;ó=‰Iô
 ÐMØ.ñ/ó 0ð 0ð "�×!Ñ! )Ñ>¨t¯~©~Ñ>ˆð #�$×"Ñ" A 3¨¨Ñ>¨t¯~©~Ñ>ˆà!ˆt×!Ñ! '¨6ÑG°T×5FÑ5FÑGÐGr   c           	      ó
  — g }|€8t        |«      D ](  \  }\  }}t        | ||||«      }|j                  |«       Œ* |S t        t        ||«      «      }	|	D ],  \  }\  \  }}}
t        | |||||
«      }|j                  |«       Œ. |S )a*  Sequentially performs the distributed estimation using
        the corresponding DistributedModel

        Parameters
        ----------
        data_generator : generator
            A generator that produces a sequence of tuples where the first
            element in the tuple corresponds to an endog array and the
            element corresponds to an exog array.
        fit_kwds : dict-like
            Keywords needed for the model fitting.
        init_kwds_generator : generator or None
            Additional keyword generator that produces model init_kwds
            that may vary based on data partition.  The current usecase
            is for WLS and GLS

        Returns
        -------
        join_method result.  For the default, _join_debiased, it returns a
        p length array.
        )Ú	enumerater]   r9   Úzip)rW   rl   r   ro   rJ   r   rX   r/   r\   Útup_genrY   s              r   rj   zDistributedModel.fit_sequential  s¼   € ð0 ˆ	àÐ&ä'0°Ó'@ò *Ñ#�‘m�u˜dä/°°d¸EÀ4Ø08ó:�à× Ñ  Õ)ð	*ð" Ðô  ¤ NØ$7ó!9ó :ˆGð 7>ò *Ñ2�Ñ2‘}˜˜t kä/°°d¸EÀ4Ø08¸+óG�à× Ñ  Õ)ð	*ð Ðr   c                 óî  ‡ ‡‡
— ddl m}  |t        ‰ j                  «      \  }Š
}|€ |€ |ˆ
ˆˆ fd„t	        |«      D «       «      }|S |�+|€)|5   |ˆ
ˆˆ fd„t	        |«      D «       «      }ddd«       |S |€,|�*t	        t        ||«      «      }	 |ˆ
ˆˆ fd„|	D «       «      }|S |�7|�5t	        t        ||«      «      }	|5   |ˆ
ˆˆ fd„|	D «       «      }ddd«       |S S # 1 sw Y   S xY w# 1 sw Y   S xY w)a©  Performs the distributed estimation in parallel using joblib

        Parameters
        ----------
        data_generator : generator
            A generator that produces a sequence of tuples where the first
            element in the tuple corresponds to an endog array and the
            element corresponds to an exog array.
        fit_kwds : dict-like
            Keywords needed for the model fitting.
        parallel_backend : None or joblib parallel_backend object
            used to allow support for more complicated backends,
            ex: dask.distributed
        init_kwds_generator : generator or None
            Additional keyword generator that produces model init_kwds
            that may vary based on data partition.  The current usecase
            is for WLS and GLS

        Returns
        -------
        join_method result.  For the default, _join_debiased, it returns a
        p length array.
        r   )Úparallel_funcNc              3   óB   •K  — | ]  \  }\  }} ‰‰|||‰«      –— Œ y ­wra   r
   ©Ú.0r   rX   r/   Úfr   rW   s       €€€r   ú	<genexpr>z.DistributedModel.fit_joblib.<locals>.<genexpr>c  s.   øè ø€ ò :Ù 3 ¡m u¨dñ ˜d D¨%°°x×@ñ :ùó   ƒc              3   óB   •K  — | ]  \  }\  }} ‰‰|||‰«      –— Œ y ­wra   r
   rx   s       €€€r   r{   z.DistributedModel.fit_joblib.<locals>.<genexpr>i  s.   øè ø€ ò  >Ù$7 D©-¨5°$ñ !" $¨¨e°T¸8× Dñ  >ùr|   c           	   3   óJ   •K  — | ]  \  }\  \  }}} ‰‰|||‰|«      –— Œ y ­wra   r
   ©ry   r   rX   r/   rQ   rz   r   rW   s        €€€r   r{   z.DistributedModel.fit_joblib.<locals>.<genexpr>o  s5   øè ø€ ò (Ù @ Ñ&@¡}¨¨t°iñ ˜d D¨%°°xÀ×Kñ (ùó   ƒ #c           	   3   óJ   •K  — | ]  \  }\  \  }}} ‰‰|||‰|«      –— Œ y ­wra   r
   r   s        €€€r   r{   z.DistributedModel.fit_joblib.<locals>.<genexpr>v  s5   øè ø€ ò  ,Ù$D DÑ*D©=¨E°4¸)ñ !" $¨¨e°T¸8ÀY× Oñ  ,ùr€   )Ústatsmodels.tools.parallelrv   r]   r   rr   rs   )rW   rl   r   rn   ro   rv   ÚparÚn_jobsrJ   rt   rz   s   ` `       @r   rk   zDistributedModel.fit_joblibD  s:  ú€ õ4 	=á&Ô'<¸d¿o¹oÓN‰ˆˆQ�àÐ#Ð(;Ð(CÙõ :ä(¨Ó8ô:ó :ˆIð. Ðð' Ð)Ð.AÐ.IØ!ñ >Ùõ  >ä#,¨^Ó#<ô >ó >�	÷>ð$ Ðð Ð%Ð*=Ð*IÜ¤ NÐ4GÓ HÓIˆGÙõ (à&ô(ó (ˆIð Ðð Ð)Ð.AÐ.MÜ¤ NÐ4GÓ HÓIˆGØ!ñ ,Ùõ  ,à#*ô ,ó ,�	÷,ð
 ÐˆyÐ÷%>ð$ Ðú÷,ð
 Ðús   ÁCÂ=C*ÃC'Ã*C4)NNNNNNNN)Nrh   NNra   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__rf   r   rj   rk   r
   r   r   r_   r_   m  sD   „ ð=€Gð~ 04Ø37ØCGØ26ó--ð^ BNØ7;ó7Hðt ,0ó-ð` (,ô6r   r_   c                   ó(   ‡ — e Zd ZdZˆ fd„Zd„ Zˆ xZS )ÚDistributedResultsaT  
    Class to contain model results

    Parameters
    ----------
    model : class instance
        Class instance for model used for distributed data,
        this particular instance uses fake data and is really
        only to allow use of methods like predict.
    params : ndarray
        Parameter estimates from the fit model.
    c                 ó&   •— t         ‰| �  ||«       y ra   )Úsuperrf   )rW   r[   r   Ú	__class__s      €r   rf   zDistributedResults.__init__‹  s   ø€ Ü‰Ñ˜ Õ'r   c                 óX   —  | j                   j                  | j                  |g|¢­i |¤ŽS )aè  Calls self.model.predict for the provided exog.  See
        Results.predict.

        Parameters
        ----------
        exog : array_like NOT optional
            The values for which we want to predict, unlike standard
            predict this is NOT optional since the data in self.model
            is fake.
        *args :
            Some models can take additional arguments. See the
            predict method of the model for the details.
        **kwargs :
            Some models can take additional keywords arguments. See the
            predict method of the model for the details.

        Returns
        -------
            prediction : ndarray, pandas.Series or pandas.DataFrame
            See self.model.predict
        )r[   Úpredictr   )rW   r/   ÚargsÚkwargss       r   r�   zDistributedResults.predictŽ  s+   € ð. "ˆt�z‰z×!Ñ! $§+¡+¨tÐE°dÒE¸fÑEÐEr   )r…   r†   r‡   rˆ   rf   r�   Ú__classcell__)r�   s   @r   rŠ   rŠ   }  s   ø„ ñô(öFr   rŠ   ra   )r   )NNN)Ústatsmodels.base.elastic_netr   Ú(statsmodels.stats.regularized_covariancer   r   r   Ústatsmodels.base.modelr   Ú#statsmodels.regression.linear_modelr   Únumpyr   r   r   r"   r+   r2   rC   rO   r]   r_   rŠ   r
   r   r   ú<module>r˜      sx   ðÝ ;÷0ñ 0å 9Ý 3Û ð@óF2ó4&ó4ò2(òV%ð. ?CØ9=ó>;óB*ð\ ')ó"÷JMñ Mô`(FÐ/õ (Fr   