Skip to content

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

Closed
josef-pkt wants to merge 3 commits into
statsmodels:mainfrom
josef-pkt:copula_move
Closed

josef-pkt wants to merge 3 commits into
statsmodels:mainfrom
josef-pkt:copula_move

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Jan 27, 2021 •

Copy link
Copy Markdown
Member

first commit is just a full move to keep history

no refactoring yet

planned module outline

  • first part in copula module are copula function, those can be deleted when we have copula specific classes for those
  • second part should be base class and classes for generating copulas, CopulaArchimedean, CopulaEV is currently only a function.
    For elliptical copulas we don't have enough generic code to add a specific base class
  • third part is specific copulas, copula specific code, possibly restricted to BV
    • Archimedean
    • EV
    • others, normal, t (i.e. elliptical), and ones that don't fit a generator pattern, e.g. Plackett
    • special copulas, e.g. independence
  • last part CopulaDistribution, classes that include marginal distributions. only base class without specific marginal distributions
    (this could go also in the second part after copula generating base classes

open question: do we add copulas with extra transformation, e.g. power transformed archimedean currently only copula_power_mv_archimedean function,
For Archimedean and EV we might be able to use transform-the-transform classes to transforms_copula,
Power transform works on archimedean generator function, and, IIRC, there are transforms for Pickand's dependence functions for EV copulas.
I don't know if there should be generic copula (extra) transforms that work also for non-Archimedean, non-EV copulas.

@pep8speaks

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:

Line 20:1: F401 'statsmodels.distributions.transforms_copula.transform_bilogistic' imported but unused
Line 20:1: F401 'statsmodels.distributions.transforms_copula.transform_hr' imported but unused
Line 20:1: F401 'statsmodels.distributions.transforms_copula.transform_joe' imported but unused
Line 20:1: F401 'statsmodels.distributions.transforms_copula.transform_tawn' imported but unused
Line 20:1: F401 'statsmodels.distributions.transforms_copula.transform_tawn2' imported but unused
Line 20:1: F401 'statsmodels.distributions.transforms_copula.transform_tev' imported but unused

@josef-pkt

josef-pkt commented Jan 27, 2021 •

Copy link
Copy Markdown
Member Author

names:
use XXXCopula,
rename CopulaArchimedean -> ArchimedeanCopula

we lose sorting if copulas are part of larger namespace, but "Copula" is more like "Model" and used in context.

Do we put "BV" in name for bivariate?
The problem will be if we hardcode the special bivariate case, and the we want to extend it. We will need branching in methods between bv and mv case.
I guess we can ignore this for now and make restriction to bv implicit (docs and exceptions)
R copula package mentions in docstring that EV copulas are all restricted to bivariate.

  • for Archimedean we can use the generic class ArchimedeanCopula for multivariate dim > 2
  • elliptical don't need a restriction to bv, except if we want bv numerical integration.
  • IIRC, gumbel is the only one with nice MV functions including mv pdf
  • for EV we might get at most mv with a few more dimension, e.g. special code for dim = 3.

@lgtm-com

lgtm-com Bot commented Jan 27, 2021

Copy link
Copy Markdown

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

new alerts:

  • 2 for Unused local variable
  • 1 for Unused import

fixed alerts:

  • 2 for Unused local variable

@josef-pkt

Copy link
Copy Markdown
Member Author

possible ENH that works as usage and test case
add distributions.extreme.BVGenExtreme
EV copula with scipy genextreme margins, modelled after the distribution in R evd package.
I used that evd class already for unit tests and had to back out the genextreme margins.

@josef-pkt

josef-pkt commented Jan 27, 2021 •

Copy link
Copy Markdown
Member Author

params/args

#7254 has theta in __init__
we need them in methods as args/params, and additional marginal params in CopulaDistribution
ev copulas have asymmetry params additional to correlation params

mv elliptical copulas will have correlation matrix, but we might not want to estimate correlation matrix as part of full MLE.
scipy: kendalltau is only for one pair of variables, spearmanrho returns correlation matrix.

How do we handle fixed or frozen params?

one of the original designs used expand_params to allow for fixed params, example in TLinearModel
https://github.com/statsmodels/statsmodels/blob/master/statsmodels/miscmodels/tmodel.py#L62

update

I have problems with args unpacking, *args, during refactoring, when args already turned into a scalar.

naming
args tuple-like, will be *args unpacked
params array-like, pooled parameters that will be unpacked if needed according to numpy rules

Parameters that don't need to have the same shape should be args, unless we want to force them into matching arrays, like e.g. weights in WLS.

When do we use args in signature, and when *args?
e.g. ArchimedeanCopula.cdf has args=None, no unpacking
copula functions and generator methods of individual args, i.e. need to be called with *args

methods of CopulaDistribution cannot have *args in signature, because we need copargs and margin_args, where margin_args is list of tuple-like args.
*args wouldn't distinguish between args for copula and each component

@josef-pkt

josef-pkt commented Jan 28, 2021 •

Copy link
Copy Markdown
Member Author

unit test for tawn doesn't have an asymmetric case
asymmetry parameters are reversed order compared to evd

evd:

> pbvevd(qgev(c(0.5,0.9)), dep = 0.25, asy = c(0.5, 0.1), model = "alog")
[1] 0.4547663
copula_bv_ev(0.5, 0.9, cop.transform_tawn, args=(0.1, 0.5, 0.25))
0.45476625438619633

current code comment in unit test seems to apply only for tawn2, but should also be for tawn
# note evd has asymmetry reversed, interchange variables
update tawn2 doesn't have two asymmetry parameter, so code comment must refer to tawn.
code comment ambiguous location and is not explicit about which copula
I think this should be reversed in our version. pattern matching with joe (negative logistic): joe has a1 * t, tawn has a1 * (1 - t) in dependence function. Maybe checking a plot helps to see the effect.

this needs another check

trying example EV copula distribution with genextreme/gev margins

R evd

> pbvevd(c(0.5,0.9), dep = 0.25, asy = c(0.5, 0.75), model = "alog")
[1] 0.464615422654154

mine, current interface before refactoring:

def cop_tawn(u, v, *args):
    return copula_bv_ev(u, v, cop.transform_tawn, args=args)

evt = CopulaDistribution([stats.genextreme(0).cdf, stats.genextreme(0).cdf], cop_tawn, copargs=(0.75, 0.5, 0.25))
evt.cdf([0.5, 0.9])
0.464615422654154

@josef-pkt

Copy link
Copy Markdown
Member Author

still undecided:
Should the transformation method in Transform classes be evaluate (here), transform (my univariate PR) or __call__ (links) or any combination or all of them?

I like transform, but in copulas those are generator functions (*) and not really transformations of something.

(*) Pickands dependence function, or (inverse ?) Laplace transform for positive dependence in Archimedean, otherwise just "generator functions"

but Laplace transform even has transform in the name. (but I only know characteristic function and moment generating functions which don't have transform in the name)

aside elliptical distributions also have "generator functions"

transform it is,
also inverse is more appropriate and explicit with transform than with evaluate (what's inverse-evaluate?)

@josef-pkt

Copy link
Copy Markdown
Member Author

unpacking components is a mess
I don't manage to get CopulaDistribution to work with Archimedean Copula class in a clean way.

in bivariate case we have unpacking x, y = xy and use x, y for margins and corresponding u, v for copula functions.

bivariate copula functions need to be converted to use a single u and unpack to u, v, but those functions will go away.
copula classes only use u for packed random variable.
we need to unpack for the marginal distributions

unpacking for marginal distributions:
conflict between python/pandas and numpy in iteration axis
The options are to either assume numpy (asarray) and iterate over last axis, i.e. columns, or to do an isinstance check

  • list is out, only allowed for one multivariate observation, or needs to be transposed
  • do we allow pandas? main usecase would be in CopulaModels
    Not, at least for now.

conclusion: use np.asarray and assume iterating is along last axis. That makes it simpler.

@josef-pkt

josef-pkt commented Jan 28, 2021 •

Copy link
Copy Markdown
Member Author

args or *args continued from above #7292 (comment)

we have both options for methods in Copula classes, require a tuple like arg as currently in ArchimedeanCopula and copula_bv_ev (cdf), or allow individual args, so it needs to be called with *args

For indvidual XXXCopula it would be nicer to have explicitly named args. The generator, transformation functions and methods use explicit arguments.

How about nested copulas?
I never looked closely, but recursive calls will need consistent interface, e.g. copula cdf calling a nested copula.cdf. That's similar to CopulaDistribution that needs to call copula cdf and marginal cdfs.
Marginal cdfs will need unpacked *args for scipy distribution compatibility.

I'm not a fan of *args but modern Python allows named keywords after *args (in contrast to old times)

#7254 doesn't have parameters/args in method, only in __init__ for fixed parameters.

still undecided

update I'm sticking with args for now in copulas, and use *args only with generators and marginal distributions.

old copula functions, at top of module, will not be compatible anymore

It's a bit messy because most current copulas only have a single parameter and we need to pack it.
maybe we should special case, single parameter.

another problem with args: it's not optional, What if there are no args?
only relevant for special copulas like independence, min and max

@josef-pkt

Copy link
Copy Markdown
Member Author

current decision on frozen args/params:

make it all or nothing, i.e. cop args can be set in __init__ to have them as fixed params,
but we don't support fixing only some copula parameters. (most copulas have only one parameter anyway)

@josef-pkt

josef-pkt commented Jan 28, 2021 •

Copy link
Copy Markdown
Member Author

random thought: add class transforms.Chain to nest transformations g(f(x))

aside: scipy has uniform distribution stats.uniform that can be used as "dummy" or identity marginal distribution.

# Extreme Value Copulas
# =====================

def copula_bv_ev(u, v, transform, args=()):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why not put these in their own module, so that you would have

distributions/copula/init.py
distributions/copula/bv.py
distributions/copula/mv.py
< and possibly others>

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.

Right now my plan was only to have two modules, not to build a full copula package, and I thought a longer namespace is not needed. If we plan to add nested and vine copulas, then this would get larger. But I will not be working on those.
(in an old private refactoring of sandbox.distributions, I had added subdirectories.)

bv and mv cannot be split nicely because it's mainly computational restrictions case by case, and I don't know yet how far we will get with mv.

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.

Checking my old code.
I have many subdirectories of sandbox.distributions, but most only contain one or two modules

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.

As a first step I would also restrict this to the bivariate case. Except for Gaussian, independent and t which can easily be n-dim. Otherwise it's a too big enterprise IMO

License: BSD-3

"""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Would also make more sense to be in distributions/copula/transforms.py rather than using file names to sort of create namespace.

@josef-pkt

Copy link
Copy Markdown
Member Author

when I move dEV Pickand's dependence function into transforms, I didn't think about that they are not monotonic, they are u-shaped and we don't need inverse functions. They only have one side of the transform, we still need deriv.

If we use a copula subdirectory, then we can add a separate module for ev_generators or pdep_functions.

subdirectory yes or no?

If we get closer to https://github.com/blent-ai/pycopula/tree/master/pycopula and https://github.com/sdv-dev/Copulas/tree/master/copulas then we need more modules
e.g. each bivariate archimedean in Copulas is around 150 lines (total, not loc)
Neither of the two has EV copulas

Currently we only need two modules, but that limits expanding this part.

Our copula is just tools, distribution code, models and applications will go somewhere else.
E.g. extreme value applications into an extreme or extreme_mv module or subpackage, similar to R package evd
Regression models, CopulaModel might go into multivariate

If we do a full splitting of copulas, then we need to decide on api access paths, i.e. do we make private modules,
e.g. split by category, we have base, archimedean, ev, other, possibly with distinction mv versus restricted to bv.

estimation/fit:

  • Archimedean can rely on kendallstau or spearmans rho for single parameter
  • elliptical, t, normal: need correlation matrix in mv case, a single correlation in bv case, kendallstau or spearmans rho
  • ev: with asymmetry parameters we need MLE, with fixed symmetry we can use same as Archimedean
  • generic: MLE, with parametric or nonparametric margins

@josef-pkt

Copy link
Copy Markdown
Member Author

We also still need some diagnostics module, e.g. gof and estimators for pickands dependence function
maybe separate nonparametric.
However, some of those might not be copula specific,
eg extreme value applications of EV copulas, gof might partially be for multivariate distributions

related then, do we get a statsmodels.distributions.multivariate subdirectory?, e.g. with elliptical and skew-elliptical distributions

sandbox has multivariate normal and multivariate t, now largely superseded by scipy distributions.
I'm looking at elliptical distributions on and off, but no specific plans for near future. (I still haven't figured out what's really useful besides normal and t.)
my sandbox mv-t is a subclass of mv-elliptical MVT(MVElliptical) in module mv_normal

subdirectory copula it is

I don't like large number of public modules
e.g.
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
ev_depfunction for ev copula "transforms" (or similar name for module)

ArchimedeanCopula and ExtremeValueCopula might need to go into the corresponding module, not in base.
transforms and ev_depfunctions can be public because they will not be changed much, except ENH, and needed when creating copulas using generic class.

What does fit with MLE return? We get full Results, including standard errors and hypothesis testing.
results classes in base when we get them?

@josef-pkt

Copy link
Copy Markdown
Member Author

restriction to bivariate

@tupui In your PR cdf and pdf use sum and products. We need to check which are valid for more than bivariate.

ev copulas are only BV and more difficult to extend, left to distant future.

But some of the archimedean are easier to extend to multivariate, even if we don't do it right away. e.g.
Generic cdf does not have a dimension restriction.
Generic pdf requires higher order derivatives of generator function, which should be possible in some cases to at least a few more dimensions.
MLE is generic, but I haven't looked at fit when using kendallstau to estimate correlation in archimedean

@josef-pkt

Copy link
Copy Markdown
Member Author

continuous in #7296 with copula folder

@tupui tupui mentioned this pull request Feb 5, 2021
1 of 3 tasks
@josef-pkt

Copy link
Copy Markdown
Member Author

closing superseded by #7296 which has been merged

copula continuous with #7254

@josef-pkt josef-pkt closed this 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