Skip to content

REF: move copula out of sandbox, and refactor, copula directory - #7296

Merged
josef-pkt merged 21 commits into
statsmodels:masterfrom
josef-pkt:copula-move2
Mar 22, 2021
Merged

josef-pkt merged 21 commits into
statsmodels:masterfrom
josef-pkt:copula-move2

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

same/similar commits as #7292 but moving to distributions.copula directory
(cherry-picked and amended each commit of 7292)

@pep8speaks

pep8speaks commented Jan 29, 2021 •

Copy link
Copy Markdown

Hello @josef-pkt! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

There are currently no PEP 8 issues detected in this Pull Request. Cheers! 🍻

Comment last updated at 2021-03-22 15:37:29 UTC

@josef-pkt

Copy link
Copy Markdown
Member Author

last commit is WIP, in the middle of refactoring when discussion about location came up.
comments about this refactoring of u,v and args are in #7292

@lgtm-com

lgtm-com Bot commented Jan 29, 2021

Copy link
Copy Markdown

This pull request introduces 3 alerts and fixes 2 when merging 9270e67 into fb3e061 - view on LGTM.com

new alerts:

  • 1 for Unused local variable
  • 1 for Unused import
  • 1 for 'import *' may pollute namespace

fixed alerts:

  • 2 for Unused local variable

@lgtm-com

lgtm-com Bot commented Jan 29, 2021

Copy link
Copy Markdown

This pull request introduces 3 alerts and fixes 2 when merging d07e424 into fb3e061 - view on LGTM.com

new alerts:

  • 1 for Unused local variable
  • 1 for Unused import
  • 1 for 'import *' may pollute namespace

fixed alerts:

  • 2 for Unused local variable

@josef-pkt

Copy link
Copy Markdown
Member Author

no related failures on azure, linting complaints are mainly unused variables.

this has now unit tests for CopulaDistributions cdf against R, using uniform, and for EVtawn also genextreme

next cleanup and then adding missing pieces

For archimedean maybe define logpdf and add logderiv, defined as log(deriv), and same for deriv2 to transformation. Based on browsing some of the code, that should work better than log(pdf)

@lgtm-com

lgtm-com Bot commented Jan 29, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts and fixes 4 when merging 46de0ea into fb3e061 - view on LGTM.com

new alerts:

  • 2 for Unused local variable

fixed alerts:

  • 4 for Unused local variable

@josef-pkt

josef-pkt commented Jan 29, 2021 •

Copy link
Copy Markdown
Member Author

need to decide on splitting module

from previous PR

api.py
base.py top level Copula class and CopulaDistribution class
copulas.py mainly api file to collect individual copulas
_archimedean, _extreme_value, _other_copulas as private modules (so we are not committed to location, and extensions)
transforms for archimedean DONE
ev_depfunction for ev copula "transforms" (or similar name for module) DONE name depfunc_ev

I'm still not sure
If we have copulas.py with copulas, that still leaves CopulaDistribution as main user class in base

TBC

I don't like two api files: split copulas in 4 public modules, and additional modules if we ever get nested copulas.
Multivariate t distribution PR in scipy.stats added over 400 total lines to _multivariate module which is currently at 4787 total lines. (for comparison, our discrete_model is at 4436 total lines)
multivariate t in scipy has been added in v1.6.0, too new for us for now, I didn't check api/parameterization with what we want.

  • copulas or base with Copula base class, CopulaDistribution and maybe a fit Results class.
  • archimedean
  • extreme_value
  • elliptical
  • other_copulas plackett, independence, min, max as far as available, and nonparametric if or when available

and collect everything in api.py as recommended access, which will also be included in higher level api.py
import statsmodels.distributions.copula.api as cop

other possible modules tools, diagnostic, ... ?

avoiding circular imports: individual copula modules import base but not the other way

special BV classes can be added to individual copula modules, if we really need them.

@lgtm-com

lgtm-com Bot commented Jan 29, 2021

Copy link
Copy Markdown

This pull request introduces 2 alerts and fixes 4 when merging 4619a48 into fb3e061 - view on LGTM.com

new alerts:

  • 2 for Unused local variable

fixed alerts:

  • 4 for Unused local variable

@josef-pkt

josef-pkt commented Jan 29, 2021 •

Copy link
Copy Markdown
Member Author

my guess right now:
Elliptical distributions will get frozen correlation or scatter matrix and not part of params, at least at the beginning, and we don't need mean and scale for distribution based copula.
But the parameterization has to match up with ppf of univariate distribution, so we get uniform margins.
Frozen correlation matrix allows us to store the inverse logdet and similar.

@josef-pkt

Copy link
Copy Markdown
Member Author

namings for ev copulas

I want to change names for authors to commonly used names in extreme value theory, AsyLogisticCopula or AsymLogisticCopula instead of tawn
evd package uses shortcuts e.g. alog, SimCop package use long names like MVAsyLogistic
copulas package uses author names as ev copula option "galambos","gumbel","huslerReiss","tawn","tev" for symmetric versions.
see #7258 (comment)

We need some alias docs or dict for discoverability, e.g. currently I have copulanamesbv dict with some aliases

def copula_power_mv_archimedean(u, transform, alpha, beta, args=(), axis=-1):
'''generic multivariate Archimedean copula with additional power transforms

Nelson p.144, equ. 4.5.2

@josef-pkt josef-pkt Jan 30, 2021 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

section for this is 2-parameter archimedean copulas
a few illustrative examples but no details on them, and not "named"
they are transformations of table 4.1 archimedean copulas

@josef-pkt

Copy link
Copy Markdown
Member Author

I found a Diplomarbeit with derivatives of bivariate extreme value copulas, generic formulas in appendix A
https://mediatum.ub.tum.de/doc/1145695/document.pdf

Also, on page 18 and 19 equ 2.21 - 2.31 has conditional distribution and density for bivariate EV copulas in terms of Pickand's dependence function.
It's nice work that summarizes about ev copulas more than articles or book chapters. Problem is that copula books like Joe 1997 only look at the symmetric cases.

conditional copula/distribution
C2|1(u2|u1) := ∂C(u1, u2) / ∂u1 = C(u1, u2) / u1 * (A(t) − t A'(t))
C1|2(u1|u2) := ∂C(u1, u2) / ∂u2 = C(u1, u2) / u2 * (A(t) + (1 − t)A'(t))

density
c(u1, u2) = C(u1, u2) / u1 u2 * (A(t)**2 + (1 − 2 t) A'(t) A(t) − (1 − t) t (A'(t)**2 - A''(t) / log(u1 u2)
where t = log(u2)/ log(u1 u2)

This needs to wait until I have derivatives of Pickand's dependence functions A

and I ran into Archimax copulas which combine elements of archimedean generator and Pickand's dependence function.
Those copulas can be archimedean, extreme value or neither. (They cannot be both because gumbel is the only one that is both)

In which module would that one go?

@josef-pkt

josef-pkt commented Jan 30, 2021 •

Copy link
Copy Markdown
Member Author

resurrecting another old idea: http://jpktd.blogspot.com/2012/12/visual-inspection-of-random-numbers.html
If we need many random number, we might be better off using interpolation, instead of numerically inverting the cdf separately at each point to get the ppf for sampling.
i.e. we can add an option and memoize the interpolation numbers for 1 set of parameters. Difference to my old experiments is that we simulate in (0, 1) interval instead of real line.

update

I found a paper that I downloaded a long time ago (not read, only 5 citations in google scholar)
Vil'chevskii, N. O., and G. L. Shevlyakov. "On the Bernstein polynomial estimators of distribution and quantile functions." Journal of Mathematical Sciences 105, no. 6 (2001): 2626-2629.

I also saw a recent article, abstract sounds good, but I didn't look at it
Pfeifer, Dietmar; Ragulina, Olena. 2020. "Adaptive Bernstein Copulas and Risk Management" Mathematics 8, no. 12: 2221. https://doi.org/10.3390/math8122221

related aside: scipy.interpolate has a one-dim piecewise bernstein polynomial interpolation and a linear d-dim interpolation class. I have never used either of them.

@lgtm-com

lgtm-com Bot commented Jan 30, 2021

Copy link
Copy Markdown

This pull request introduces 4 alerts and fixes 4 when merging 358c72b into fb3e061 - view on LGTM.com

new alerts:

  • 2 for Unused local variable
  • 2 for Unused import

fixed alerts:

  • 4 for Unused local variable

@josef-pkt

Copy link
Copy Markdown
Member Author

another idea: plot bivariate marginal cdf in multivariate copula

IIRC, the marginal subset cdf just has ones at all other positions, so we can get a cdf_marginal_bv or cdf_marginal_subset that we can use in plotting cdf.
I don't remember seeing a simple generic expression for marginal pdf, that might need partial derivatives w.r.t. subsets of variables.
need to verify

@josef-pkt

josef-pkt commented Jan 30, 2021 •

Copy link
Copy Markdown
Member Author

another idea: reusing scipy distribution generic cdf->ppf inversion and rvs
add private module _conditional to subclass scipy distributions base class and define only conditional cdf

collection for 6 cond. cdf is in Joe 1997 p. 147 (only Frank and an "unknown" copula have closed form ppf)

I guess not. If we want to use our own quasi-random numbers, then we need our own rvs.
We can just put numerical inversion functions in tools.

@josef-pkt

Copy link
Copy Markdown
Member Author

current limitation
args needs to be a tuple of scalars, i.e. copula args ar not vectorized, even though it doesn't raise exception.
The problem is that broadcasting might work, but requires different vectorization or shape for different methods, ie. 1-dim or 2-dim 1-column arrays.
Current behavior, when it works, is likely not be forwards compatible, when we change to fix this.

Usage, e.g. time varying copula correlation, where copula args are modeled as varying by observation, where we have regression case for copargs and not just marginal args.

@tupui tupui mentioned this pull request Feb 5, 2021
1 of 3 tasks
@bashtage

Copy link
Copy Markdown
Member

If the distribution has beta marginal, why is the contour plot not on [0,1]x[0,1]?

@bashtage

Copy link
Copy Markdown
Member

Oh those are integer indices.

@josef-pkt

josef-pkt commented Mar 16, 2021 •

Copy link
Copy Markdown
Member Author

I didn't specify the x-axis in the contour plots. I have those in another notebook but copy pasted the plot part from an earlier version.

Also it would be nice to have the same level sets across plots, but I have not tried to figure out how to set the location of level sets in contour plot.

@josef-pkt

Copy link
Copy Markdown
Member Author

I cleaned up the contourplot and updated the notebook in the gist (plus some dev code to check get_marginal)

Keeping the same levels level sets shows that the peak gets flattened

@lgtm-com

lgtm-com Bot commented Mar 16, 2021

Copy link
Copy Markdown

This pull request introduces 8 alerts and fixes 4 when merging 4bcdd14 into 7d707cf - view on LGTM.com

new alerts:

  • 4 for Unused import
  • 2 for Unused local variable
  • 2 for Variable defined multiple times

fixed alerts:

  • 4 for Unused local variable

@josef-pkt

Copy link
Copy Markdown
Member Author

I'm stopping with Bernstein for now. BernsteinDistribution has all parts that I want or need for now.
(One part that would be useful to add is automatic batch evaluation of bernstein polynomial to avoid exploding memory usage by accident. I added it to asymmetric kernels, but I don't really want to copy-paste it another 2 to 6 times.)

A bit more work on copula code, then I plan to merge this, so @tupui can merge his code into this.

@lgtm-com

lgtm-com Bot commented Mar 17, 2021

Copy link
Copy Markdown

This pull request introduces 8 alerts and fixes 4 when merging 3abd5b9 into 7d707cf - view on LGTM.com

new alerts:

  • 4 for Unused import
  • 2 for Unused local variable
  • 2 for Variable defined multiple times

fixed alerts:

  • 4 for Unused local variable

@josef-pkt

Copy link
Copy Markdown
Member Author

derivatives in last commit for pickands dep func are derived in wolfram alpha and edited by hand to get a compact form

  • still missing derivative for bilogistic and tev depfuncs
    I added numerical derivatives. We need numerical derivatives for the fit method, and we better avoid nested num diff.
  • tawn or tawn2 still has interchanged a1, a2
  • unit tests for ev copula pdf (against R evd package)
  • a few pep-8/lint issues

remove old, now likely redundant code: leave for later when we have case specific methods in classes, currently much is generic in ev and archimedean copula classes

@josef-pkt

Copy link
Copy Markdown
Member Author

related to pdf of EV copulas: use derivatives of copula function directly if that is available

I haven't looked specifically for this yet. Currently, everything in the EV copulas uses the definition through Pickand's dependence function.
We might get better pdf in some cases if we can derive it directly from the cdf/copula function.

@josef-pkt

josef-pkt commented Mar 18, 2021 •

Copy link
Copy Markdown
Member Author

There is likely a bug in the EV copula generic pdf computation from depfunc.
maybe I copied the formula wrongly from the reference, code looks the same as formula

update I didn't manage to fix the pdf based on the reference Diplomarbeit cited above #7296 (comment)

Instead I used "On Densities of Extreme Value Copulas_ma-doyon.pdf" page 22, 23 equ (36).
It's almost the same expression except one part not expanded.
Now I can match copula package for symmetric version of asymlogistic/gumbel, and evd package for the gev copula with asymlogistic and another one (I tried so far only 2).

@josef-pkt

Copy link
Copy Markdown
Member Author

I'm not able to match up pdf of tawn2 AsymMixed copula with evd, also cdf seems to have flipped arguments if second parameter is nonzero (asymmetric case)

I'm not sure they didn't change some definition or parameterization when computing pdf, cdf.
Their pickand's dep function agrees with mine.
I haven't found another R package that has AsymMixed.

So far, all my evd copula code is still generic with only dep functions as case specific.
The plan is now to unit test generic code, and rely that it works correctly for individual cases, even if it doesn't match evd in all cases.

@josef-pkt

josef-pkt commented Mar 19, 2021 •

Copy link
Copy Markdown
Member Author

checking pdf computed with numerical derivative i.e. 2nd cross derivative in bivariate case
cev is a AsymMixed copula with genextreme margins

numdiff pdf agrees with pdf from dep func, (at least at equal u point)
I can use this for consistency testing, independent of other packages

cev.cdf([0.5, 0.5], args3), cev.pdf([0.5, 0.5], args3)
(0.3620623461620781, 0.12908851059185103)

p = np.array([0.5, 0.5])
approx_hess(p, cev.cdf, args=(args3,))
array([[-0.12611335,  0.12908851],
       [ 0.12908851, -0.12620085]])

To roundtrip checking consistency, I will need functions to compute nonparametric estimate of pickand's dep func from rvs and/or a way to compute dep func from copula (cdf or pdf) itself.

I will need some documentation to answer: Why do statsmodels and evd not agree in this?

Or I still have bugs, in pdf or other parts.

@josef-pkt

Copy link
Copy Markdown
Member Author

bugfixes and redefinition like flipping asymmetry

Now matches evd for AsymLogistic, AsymNegLogistic, AsymMixed and HR, for cdf and genextreme copula distribution pdf
The two missing AsymBiLogistic and TEV do not have working dep func derivatives yet.

HR and AsymNegLogistic (joe) have inverted dependence parameter, 1/dep compared to evd

The unit test for ev copulas and ev-gev distribution needs to be reorganized, currently a bit messy in the lists for parameterized unit tests.
test_copulas is still not in the copula subfolder.
I guess I will move it after all, because those unit test modules will get larger and need a results subdirectory.

@lgtm-com

lgtm-com Bot commented Mar 20, 2021

Copy link
Copy Markdown

This pull request introduces 8 alerts and fixes 4 when merging 24f57c7 into 6d4d588 - view on LGTM.com

new alerts:

  • 4 for Unused import
  • 2 for Unused local variable
  • 2 for Variable defined multiple times

fixed alerts:

  • 4 for Unused local variable

@josef-pkt

josef-pkt commented Mar 21, 2021 •

Copy link
Copy Markdown
Member Author

checking briefly book "Statistics of Extremes - Theory and Application" chapter 8 and 9 again
They use A(y2 / (y1 + y2)) in the ev copula which is what I initially used, now I have y1 in numerator, A(y1 / (y1 + y2)) to match R evd

evd has the formula in the notes for abvevd function with A(y1 / (y1 + y2))

the same will apply to stable dependence function
l(v1, v2) = (v1 + v2) * A(v2 / (v1 + v2)) chapter 8, p 268 equ (8,44)
For consistency I will need to change numerator also here.

copula package:
I don't see formulas for ev copulas in their documentation
Book Elements ... (2018) p. 113 equ. (3.12) has multivariate definition and drops the y1 / sum(yi) term, i.e. A(y2 / sum(yi), ..., yd / sum(yi))
where yi = log(u_i)
(but copula package has only exchangable versions of EV copulas.)

The only part that we really want to have is to match index of asymmetry parameters to index of random variable.
i.e. copula and stable dependence functions should have terms a1 y1, a2 y2, ...

otherwise it's just a convention of dropping first or dropping last term for values in simplex.

Also in articles by Genest and coauthors, e.g. for gof, they use A(y2 / (y1 + y2)) or my initial A(log(v) / log(u v))
Those articles were my initial source for the code.

@lgtm-com

lgtm-com Bot commented Mar 21, 2021

Copy link
Copy Markdown

This pull request introduces 4 alerts and fixes 4 when merging 60be727 into 6d4d588 - view on LGTM.com

new alerts:

  • 4 for Unused import

fixed alerts:

  • 4 for Unused local variable

@lgtm-com

lgtm-com Bot commented Mar 22, 2021

Copy link
Copy Markdown

This pull request introduces 4 alerts and fixes 4 when merging 25d197a into 6d4d588 - view on LGTM.com

new alerts:

  • 4 for Unused import

fixed alerts:

  • 4 for Unused local variable

@josef-pkt

Copy link
Copy Markdown
Member Author

all green (1 unrelated test failure with pandas in pre-release testing)

merging,

@josef-pkt
josef-pkt merged commit 4cf8feb into statsmodels:master Mar 22, 2021
@josef-pkt

Copy link
Copy Markdown
Member Author

@tupui it's merged

@tupui

tupui commented Mar 22, 2021

Copy link
Copy Markdown
Contributor

@tupui it's merged

Great thanks! I will update my PR and let you know then.

@josef-pkt josef-pkt added this to the 0.13 milestone Apr 5, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants