
    "g9E                     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       e/var/www/dash_apps/app1/venv/lib/python3.12/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      ?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 	3GAt#488C919K*L$L 3%.q\3F1a4L	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 JJqM}}Hqwwr{*It{{# 	MAOO1DNN1-11!CF)KilKL	M OOH%66Q;		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 vvdkk!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 JJqM}}HrdQWWR[01It{{# 	MA,DNN1%,,QsAvYF1FFDOO1DNN1-11!CF)KilKL	M OOH%66Q;		A""1h//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#    & vvhdhhq(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>XX4lXCF%%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   $ 	-::?MM:;	R[[a#gyA[[a#gyACBBHHJ
3466xx!!))"((3a(b)%%b)RT4Y7D\
[[Rv%)
1(m  - 	c
c
Aq
Aq
g||Bf|-s
r   c                 v    | j                  ||      }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  s>     HHTH5!Q$1a4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     JJt771:?""1QT7AadG4Q7C

A"1X>uQqS!}>*+ $$QsAvY#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   