Skip to content

Copula density not correct for d>2 #8631

Closed

Description

@Tobi0

It seems that the pdf of some Archimedian Copulas are incorrect for d>2. They do not throw an error or warning in this case. The formulas look generic for any dimension at first but are restricted to d=2. At least for Gumbel and Clayton.
I compared with this: https://arxiv.org/pdf/1207.1708.pdf
For Frank there is a dim check ("pdf is currently only available for bivariate copula").

from statsmodels.distributions.copula.archimedean import GumbelCopula
c=GumbelCopula()
c.pdf([.7,.7,.7],20)
> array([3.97063356e-08])

For example in this case, a high value for the density would be expected.

Also it would be good to know the source where the formulas have been taken from.

Activity

  1. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    formulas were taken from several books and articles, main books AFAIR, Nelson and two books by Joe
    some docstrings have references, and code comments in a few places
    The formulas for Gumbel and Clayton might have been copied from an older (license compatible) python package.

    #4046 (comment)
    mentions Nelson
    archimedean module mentions Joe 2014 and Joe 1997

    I don't remember about the explicit pdf formulas in Gumbel and Clayton archimedean (nor whether I or tupui wrote the code)

    I had read the referenced article, but didn't implement a way to compute higher dimensional derivatives for archimedean copulas.
    Note, the Swiss authors use psi as generator while we use phi, where one is the inverse function of the other.

  2. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    AFAICS, we only have unit test for bivariate Gumbel
    It looks like all copula unit tests are only for bivariate case, dim=2

  3. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    Looks like a bug, thanks for reporting

    very high agreement to R copula package for dim=2, completely different for dim=3
    It's not clear to me what's the problem, the formula should be independent of dim. ???

    from statsmodels.distributions.copula.archimedean import GumbelCopula
    c=GumbelCopula()
    c.pdf([.7,.7,.7],20)  # should be 469.1509239922922 from R copula
    # > array([3.97063356e-08])
    array([3.97063356e-08])
     
    pdfval = c.pdf([.7,.7],20)
    pdfval[0], 19.82764498336631, pdfval[0] - 19.82764498336631
    (19.82764498336638, 19.82764498336631, 7.105427357601002e-14)
    
  4. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    setting k_dim = 3 issues a warning
    The warning is standard UserWarning and warns only once. Maybe we want to use a statsmodels warning class.

    c=GumbelCopula(k_dim=3)
    ...\statsmodels\distributions\copula\copulas.py:269: UserWarning: copulas for more than 2 dimension is untested
      warnings.warn("copulas for more than 2 dimension is untested")
    
  5. added
    type-bug-wrong
    on Jan 23, 2023
  6. added this to the 0.14 milestone on Jan 23, 2023
  7. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    I have not found a source for the gumbel and clayton pdf formulas yet.
    The formulas in the arxiv paper and an earlier article differs from those implemented.
    Our formulas might drop a term that is irrelevant for dim=2 or hardcode some part for dim=2.
    (I had assumed the formula is for any k_dim, since we just use prod and sum accumulation.

    page 138 in
    Hofert, M., Mächler, M., and McNeil, A. J. (2012), Likelihood inference for Archimedean
    copulas in high dimensions under known margins, Journal of Multivariate Analysis,
    110, 133–150, doi:10.1016/j.jmva.2012.02.019.

  8. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    Ok,
    As long as we don't have the appropriate extension to k_dim > 2, we should raise an exception.
    The warning occurs in __init__, The cdf is generic for any k_dim in archimedean, so still useful

    So we can raise in methods if the evaluation point u does not have u.shape(-1) == self.k_dim
    currently we only use u = np.atleast_2d(u) but no checks in pdf and other methods.

    logpdf of superclass ArchimedeanCopula already does this, it raises explicitly for dim >2, independently of k_dim

            if u.shape[-1] > 2:
                msg = "pdf is currently only available for bivariate copula"
                raise ValueError(msg)
    
  9. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    Reference

    Joe 2014, Dependence Modeling with Copulas, has explicit formula for density of bivariate Gumbel copula, page 172, but no density for multivariate extensions (section 4.8.2)

    same for Clayton
    bivariate density p. 168 is the same as the formula in our code
    Joe's full name for "clayton" is Bivariate Mardia-Takahasi-Clayton-Cook-Johnson

  10. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    It's worse with clayton and gumbel
    correction cdf for gumbel for k_dim=3 is correct, formula does not have k_dim in it

    Even cdf is only correct for k_dim=2
    cdf of those two copulas use explicit expressions and not the generic generator formula. Those formulas are hardcoded for dim=2

    Frank has dim in the explicit cdf formula, but dim = u.shape[-1] independent of self.k_dim.
    i.e. we are not restricting u to be consistent with self.k_dim (Initially I did not have a k_dim in __init__)

  11. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    Aside:
    Extremevalue copula will implicitly raise if u is not for bivariate because of tuple unpacking.
    u1, u2 = np.asarray(u).T

    to unit tests:

    my test for archimedean test_copulas checks the generic generator construction, but it's also only for bivariate cases in cop_list

  12. josef-pkt commented on Jan 23, 2023

    @josef-pkt
    Member

    another aside:
    archimedean generator classes in transforms don't have docstrings.
    not clear is deriv the derivative of phi or psi (evaluate is phi, inverse is psi), but AFAICS, Hofert et al have derivative of psi.

    based on ArchimedeanCopula.pdf implementation it's phi_deriv
    but AFAIU my old code, the last part computes the second derivative of the inverse function (psi) from the derivatives of phi
    pdfv *= phi_d2(cdfv, *args)
    pdfv /= phi_d1(cdfv, *args)**3

    in analogy to link classes, we need deriv_inverse or deriv2_inverse
    For pdf we need 1st derivative of phi, and k_dim'th derivative of the inverse function psi.

    (IIRC, Before I stopped working on copulas, I was trying to get numerical derivatives out of mathematica, or Wolfram alpha)

  13. Tobi0 commented on Jan 24, 2023

    @Tobi0
    ContributorAuthor

    Wouldn't it be possible to implement the density formulas of Hofert et al for the multivariate pdf?

    side note:
    I looked at the package "pycopula" they use a numeric approach for n>2 but I am only getting complex numbers.

  14. josef-pkt commented on Jan 24, 2023

    @josef-pkt
    Member

    Wouldn't it be possible to implement the density formulas of Hofert et al for the multivariate pdf?

    Yes, that would be best. But it's work that someone needs to do.
    Adding copulas was already a lot of work and I ran out of time and patience to work on more extensions.

    I looked at the package "pycopula" they use a numeric approach for n>2 but I am only getting complex numbers.

    I saw this, but I worried that numerical approximations for higher order might not be very accurate. And the Hofert et al makes it unnecessary for the standard archimedean.

    (Another thing missing are conditional distributions of second dimension or random variable given the first. I had added it only to Frank)

  15. josef-pkt commented on Jan 24, 2023

    @josef-pkt
    Member

    looking again at the special function used by Hofert et al for derivatives

    polylogarithm Li doesn't look so bad, It's not available in scipy.special, it could be computed from Hurwitz zeta function.
    However, AFAICS we only need it for negative integers where it is a finite sum with Sterling second kind numbers.
    https://en.wikipedia.org/wiki/Polylogarithm#Particular_values

    Sterling numbers are also not in scipy.special.
    AFAICS, we can precompute them for given k_dim, independently of evaluation points of pdf or generator function.
    I have not checked yet which indexing we need or whether we can vectorize the required Sterling number computation.

  16. josef-pkt commented on Jan 24, 2023

    @josef-pkt
    Member

    parking this here for now

    Sterling code is from Rosetta Code converted to class for cache
    polylog Li code formulas from Wikipedia
    (I also have a brute force polynomial series function for Li, but finding truncation point is non-trivial, and not needed for negative integer values)

    n = k_dim, but Li argument is -n (defined for first argument is negative integer)

    class Sterling1():
        
        def __init__(self):
            self._cache = {}
        
        def __call__(self, n, k):
            key = str(n) + "," + str(k)
    
            if key in self._cache.keys():
                return self._cache[key]
            if n == k == 0:
                return 1
            if n > 0 and k == 0:
                return 0
            if k > n:
                return 0
            result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)
            self._cache[key] = result
            return result
        
        def clear_cache(self):
            self._cache = {}
    
    sterling1 = Sterling1()
    
    
    class Sterling2():
        
        def __init__(self):
            self._cache = {}
        
        def __call__(self, n, k):
            key = str(n) + "," + str(k)
    
            if key in self._cache.keys():
                return self._cache[key]
            if n == k == 0:
                return 1
            if (n > 0 and k == 0) or (n == 0 and k > 0):
                return 0
            if n == k:
                return 1
            if k > n:
                return 0
            result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
            computed[key] = result
            return result
    
        def clear_cache(self):
            self._cache = {}
            
    sterling2 = Sterling2()
    
    
    def li3(z):
        return z * (1 + 4 * z + z**2) / (1 - z)**4
    
    
    def li4(z):
        return z * (1 + z) * (1 + 10 * z + z**2) / (1 - z)**5
    
    
    def lin(n, z):
        """Polylogarithm for negative integer
        """
        if np.size(z) > 1:
            z = np.array(z)[..., None]
            # raise ValueError("currently only for scalar z")
            
        k = np.arange(n+1)
        st2 = np.array([sterling2(n + 1, ki + 1) for ki in k]) 
        res = (-1)**(n+1) * np.sum(factorial(k) * st2 * (-1 / (1 - z))**(k+1), axis=-1)
        return res
    
  17. josef-pkt commented on Jan 24, 2023

    @josef-pkt
    Member

    @Tobi0
    by the way, Which dimension do you need for the copula?

    I went back to Wolfram alpha, and I can get at least a few analytical derivatives of generators.

  18. josef-pkt commented on Jan 25, 2023

    @josef-pkt
    Member

    I opened PR #8633 for bugfixes and extensions for k_dim > 2

  19. Tobi0 commented on Jan 27, 2023

    @Tobi0
    ContributorAuthor

    Which dimension do you need for the copula?

    at least 20 ...

    I think I can implement generic densities.
    It's probably easier if you merge your PR before.
    Where should I put the sterling code?

  20. josef-pkt commented on Jan 27, 2023

    @josef-pkt
    Member

    gumbel pdf for d=2 looks correct, it passes and passed the unit tests. Unit tests for cdf, pdf for d=2 were already pretty good.
    I didn't check why the formulas in the references differ.

    It would be great if you can implement the densities for general k_dim.
    Now we have several special functions in copulas, so using a new _special.py module in copulas is better as location to collect those, and maybe at some point we can use scipy functions instead.

    When we add the general pdf to the individual archimedean copulas, then sterling numbers can be cached for fixed k_dim.
    I'm not sure whether we can cache the sterling numbers for the generator transforms because they are currently stateless (no stored attributes). I have not checked that yet.

    I'm soon finished with my PR and will merge it. Mainly a final check on raising exceptions for not supported cases.

  21. josef-pkt commented on Jan 27, 2023

    @josef-pkt
    Member

    brief github search for copula in python

    MIT licensed, multivariate rvs for archimedean, arbitrary n_dim
    https://github.com/maximenc/pycop/blob/master/pycop/simulation.py

    I guess, we mainly need to extend the sum, product over more than 2-dim in the current computation

    includes Joe as additional copula

  22. rlucas7 commented on Jun 12, 2023

    @rlucas7
    Contributor

    parking this here for now

    Sterling code is from Rosetta Code converted to class for cache polylog Li code formulas from Wikipedia (I also have a brute force polynomial series function for Li, but finding truncation point is non-trivial, and not needed for negative integer values)

    n = k_dim, but Li argument is -n (defined for first argument is negative integer)

    class Sterling1():
        
        def __init__(self):
            self._cache = {}
        
        def __call__(self, n, k):
            key = str(n) + "," + str(k)
    
            if key in self._cache.keys():
                return self._cache[key]
            if n == k == 0:
                return 1
            if n > 0 and k == 0:
                return 0
            if k > n:
                return 0
            result = sterling1(n - 1, k - 1) + (n - 1) * sterling1(n - 1, k)
            self._cache[key] = result
            return result
        
        def clear_cache(self):
            self._cache = {}
    
    sterling1 = Sterling1()
    
    
    class Sterling2():
        
        def __init__(self):
            self._cache = {}
        
        def __call__(self, n, k):
            key = str(n) + "," + str(k)
    
            if key in self._cache.keys():
                return self._cache[key]
            if n == k == 0:
                return 1
            if (n > 0 and k == 0) or (n == 0 and k > 0):
                return 0
            if n == k:
                return 1
            if k > n:
                return 0
            result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
            computed[key] = result
            return result
    
        def clear_cache(self):
            self._cache = {}
            
    sterling2 = Sterling2()
    
    
    def li3(z):
        return z * (1 + 4 * z + z**2) / (1 - z)**4
    
    
    def li4(z):
        return z * (1 + z) * (1 + 10 * z + z**2) / (1 - z)**5
    
    
    def lin(n, z):
        """Polylogarithm for negative integer
        """
        if np.size(z) > 1:
            z = np.array(z)[..., None]
            # raise ValueError("currently only for scalar z")
            
        k = np.arange(n+1)
        st2 = np.array([sterling2(n + 1, ki + 1) for ki in k]) 
        res = (-1)**(n+1) * np.sum(factorial(k) * st2 * (-1 / (1 - z))**(k+1), axis=-1)
        return res
    

    @josef-pkt the stirling2 code in scipy can be used in place of what you have here (once it is merged) it should be faster in most scenarios b/c the recursive computation from Rosetta code does not cache sub-problems whereas the dp approach in the scipy.special pr will handle that easily. Also,
    it works on numpy arrays and supports all the usual broadcasting.

    One question we're debating on the PR is whether negative values for stirling2 (of n or k) should be a 0 or a Nan. if you'd like to weigh in as a likely future user of the code that would be helpful.

    scipy/scipy#18103

    stirling1 is going to be a separate pr but we'll get to that one too.

  23. josef-pkt commented on Jun 12, 2023

    @josef-pkt
    Member

    @rlucas7
    I'm not an expert in special functions. So, I don't have any opinion on details or support outside of our use case.

    A brief search finds an extension of sterling numbers to negative integer values, at least for both n, k negative and possibly for other cases. https://en.wikipedia.org/wiki/Stirling_number#Stirling_numbers_with_negative_integral_values
    I would return nan instead of zero if either k or n or both are strictly negative to avoid committing on any extension of the function that might not be "appropriate", future proof, supported by theory.

  24. josef-pkt commented on Jan 6, 2025

    @josef-pkt
    Member

    most of this has been fixed in #8633
    issue can most likely be closed

    we need a generic check function that list which methods work or raise for k_dim > 2.
    testcopula.test_copulas_raise is parameterized test for kdim = [5, 6] for pdf and rvs methods.

  25. bashtage commented on Jul 30, 2026

    @bashtage
    Member

    Fixed by PR #8633, which added generic polylog/derivk_inverse machinery for the Archimedean copulas (GumbelCopula, ClaytonCopula) with per-copula fallbacks for k_dim != 2. Closing as fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    comp-distributionstype-bug-wrong

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions