
    M/Ph9E                     p    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dS )
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                   :    e Zd ZdZd
dZddZddZddZdd	ZdS )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                 X    || _         || _        || _        t          |          | _        d S N)copula	marginalscop_argslenk_vars)selfr   r   r   s       h/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/distributions/copula/copulas.py__init__zCopulaDistribution.__init__'   s*     # )nn       Nc                     || j         }|dg| j        z  }| j                            |||          }t	          | j                  D ]3\  }} |j        dd|dd|f         dz
  z  z   g||         R  |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
        Nr	   )nobsargsrandom_stateg      ?gA?)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0 	3 	3GAt#48C919K*L$L 3%.q\3 3 3F111a4LLr   c                    t          j        |          }|| j        }|dg|j        d         z  }g }t	          | j                  D ]<}|                     | j        |         j        |d|f         g||         R             =t          j	        |          }|j
        dk    r|                                }| 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

        Nr	   .r   )npasarrayr   shaperanger   appendr   cdfcolumn_stackndimsqueezer   )r   yr   r   cdf_margr   us          r   r(   zCopulaDistribution.cdfj   s    2 JqMM}Hqwr{*It{## 	M 	MAOO1DN1-1!CF)KilKKKLLLLOH%%6Q;;		A{q(+++r   c                 V    t          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 vdkk!h)kLLMMMr   c                     t          j        |          }|| j        }|t          dg|j        d         z            }d}g }t          | j                  D ]f}| | j        |         j        |d|f         g||         R  z  }|	                     | j        |         j
        |d|f         g||         R             gt          j        |          }|j        dk    r|                                }|| 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

        Nr	   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 JqMM}HrdQWR[011It{## 	M 	MA,DN1%,QsAvYF1FFFFDOO1DN1-1!CF)KilKKKLLLLOH%%6Q;;		A""1h///r   r	   )r   NNN)NN)	__name__
__module____qualname____doc__r   r   r(   r2   r1   r	   r   r   r   r      s         "% % % %8 8 8 8t&, &, &, &,PN N N N4* * * * * *r   r   c                   ~    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dS )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                     || _         d S r   )k_dim)r   r?   s     r   r   zCopula.__init__
  s    


r   r   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                     dS )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                 B    t          j         | j        |g|R            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   rD   s      r   r1   zCopula.logpdfC  s(    & vhdhq(4((()))r   c                     dS )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	   rD   s      r   r(   z
Copula.cdfX  rE   r     c                 F   | j         dk    rt          d          ||                     ||          }t          j        |          \  }}|                    |dddf         |dddf                    |                    d           |                    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
        r=   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C>XX4lXCCF%b))R


6!!!Q$<1...
c
cF{r   
   c           
      .   ddl m} | j        dk    rddl}|                    d           d}d}t          j        t          j        |d|z
  |          t          j        |d|z
  |                    \  }}t          j        |	                                |	                                g          j
        }	|                     |	          j
                            |j                  }
t          j        |
d	          }t          j        |
d
          }t          j        |          \  }}t          j        |||          }||g}|                    |||
|d|d         |d                   }|                    d           |                    d           |                    dd           |                    dd           |                    d           |                    ||          }|                    d           |                                 |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   )pyplotr=   NzPlotting 2-dimensional Copula.d   g-C6?r      _   )numT)antialiasedvminvmaxr.   rK   equal)ticksp)
matplotlibrV   r?   warningswarnr#   meshgridlinspacevstackravelTr2   reshaper%   nanpercentiler   rM   contourfrO   rP   set_xlimset_ylim
set_aspectcolorbar	set_labeltight_layout)r   	ticks_nbrrQ   pltrb   	n_samplesepsuuvvpointsdatamin_max_rR   vticks
range_cbarcscbars                     r   plot_pdfzCopula.plot_pdf  s   $ 	-,,,,,:??OOOMM:;;;	R[a#gyAA[a#gyAAC CBBHHJJ

3446xx!))"(33a((b))%b))RT4Y777D\
[[Rv%)
1(m  - - 	c
c
Aq
Aq
g||Bf|--s
r      c                     |                      ||          }t          j        |dddf         |dddf                   d         S )zKendall'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  sI     HHTH55!!!Q$111a411!44r   c                 H   t          j        |          j        d         dk    r0t          j        dddf         dddf                   d         }n7| j        fdt                    D             }t          j        |          }|                     |          S )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   r=   Nr   c           	          g | ]C}t          |d z             D ]-}t          j        d|f         d|f                   d         .DS )r   .r   )r&   r   r   ).0r   jkr   s      r   
<listcomp>z)Copula.fit_corr_param.<locals>.<listcomp>  sk     > > >uQqS!}}> >*+ $QsAvY#q&	::1= > > > >r   )	r#   r$   r%   r   r   r?   r&   mean_arg_from_tau)r   ry   tautausr   r   s       @@r   fit_corr_paramzCopula.fit_corr_param  s     Jt71:??"1QQQT7AaaadG44Q7CC
A> > > > >"1XX> > >D'$--C!!#&&&r   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.

        rA   )r   r   s     r   r   zCopula._arg_from_tau  s
     "!r   )r=   )r   r	   Nr6   )NrI   NN)rT   N)r   N)r7   r8   r9   r:   r   r   r   r2   r1   r(   rS   r   r   r   r   r	   r   r   r<   r<      s        . .`   " " " "B    ^(* * * **    ^(. . . .`3 3 3 3j
5 
5 
5 
5' ' '4" " " " "r   r<   )r:   abcr   r   numpyr#   scipyr   statsmodels.graphicsr   r   r<   r	   r   r   <module>r      s     $ # # # # # # #           & & & & & &A A A A A A A AHn" n" n" n" n"S n" n" n" n" n"r   