Ë
    ¢�Dj@G  ã                   ób   — d Z ddlmZmZ ddlZddlmZ ddlm	Z	  G d„ d«      Z
 G d„ d	e«      Zy)
zé

Which Archimedean is Best?
Extreme Value copulas formulas are based on Genest 2009

References
----------

Genest, C., 2009. Rank-based inference for bivariate extreme-value
copulas. The Annals of Statistics, 37(5), pp.2990-3022.

é    )ÚABCÚabstractmethodN)Ústats)Úutilsc                   ó8   — e Zd ZdZdd„Zd	d„Zd
d„Zd
d„Zd
d„Zy)ÚCopulaDistributiona§  Multivariate copula distribution

    Parameters
    ----------
    copula : :class:`Copula` instance
        An instance of :class:`Copula`, e.g. :class:`GaussianCopula`,
        :class:`FrankCopula`, etc.
    marginals : list of distribution instances
        Marginal distributions.
    copargs : tuple
        Parameters for copula

    Notes
    -----
    Status: experimental, argument handling may still change

    c                 óN   — || _         || _        || _        t        |«      | _        y ©N)ÚcopulaÚ	marginalsÚcop_argsÚlenÚk_vars)Úselfr   r   r   s       úlC:\Crop_Prediction\Backend\crop-ai-system\venv\Lib\site-packages\statsmodels/distributions/copula/copulas.pyÚ__init__zCopulaDistribution.__init__'   s$   € àˆŒð #ˆŒØ ˆŒÜ˜)“nˆ�ó    Nc                 ó  — |€| j                   }|€dg| j                  z  }| j                  j                  |||¬«      }t	        | j
                  «      D ]2  \  }} |j                  dd|dd…|f   dz
  z  z   g||   ¢­Ž |dd…|f<   Œ4 |S )a6  Draw `n` in the half-open interval ``[0, 1)``.

        Sample the joint distribution.

        Parameters
        ----------
        nobs : int, optional
            Number of samples to generate in the parameter space.
            Default is 1.
        cop_args : tuple
            Copula parameters. If None, then the copula parameters will be
            taken from the ``cop_args`` attribute created when initiializing
            the instance.
        marg_args : list of tuples
            Parameters for the marginal distributions. It can be None if none
            of the marginal distributions have parameters, otherwise it needs
            to be a list of tuples with the same length has the number of
            marginal distributions. The list can contain empty tuples for
            marginal distributions that do not take parameter arguments.
        random_state : {None, int, numpy.random.Generator}, optional
            If `seed` is None then the legacy singleton NumPy generator.
            This will change after 0.13 to use a fresh NumPy ``Generator``,
            so you should explicitly pass a seeded ``Generator`` if you
            need reproducible results.
            If `seed` is an int, a new ``Generator`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` instance then that instance is
            used.

        Returns
        -------
        sample : array_like (n, d)
            Sample from the joint distribution.

        Notes
        -----
        The random samples are generated by creating a sample with uniform
        margins from the copula, and using ``ppf`` to convert uniform margins
        to the one specified by the marginal distribution.

        See Also
        --------
        statsmodels.tools.rng_qrng.check_random_state
        N© )ÚnobsÚargsÚrandom_stateg      à?g�Aòÿÿÿï?)r   r   r   ÚrvsÚ	enumerater   Úppf)r   r   r   Ú	marg_argsr   ÚsampleÚiÚdists           r   r   zCopulaDistribution.rvs0   sª   € ðZ ÐØ—}‘}ˆHØÐØ˜˜tŸ{™{Ñ*ˆIà—‘—‘ d°Ø.:ð !ó <ˆô ! §¡Ó0ò 	3‰GˆAˆtØ#˜4Ÿ8™8 C¨9¸ÂÀ1À¹ÈÑ9KÑ*LÑ$Lð 3Ø%.¨q¡\ò3ˆF’1�a�4ŠLð	3ð ˆr   c                 ó¸  — t        j                  |«      }|€| j                  }|€dg|j                  d   z  }g }t	        | j
                  «      D ]9  }|j                   | j                  |   j                  |d|f   g||   ¢­Ž «       Œ; t        j                  |«      }|j                  dk(  r|j                  «       }| j                  j                  ||«      S )a®  CDF of copula distribution.

        Parameters
        ----------
        y : array_like
            Values of random variable at which to evaluate cdf.
            If 2-dimensional, then components of multivariate random variable
            need to be in columns
        cop_args : tuple
            Copula parameters. If None, then the copula parameters will be
            taken from the ``cop_args`` attribute created when initiializing
            the instance.
        marg_args : list of tuples
            Parameters for the marginal distributions. It can be None if none
            of the marginal distributions have parameters, otherwise it needs
            to be a list of tuples with the same length has the number of
            marginal distributions. The list can contain empty tuples for
            marginal distributions that do not take parameter arguments.

        Returns
        -------
        cdf values

        r   éÿÿÿÿ.é   )ÚnpÚasarrayr   ÚshapeÚranger   Úappendr   ÚcdfÚcolumn_stackÚndimÚsqueezer   )r   Úyr   r   Úcdf_margr   Úus          r   r(   zCopulaDistribution.cdfj   sÈ   € ô2 �J‰J�q‹MˆØÐØ—}‘}ˆHØÐØ˜˜qŸw™w r™{Ñ*ˆIàˆÜ�t—{‘{Ó#ò 	MˆAØ�O‰OÐ1˜DŸN™N¨1Ñ-×1Ñ1°!°C¸°F±)ÐK¸iÈ¹lÒKÕLð	Mô �O‰O˜HÓ%ˆØ�6‰6�QŠ;Ø—	‘	“ˆAØ�{‰{�‰˜q (Ó+Ð+r   c                 óP   — t        j                  | j                  |||¬«      «      S )a­  PDF of copula distribution.

        Parameters
        ----------
        y : array_like
            Values of random variable at which to evaluate cdf.
            If 2-dimensional, then components of multivariate random variable
            need to be in columns
        cop_args : tuple
            Copula parameters. If None, then the copula parameters will be
            taken from the ``cop_args`` attribute created when initiializing
            the instance.
        marg_args : list of tuples
            Parameters for the marginal distributions. It can be None if none
            of the marginal distributions have parameters, otherwise it needs
            to be a list of tuples with the same length has the number of
            marginal distributions. The list can contain empty tuples for
            marginal distributions that do not take parameter arguments.

        Returns
        -------
        pdf values
        )r   r   )r#   ÚexpÚlogpdf)r   r,   r   r   s       r   ÚpdfzCopulaDistribution.pdf’   s"   € ô0 �v‰v�d—k‘k !¨hÀ)�kÓLÓMÐMr   c                 ó.  — t        j                  |«      }|€| j                  }|€t        dg|j                  d   z  «      }d}g }t        | j                  «      D ]d  }| | j                  |   j                  |d|f   g||   ¢­Ž z  }|j                   | j                  |   j                  |d|f   g||   ¢­Ž «       Œf t        j                  |«      }|j                  dk(  r|j                  «       }|| j                  j                  ||«      z  }|S )a·  Log-pdf of copula distribution.

        Parameters
        ----------
        y : array_like
            Values of random variable at which to evaluate cdf.
            If 2-dimensional, then components of multivariate random variable
            need to be in columns
        cop_args : tuple
            Copula parameters. If None, then the copula parameters will be
            taken from the ``cop_args`` attribute creating when initiializing
            the instance.
        marg_args : list of tuples
            Parameters for the marginal distributions. It can be None if none
            of the marginal distributions have parameters, otherwise it needs
            to be a list of tuples with the same length has the number of
            marginal distributions. The list can contain empty tuples for
            marginal distributions that do not take parameter arguments.

        Returns
        -------
        log-pdf values

        r   r!   g        .r"   )r#   r$   r   Útupler%   r&   r   r   r1   r'   r(   r)   r*   r+   r   )r   r,   r   r   Úlpdfr-   r   r.   s           r   r1   zCopulaDistribution.logpdf¬   s  € ô2 �J‰J�q‹MˆØÐØ—}‘}ˆHØÐÜ˜r˜d Q§W¡W¨R¡[Ñ0Ó1ˆIàˆØˆÜ�t—{‘{Ó#ò 	MˆAØÐ,�D—N‘N 1Ñ%×,Ñ,¨Q¨s°A¨v©YÐF¸À1¹ÒFÑFˆDØ�O‰OÐ1˜DŸN™N¨1Ñ-×1Ñ1°!°C¸°F±)ÐK¸iÈ¹lÒKÕLð	Mô �O‰O˜HÓ%ˆØ�6‰6�QŠ;Ø—	‘	“ˆAà�—‘×"Ñ" 1 hÓ/Ñ/ˆØˆr   ©r   )r"   NNN)NN)	Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r(   r2   r1   r   r   r   r   r      s#   „ ñó"%ó8ót&,óPNô4*r   r   c                   óp   — e Zd ZdZdd„Zdd„Zedd„«       Zdd„Zedd„«       Z	dd„Z
dd	„Zdd
„Zd„ Zd„ Zy)ÚCopulau_  A generic Copula class meant for subclassing.

    Notes
    -----
    A function :math:`\phi` on :math:`[0, \infty]` is the Laplace-Stieltjes
    transform of a distribution function if and only if :math:`\phi` is
    completely monotone and :math:`\phi(0) = 1` [2]_.

    The following algorithm for sampling a ``d``-dimensional exchangeable
    Archimedean copula with generator :math:`\phi` is due to Marshall, Olkin
    (1988) [1]_, where :math:`LS^{âˆ’1}(\phi)` denotes the inverse
    Laplace-Stieltjes transform of :math:`\phi`.

    From a mixture representation with respect to :math:`F`, the following
    algorithm may be derived for sampling Archimedean copulas, see [1]_.

    1. Sample :math:`V \sim F = LS^{âˆ’1}(\phi)`.
    2. Sample i.i.d. :math:`X_i \sim U[0,1], i \in \{1,...,d\}`.
    3. Return:math:`(U_1,..., U_d)`, where :math:`U_i = \phi(âˆ’\log(X_i)/V), i
       \in \{1, ...,d\}`.

    Detailed properties of each copula can be found in [3]_.

    Instances of the class can access the attributes: ``rng`` for the random
    number generator (used for the ``seed``).

    **Subclassing**

    When subclassing `Copula` to create a new copula, ``__init__`` and
    ``random`` must be redefined.

    * ``__init__(theta)``: If the copula
      does not take advantage of a ``theta``, this parameter can be omitted.
    * ``random(n, random_state)``: draw ``n`` from the copula.
    * ``pdf(x)``: PDF from the copula.
    * ``cdf(x)``: CDF from the copula.

    References
    ----------
    .. [1] Marshall AW, Olkin I. â€œFamilies of Multivariate Distributionsâ€�,
      Journal of the American Statistical Association, 83, 834â€“841, 1988.
    .. [2] Marius Hofert. "Sampling Archimedean copulas",
      UniversitÃ¤t Ulm, 2008.
    .. rvs[3] Harry Joe. "Dependence Modeling with Copulas", Monographs on
      Statistics and Applied Probability 134, 2015.

    c                 ó   — || _         y r
   )Úk_dim)r   r>   s     r   r   zCopula.__init__
  s	   € Øˆ�
r   Nc                 ó   — t         ‚)aE  Draw `n` in the half-open interval ``[0, 1)``.

        Marginals are uniformly distributed.

        Parameters
        ----------
        nobs : int, optional
            Number of samples to generate from the copula. Default is 1.
        args : tuple
            Arguments for copula parameters. The number of arguments depends
            on the copula.
        random_state : {None, int, numpy.random.Generator}, optional
            If `seed` is None then the legacy singleton NumPy generator.
            This will change after 0.13 to use a fresh NumPy ``Generator``,
            so you should explicitly pass a seeded ``Generator`` if you
            need reproducible results.
            If `seed` is an int, a new ``Generator`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` instance then that instance is
            used.

        Returns
        -------
        sample : array_like (nobs, d)
            Sample from the copula.

        See Also
        --------
        statsmodels.tools.rng_qrng.check_random_state
        ©ÚNotImplementedError)r   r   r   r   s       r   r   z
Copula.rvs  s
   € ô> "Ð!r   c                  ó   — y)a[  Probability density function of copula.

        Parameters
        ----------
        u : array_like, 2-D
            Points of random variables in unit hypercube at which method is
            evaluated.
            The second (or last) dimension should be the same as the dimension
            of the random variable, e.g. 2 for bivariate copula.
        args : tuple
            Arguments for copula parameters. The number of arguments depends
            on the copula.

        Returns
        -------
        pdf : ndarray, (nobs, k_dim)
            Copula pdf evaluated at points ``u``.
        Nr   ©r   r.   r   s      r   r2   z
Copula.pdf.  ó   � r   c                 óN   — t        j                   | j                  |g|¢­Ž «      S )aY  Log of copula pdf, loglikelihood.

        Parameters
        ----------
        u : array_like, 2-D
            Points of random variables in unit hypercube at which method is
            evaluated.
            The second (or last) dimension should be the same as the dimension
            of the random variable, e.g. 2 for bivariate copula.
        args : tuple
            Arguments for copula parameters. The number of arguments depends
            on the copula.

        Returns
        -------
        cdf : ndarray, (nobs, k_dim)
            Copula log-pdf evaluated at points ``u``.
        )r#   Úlogr2   rC   s      r   r1   zCopula.logpdfC  s#   € ô& �v‰v�h�d—h‘h˜qÐ( 4Ò(Ó)Ð)r   c                  ó   — y)ak  Cumulative distribution function evaluated at points u.

        Parameters
        ----------
        u : array_like, 2-D
            Points of random variables in unit hypercube at which method is
            evaluated.
            The second (or last) dimension should be the same as the dimension
            of the random variable, e.g. 2 for bivariate copula.
        args : tuple
            Arguments for copula parameters. The number of arguments depends
            on the copula.

        Returns
        -------
        cdf : ndarray, (nobs, k_dim)
            Copula cdf evaluated at points ``u``.
        Nr   rC   s      r   r(   z
Copula.cdfX  rD   r   c                 ó  — | j                   dk7  rt        d«      ‚|€| j                  ||¬«      }t        j                  |«      \  }}|j                  |dd…df   |dd…df   «       |j                  d«       |j                  d«       ||fS )	a  Sample the copula and plot.

        Parameters
        ----------
        sample : array-like, optional
            The sample to plot.  If not provided (the default), a sample
            is generated.
        nobs : int, optional
            Number of samples to generate from the copula.
        random_state : {None, int, numpy.random.Generator}, optional
            If `seed` is None then the legacy singleton NumPy generator.
            This will change after 0.13 to use a fresh NumPy ``Generator``,
            so you should explicitly pass a seeded ``Generator`` if you
            need reproducible results.
            If `seed` is an int, a new ``Generator`` instance is used,
            seeded with `seed`.
            If `seed` is already a ``Generator`` instance then that instance is
            used.
        ax : AxesSubplot, optional
            If given, this subplot is used to plot in instead of a new figure
            being created.

        Returns
        -------
        fig : Figure
            If `ax` is None, the created figure.  Otherwise the figure to which
            `ax` is connected.
        sample : array_like (n, d)
            Sample from the copula.

        See Also
        --------
        statsmodels.tools.rng_qrng.check_random_state
        é   z#Can only plot 2-dimensional Copula.N)r   r   r   r"   r.   Úv)r>   Ú
ValueErrorr   r   Úcreate_mpl_axÚscatterÚ
set_xlabelÚ
set_ylabel)r   r   r   r   ÚaxÚfigs         r   Úplot_scatterzCopula.plot_scatterm  s‡   € ðF �:‰:˜Š?ÜÐBÓCÐCàˆ>Ø—X‘X 4°l�XÓCˆFä×%Ñ% bÓ)‰ˆˆRØ
�
‰
�6š!˜Q˜$‘< ª¨1¨¡Ô.Ø
�‰�cÔØ
�‰�cÔà�Fˆ{Ðr   c           
      óè  — ddl m} | j                  dk7  rddl}|j	                  d«       d}d}t        j                  t        j                  |d|z
  |«      t        j                  |d|z
  |«      «      \  }}t        j                  |j                  «       |j                  «       g«      j                  }	| j                  |	«      j                  j                  |j                  «      }
t        j                  |
d	«      }t        j                  |
d
«      }t        j                   |«      \  }}t        j                  |||¬«      }||g}|j#                  |||
|d|d   |d   ¬«      }|j%                  d«       |j'                  d«       |j)                  dd«       |j+                  dd«       |j-                  d«       |j/                  ||¬«      }|j1                  d«       |j3                  «        |S )aÒ  Plot the PDF.

        Parameters
        ----------
        ticks_nbr : int, optional
            Number of color isolines for the PDF. Default is 10.
        ax : AxesSubplot, optional
            If given, this subplot is used to plot in instead of a new figure
            being created.

        Returns
        -------
        fig : Figure
            If `ax` is None, the created figure.  Otherwise the figure to which
            `ax` is connected.

        r   )ÚpyplotrI   NzPlotting 2-dimensional Copula.éd   g-Cëâ6?r"   é   é_   )ÚnumT)ÚantialiasedÚvminÚvmaxr.   rJ   Úequal)ÚticksÚp)Ú
matplotlibrT   r>   ÚwarningsÚwarnr#   ÚmeshgridÚlinspaceÚvstackÚravelÚTr2   Úreshaper%   Únanpercentiler   rL   ÚcontourfrN   rO   Úset_xlimÚset_ylimÚ
set_aspectÚcolorbarÚ	set_labelÚtight_layout)r   Ú	ticks_nbrrP   Úpltr`   Ú	n_samplesÚepsÚuuÚvvÚpointsÚdataÚmin_Úmax_rQ   ÚvticksÚ
range_cbarÚcsÚcbars                     r   Úplot_pdfzCopula.plot_pdf�  s�  € õ$ 	-Ø�:‰:˜Š?ÛØ�M‰MÐ:Ô;àˆ	àˆÜ—‘œRŸ[™[¨¨a°#©g°yÓAÜŸ[™[¨¨a°#©g°yÓAóC‰ˆˆBä—‘˜BŸH™H›J¨¯©«
Ð3Ó4×6Ñ6ˆà�x‰x˜Ó×!Ñ!×)Ñ)¨"¯(©(Ó3ˆÜ×Ñ  aÓ(ˆÜ×Ñ  bÓ)ˆä×%Ñ% bÓ)‰ˆˆRä—‘˜T 4¨YÔ7ˆØ˜D�\ˆ
Ø�[‰[˜˜R  vØ%)°
¸1±Ø(¨™mð ó -ˆð 	�‰�cÔØ
�‰�cÔØ
�‰�A�qÔØ
�‰�A�qÔØ
�‰�gÔØ�|‰|˜B fˆ|Ó-ˆØ�‰�sÔØ×ÑÔàˆ
r   c                 óv   — | j                  ||¬«      }t        j                  |dd…df   |dd…df   «      d   S )zƒKendall's tau based on simulated samples.

        Returns
        -------
        tau : float
            Kendall's tau.

        )r   Nr   r"   )r   r   Ú
kendalltau)r   r   r   Úxs       r   Útau_simulatedzCopula.tau_simulatedÒ  s>   € ð �H‰H�T¨ˆHÓ5ˆÜ×Ñ ¢! Q $¡¨ª1¨a¨4©Ó1°!Ñ4Ð4r   c                 ó®  — t        j                  |«      }|j                  d   dk(  r(t        j                  |dd…df   |dd…df   «      d   }np| j
                  }t        |«      D ��cg c]9  }t        |dz   |«      D ]%  }t        j                  |d|f   |d|f   «      d   ‘Œ' Œ; }}}t        j                  |«      }| j                  |«      S c c}}w )a¸  Copula correlation parameter using Kendall's tau of sample data.

        Parameters
        ----------
        data : array_like
            Sample data used to fit `theta` using Kendall's tau.

        Returns
        -------
        corr_param : float
            Correlation parameter of the copula, ``theta`` in Archimedean and
            pearson correlation in elliptical.
            If k_dim > 2, then average tau is used.
        r"   rI   Nr   .)	r#   r$   r%   r   r€   r>   r&   ÚmeanÚ_arg_from_tau)r   rw   r�   ÚtauÚkr   ÚjÚtauss           r   Úfit_corr_paramzCopula.fit_corr_paramÞ  sÓ   € ô �J‰J�tÓˆà�7‰7�1‰:˜Š?Ü×"Ñ" 1¢Q¨ T¡7¨Aªa°¨d©GÓ4°QÑ7‰Cà—
‘
ˆAä" 1›X÷>Ø¬u°Q°q±S¸!«}ò>Ø*+ô ×$Ñ$ Q s¨A v¡Y°°#°q°&±	Ó:¸1Ó=ð >Ð=ð >ˆDñ >ä—'‘'˜$“-ˆCØ×!Ñ! #Ó&Ð&ùó>s   Á*>Cc                 ó   — t         ‚)a@  Compute correlation parameter from tau.

        Parameters
        ----------
        tau : float
            Kendall's tau.

        Returns
        -------
        corr_param : float
            Correlation parameter of the copula, ``theta`` in Archimedean and
            pearson correlation in elliptical.

        r@   )r   r†   s     r   r…   zCopula._arg_from_tauø  s
   € ô "Ð!r   )rI   )r"   r   Nr6   )Niô  NN)é
   N)i   N)r7   r8   r9   r:   r   r   r   r2   r1   r(   rR   r~   r‚   rŠ   r…   r   r   r   r<   r<   Ù   s[   „ ñ.ó`ó"ðB òó ðó(*ð* òó ðó(.ó`3ój
5ò'ó4"r   r<   )r:   Úabcr   r   Únumpyr#   Úscipyr   Ústatsmodels.graphicsr   r   r<   r   r   r   ú<module>r‘      s3   ðñ÷ $ã Ý å &÷Añ AôHn"ˆSõ n"r   