Skip to content

Copula 7254 rebased - #7408

Merged
josef-pkt merged 26 commits into
statsmodels:mainfrom
josef-pkt:copula_7254_rebased
Jul 25, 2021
Merged

josef-pkt merged 26 commits into
statsmodels:mainfrom
josef-pkt:copula_7254_rebased

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

amending last commit and getting unit tests to pass

@josef-pkt

Copy link
Copy Markdown
Member Author

unit test only fail with missing matplotlib
and a few pep-8 complaints

@josef-pkt

josef-pkt commented Apr 7, 2021 •

Copy link
Copy Markdown
Member Author

coverage report codecov looks screwed up.
None of my unit test already in main are run anymore according to codecov
(but I'm pretty sure thwy were run locally on my computer.)

update the parameterized tests fail locally if I change numbers in the results lists. So codecov coverage changes tab doesn't make sense

new tests are also run locally, but lines don't show test coverage, e.g. using -v

..\eclipse_ws\statsmodels\statsmodels_py37_main\statsmodels\statsmodels\distribu
tions\copula\tests\test_copula.py::TestGumbelCopula::test_pdf PASSED [ 95%]
..\eclipse_ws\statsmodels\statsmodels_py37_main\statsmodels\statsmodels\distribu
tions\copula\tests\test_copula.py::TestGumbelCopula::test_cdf PASSED [ 97%]
..\eclipse_ws\statsmodels\statsmodels_py37_main\statsmodels\statsmodels\distribu
tions\copula\tests\test_copula.py::TestGumbelCopula::test_validate_params PASSED
 [ 98%]
..\eclipse_ws\statsmodels\statsmodels_py37_main\statsmodels\statsmodels\distribu
tions\copula\tests\test_copula.py::TestGumbelCopula::test_random_follow_pdf PASS
ED [100%]

@josef-pkt
josef-pkt force-pushed the copula_7254_rebased branch from 3cce758 to 0b1ed35 Compare April 7, 2021 21:59
@pep8speaks

pep8speaks commented Apr 7, 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-07-24 01:08:11 UTC

@josef-pkt

josef-pkt commented Apr 8, 2021 •

Copy link
Copy Markdown
Member Author

error 1E AttributeError: module 'scipy.stats' has no attribute 'multivariate_t'1
in test using scipy 1.3.3

statsmodels/distributions/copula/tests/test_copula.py:344: in TestStudentCopula

scipy.stats.multivariate_t is "New in version 1.6.0."

if cov is None:
cov = [[1., 0.], [0., 1.]]
self.density = stats.t(df=df)
self.mv_density = stats.multivariate_t(shape=cov, df=df)

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.

misleading names:
those are distribution instances and not densities/pdf

@josef-pkt
josef-pkt force-pushed the copula_7254_rebased branch 2 times, most recently from 43b6bd4 to a4e399c Compare April 9, 2021 17:18
@josef-pkt

Copy link
Copy Markdown
Member Author

something weird

why is pytest running the __init__ of a class that does not start or end in Test?
class name is _estStudentCopula, super class also doesn't have test in name anymore

____ ERROR collecting statsmodels/distributions/copula/tests/test_copula.py ____
statsmodels/distributions/copula/tests/test_copula.py:342: in <module>
    class _estStudentCopula(CheckCopula):
statsmodels/distributions/copula/tests/test_copula.py:343: in _estStudentCopula
    copula = StudentCopula(cov=[[1., 0.8], [0.8, 1.]], df=2)
statsmodels/distributions/copula/elliptical.py:68: in __init__
    self.mv_density = stats.multivariate_t(shape=cov, df=df)
E   AttributeError: module 'scipy.stats' has no attribute 'multivariate_t'
____ ERROR collecting statsmodels/distributions/copula/tests/test_copula.py ____
statsmodels/distributions/copula/tests/test_copula.py:342: in <module>
    class _estStudentCopula(CheckCopula):
statsmodels/distributions/copula/tests/test_copula.py:343: in _estStudentCopula
    copula = StudentCopula(cov=[[1., 0.8], [0.8, 1.]], df=2)
statsmodels/distributions/copula/elliptical.py:68: in __init__
    self.mv_density = stats.multivariate_t(shape=cov, df=df)
E   AttributeError: module 'scipy.stats' has no attribute 'multivariate_t'

trying again, this time commented out the test class
amended and force pushed

@josef-pkt

Copy link
Copy Markdown
Member Author

Ok that was it.

pytest didn't run the full test suite. It skipped more than just the (non-test) class that had an error, i.e. stopped collecting. pytest :(
Now test coverage is back up to 75%,
archimedean, elliptical and others are mostly covered, ev is unchanged

@tupui

tupui commented Apr 23, 2021

Copy link
Copy Markdown
Contributor

Just seeing this, shall I close #7254 then? What's the plan here @josef-pkt? Let me know if I can still be of help, even just for reviewing it's fine.

@josef-pkt

josef-pkt commented May 10, 2021 •

Copy link
Copy Markdown
Member Author

We need a copy of multivariate_t for compatibility with scipy < 1.6
Currently I use the copied version unconditionally to check behavior across versions.
I will make it conditional on scipy <1.6 later.

I also left currently the multivariate_normal in the compat module. I don't think we need it, but I have not checked that.

azure is all green except for style check, mainly line breaks in copied scipy code, needs a pep8 E501 ignore

edit
that was silly. I forgot to uncomment the unit test, so the multivariate_t compat didn't run.

@josef-pkt
josef-pkt force-pushed the copula_7254_rebased branch from ea8a6fb to 094bc47 Compare May 10, 2021 17:58
@josef-pkt

Copy link
Copy Markdown
Member Author

aside: this # flake8: noqa: E501 on top of the file worked in azure style check. no more complaints about long lines in scipy copy

@josef-pkt
josef-pkt force-pushed the copula_7254_rebased branch from 094bc47 to 84f01f0 Compare May 11, 2021 04:47
@josef-pkt

Copy link
Copy Markdown
Member Author

now all green including style check
unit test coverage looks ok (> 80%) except for copulas.py (old code, plot method)

trying out:

plot requires dimension d=2
GaussianCopula has d=inf


ValueError Traceback (most recent call last)
in
1 cop = GaussianCopula(cov=[[1., 0.8], [0.8, 1.]])
----> 2 _ = cop.plot_pdf(10)

m:\josef_new\eclipse_ws\statsmodels\statsmodels_py37_main\statsmodels\statsmodels\distributions\copula\copulas.py in plot_pdf(self, ticks_nbr, ax)
414 from matplotlib import pyplot as plt
415 if self.d != 2:
--> 416 raise ValueError("Can only plot 2-dimensional Copula.")
417
418 n_samples = 100

ValueError: Can only plot 2-dimensional Copula.


also ZeroDivision Warning in plot for GaussianCopula

@josef-pkt

Copy link
Copy Markdown
Member Author

StudentCopula has default df=1
Either we don't set a default or we set it too a larger value.

I got a bit surprised because the contourplot for T copula with gaussian margins looks almost like an X (tilted cross)

with df=3 or 4, the contour/scatter plot looks more like a trapezoidal ellipsoid

@josef-pkt

Copy link
Copy Markdown
Member Author

naming/terminology

elliptical distribution cov/corr/scatter/shape matrix What do we call it?
in gaussian the matrix is pearson correlation
in mv-t the matrix does not correspond to cov of distribution, scipy uses shape matrix.

correction: AFAICS, standard mv-t shape matrix is the same as the correlation matrix. Variance and cov depend on df and scale, and standard t, mv-t (scale=1) does not have unit variance, but df term should cancel when we compute pearson correlation.

-> use corr or pearson_corr for shape matrix in Gaussian and t copulas, instead of current cov.

@lgtm-com

lgtm-com Bot commented May 14, 2021

Copy link
Copy Markdown

This pull request introduces 4 alerts when merging 33a990f into 4956b3b - view on LGTM.com

new alerts:

  • 4 for Unused import

@josef-pkt

josef-pkt commented May 18, 2021 •

Copy link
Copy Markdown
Member Author

unit tests: unnecessary repeated sampling sample = self.copula.random(10000)

Gumbel margins test just failed locally
I added a seed somewhere and it changes random numbers. Unit tests don't have fixed seed.

random draws from copula do not satisfy uniform marginal frequencies, even if the distribution is uniform
fragile test

___________________ TestGumbelCopula.test_uniform_marginals ___________________

self = <test_copula.TestGumbelCopula object at 0x00000065C57448E0>

    def test_uniform_marginals(self):
        sample = self.copula.random(10000)
        assert_array_almost_equal(
            np.mean(sample, axis=0), np.repeat(0.5, self.dim), decimal=2
        )
>       assert_array_almost_equal(
            np.percentile(sample, 25, axis=0), np.repeat(0.25, self.dim),
            decimal=2
        )
E       AssertionError:
E       Arrays are not almost equal to 2 decimals
E
E       Mismatched elements: 1 / 2 (50%)
E       Max absolute difference: 0.01683089
E       Max relative difference: 0.06732357
E        x: array([0.23, 0.25])
E        y: array([0.25, 0.25])

...\statsmodels\statsmodels\distributions\copula\tests\test_copula.py:324: AssertionError

I'm currently writing a unit test for random that assert a chisquare test outcome for approximately correct distribution of rvs

@lgtm-com

lgtm-com Bot commented May 18, 2021

Copy link
Copy Markdown

This pull request introduces 4 alerts when merging a816c0e into d2a4e6f - view on LGTM.com

new alerts:

  • 4 for Unused import

@josef-pkt

Copy link
Copy Markdown
Member Author

two unrelated errors in azuere testing
windows 3.8 fails to install Building wheel for pywinpty (PEP 517): finished with status 'error'
linux pre has a test error which looks like scipy.spatial pdist changes

this PR is still green, including style check

# this means marginals are independents
sample = rng.random((n, self.d))
else:
sample = self.copula.random(n, random_state=random_state)

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.

why does this not use rng?
what is return of check_random_state

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It's a typo and should read sample = self.copula.random(n, random_state=rng). check_random_state returns an instance of RandomState or Generator (only if a generator was passed).

@josef-pkt

Copy link
Copy Markdown
Member Author

_rankdata_no_ties should be 1- based, currently it's zero based. BUG
I need to check options for "plotting positions" in usage of ranks for copulas

our current univariate ECDF uses y = np.linspace(1./nobs,1,nobs) i.e. no slack, like `arange(1, nobs + 1) / nobs
For distributions we don't have in general fixed finite support bounds
For copulas, we require [0, 1]. and use plotting position to stay away from boundary or only from lower boundary.
( I guess it depends on whether we want points or bins #7454 )

plotting_pos function is in statsmodels.graphics.gofplots
aside: class ProbPlot only uses a but not b parameter: plotting_pos(self.nobs, self.a)

b = a if b is None else b
return (np.arange(1.0, nobs + 1) - a) / (nobs + 1 - a - b)

a=b=0 is "weibull" 1 ... n / (n + 1)
a=b=0.5 is "hazen" ({1 ... n} - 0.5) / n
names in copBasic docs

@josef-pkt

Copy link
Copy Markdown
Member Author

maybe I shouldn't ignore ties for ecdf, rankdata
example elnino monthly temperature dataset . Data is rounded to two decimals and has ties
first column is year, others are temp by months

(np.diff(np.sort(dta.data.values, axis=0), axis=0) == 0).sum(0)
array([0, 8, 6, 5, 6, 4, 6, 9, 6, 1, 5, 5, 5])

I started unit test against R copBasic with this, but arbitrary tie breaking looks fragile and might agree only as long as same sorting algorithm is used across packages. (For Hosmer-Lemeshow grouping I also had tie breaking differences by sort algorithm or tie breaking rules.)

I think brute force ecdf on non-ranked data is unique. Other cases might not produce correct ecdf with ties.
That would require rankdata with ties in ranking, and no sequential search (my speedup for bivariate case).

@josef-pkt

Copy link
Copy Markdown
Member Author

design: make dimension a __init__ keyword.

We need copula parameters as method arguments at least for some methods like logpdf/loglike. But we can treat the dimension of the model as fixed. In some cases I kept it currently implicit, e.g. determining dimension from values of random variable u.

One reason to do that is that we might precompute some intermediate results for fixed dimension.

e.g. Hofert et al have explicit formulas for multi-dimensional pdf/logpdf of 5 archimedean copula families. Gumbel and Joe have a finite sum term that is indepenend of u, however not independent of copula parameter and dimension.

Frank and AMH are messier because they have infinite sum, polylogarithm that doesn't exist in scipy.special. That sum also depends on u.

Hofert, Marius, Martin Mächler, and Alexander J. McNeil. 2012. “Likelihood Inference for Archimedean Copulas in High Dimensions under Known Margins.” Journal of Multivariate Analysis, Special Issue on Copula Modeling and Dependence, 110 (September): 133–50. https://doi.org/10.1016/j.jmva.2012.02.019.

@josef-pkt
josef-pkt force-pushed the copula_7254_rebased branch from 83f71a1 to 9835ee6 Compare July 23, 2021 22:56
@josef-pkt

Copy link
Copy Markdown
Member Author

rebased on current main

@lgtm-com

lgtm-com Bot commented Jul 23, 2021

Copy link
Copy Markdown

This pull request introduces 6 alerts when merging 9835ee6 into d2f6634 - view on LGTM.com

new alerts:

  • 4 for Unused import
  • 2 for Syntax error

@josef-pkt

josef-pkt commented Jul 24, 2021 •

Copy link
Copy Markdown
Member Author

it looks like the last commit was unfinished refactoring adding random_state. has syntax error
tau_simulated(self, nobs=1024, random_state=):

amended and force pushed

@josef-pkt
josef-pkt force-pushed the copula_7254_rebased branch from 9835ee6 to 1cc0da2 Compare July 24, 2021 01:08
"""

def __init__(self, d):
self.d = d

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.

no one letter names
k_dim or k_vars

rng = check_random_state(random_state)
if self.copula is None:
# this means marginals are independents
sample = rng.random((nobs, self.d))

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.

this should go through independence copula, not here in base class

@lgtm-com

lgtm-com Bot commented Jul 24, 2021

Copy link
Copy Markdown

This pull request introduces 4 alerts when merging 1cc0da2 into d2f6634 - view on LGTM.com

new alerts:

  • 4 for Unused import

@josef-pkt

josef-pkt commented Jul 24, 2021 •

Copy link
Copy Markdown
Member Author

insuffient unit test coverage in several modules https://codecov.io/gh/statsmodels/statsmodels/tree/copula_7254_rebased/statsmodels/distributions/copula

copulas.py still contains old code, not covered
other_copulas.rvs_kernel added in last commit has not unit tests
archimedean.py missing test coverage mainly for tau related methods
elliptical.py tau, rho related methods and tail
depfunc_ev.py mainly no coverage for _check_args
extreme_value 100% coverage
is_completly_monotonic only method is_completly_monotonic is not covered

distributions.tools.py no coverage for _ecdf_mv function

_ecdf_mv returns counts and not plotting positions.

@josef-pkt

Copy link
Copy Markdown
Member Author

based on my latest notebook (before the break) I was working on ecdf and beta kernel.
dataset elnino using two months would work nicely, except that there are ties that ecdf is not designed to handle.

AFAICS, I didn't manage to replicate this with package library(copBasic) with something like

> fakeV <- lmomco::pp(en2[,2], sort=FALSE) # Weibull plotting position i/(n+1)
> uv <- data.frame(U=fakeU, V=fakeV); # our U-statistics
> empcop <- EMPIRcopdf(para=uv)

en2 is elnino with april and august in the two columns

@josef-pkt

Copy link
Copy Markdown
Member Author

@tupui I will merge this today.
It still needs work before the release, but I will be travelling and sightseeing for the next two weeks.

You could add missing pieces if you have time.

One part that needs to be cleaned up and added to is the kendall tau support. We need either analytical functions or numerical integration for those. I added some analytical tau function, to elliptical, gumbel and clayton.
Also, we need the inverse function for tau to get the copula correlation from tau. I don't know how much we have there.

extreme value copulas will not have a tau or inverse tau directly, because those all have more than one parameter.
I don't know yet how to support the symmetric special cases for the extreme value copulas.

currently only Frank has conditional distribution of the second rv given the first rv: cdfcond_2g1, ppfcond_2g1

We might be able to support main parts pdf, cdf for more than two dimension in some Archimedean copulas, maybe gumbel or clayton ?

@josef-pkt
josef-pkt merged commit 4e2cf05 into statsmodels:main Jul 25, 2021
@josef-pkt

Copy link
Copy Markdown
Member Author

I forgot to push my latest changes using amend

ArchimedeanCopula.cdf and other methods have two docstrings. I fixed it but didn't push it before merging.

@josef-pkt
josef-pkt deleted the copula_7254_rebased branch July 25, 2021 04:04
@tupui

tupui commented Jul 25, 2021

Copy link
Copy Markdown
Contributor

Thanks for merging @josef-pkt

I will see if I have some time for tau.
Also before the release it would need some user friendly documentation on how to use this. I can try to propose something. Where should this go?

@tupui tupui mentioned this pull request Jul 25, 2021
1 of 3 tasks
@josef-pkt

Copy link
Copy Markdown
Member Author

Some overview description can go into the module docs. I think GLM has the most of that.

examples for usage go into notebooks.
Notebooks that are added to the repository need to be empty in the PR, so we don't increase the size of a checkout with machine generated data, plots, ...
We can use a gist for developing a notebook so we can see the output.

I have several notebooks that I started out as usage examples, but then become development notebooks when I needed to try out new features.

@tupui

tupui commented Jul 26, 2021 •

Copy link
Copy Markdown
Contributor

@josef-pkt Something else, would it be ok if I added support for QMC? There would not be much to do. We are using rng.random all around and we would just need to somehow allow QMCEngine.random, I could write a small wrapper for it.

Either way the current check_random_state is not the best solution as it's a private method we should not rely too much on. So I could write a new one for statsmodels if you want, with the requirements you want. I can also just copy it and add support for passing along QMCEngine.

@josef-pkt

Copy link
Copy Markdown
Member Author

Yes to both
Random state helper function should go into statsmodels.tools, I think

Qmc would be good to add, but many copula rvs are based on mixtures, and those will not have proper properties.
We need conditional ppf to support qmc rvs

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.

3 participants