You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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.
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)
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")
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.
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)
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
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__)
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)
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)
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.
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
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.
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.
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.
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.
Activity
josef-pkt commentedon Jan 23, 2023
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
psias generator while we usephi, where one is the inverse function of the other.josef-pkt commentedon Jan 23, 2023
AFAICS, we only have unit test for bivariate Gumbel
It looks like all copula unit tests are only for bivariate case, dim=2
josef-pkt commentedon Jan 23, 2023
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. ???
josef-pkt commentedon Jan 23, 2023
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.
josef-pkt commentedon Jan 23, 2023
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.
josef-pkt commentedon Jan 23, 2023
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 usefulSo we can raise in methods if the evaluation point
udoes not haveu.shape(-1) == self.k_dimcurrently we only use
u = np.atleast_2d(u)but no checks in pdf and other methods.logpdfof superclass ArchimedeanCopula already does this, it raises explicitly for dim >2, independently of k_dimjosef-pkt commentedon Jan 23, 2023
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
josef-pkt commentedon Jan 23, 2023
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
dimin the explicit cdf formula, butdim = u.shape[-1]independent ofself.k_dim.i.e. we are not restricting
uto be consistent withself.k_dim(Initially I did not have a k_dim in__init__)josef-pkt commentedon Jan 23, 2023
Aside:
Extremevalue copula will implicitly raise if
uis not for bivariate because of tuple unpacking.u1, u2 = np.asarray(u).Tto unit tests:
my test for archimedean
test_copulaschecks the generic generator construction, but it's also only for bivariate cases incop_listjosef-pkt commentedon Jan 23, 2023
another aside:
archimedean generator classes in
transformsdon't have docstrings.not clear is
derivthe derivative of phi or psi (evaluateis phi,inverseis 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)
Tobi0 commentedon Jan 24, 2023
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.
josef-pkt commentedon Jan 24, 2023
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 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)
josef-pkt commentedon Jan 24, 2023
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.
josef-pkt commentedon Jan 24, 2023
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)
josef-pkt commentedon Jan 24, 2023
@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.
josef-pkt commentedon Jan 25, 2023
I opened PR #8633 for bugfixes and extensions for k_dim > 2
Tobi0 commentedon Jan 27, 2023
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?
josef-pkt commentedon Jan 27, 2023
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
specialfunctions in copulas, so using a new_special.pymodule 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
transformsbecause 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.
josef-pkt commentedon Jan 27, 2023
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
rlucas7 commentedon Jun 12, 2023
@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
stirling1is going to be a separate pr but we'll get to that one too.josef-pkt commentedon Jun 12, 2023
@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.
josef-pkt commentedon Jan 6, 2025
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_raiseis parameterized test for kdim = [5, 6] for pdf and rvs methods.bashtage commentedon Jul 30, 2026
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.